3

Cant get my function to work and add the value of the button to the text field when clicked by user.

HTML

<form name="testing" action="test.php" method="get">Chords:
<textarea name="field"></textarea>
<input type="button" value="G" onClick="addToField('G');">
<input type="button" value="C" onClick="addToField('C');">
<input type="button" value="Am" onClick="addToField('Am');">
<input type="button" value="F" onClick="addToField('F');">

JavaScript

<script language="javascript" type="text/javascript">
    function addToField(crd){
        document.testing.field.value += crd;
    }
</script>

Really stuck trying to understand whats wrong here.

Hope this shows what I am trying to achieve: https://jsfiddle.net/034hyjo2/6/

3 Answers 3

2

You're accessing the object incorrectly

<script language="javascript" type="text/javascript">
    function addToField(crd){
        document.getElementByName("testing").value += crd;
    }
</script>

Or, give the element an ID and use getElementByID("testing").value. I usually find that works better anyway...

Sign up to request clarification or add additional context in comments.

Comments

2

If you're just getting it in the fiddle, it works by putting the script tag above your HTML:

<script>
    var addToField = function(c) {
        document.testing.field.value += c;
    };
</script>
<form name="testing" action="test.php" method="get">Chords:
    <textarea name="field"> </textarea>
    <input type="button" value="G" onClick="addToField('G');">
    <input type="button" value="C" onClick="addToField('C');">
    <input type="button" value="Am" onClick="addToField('Am');">
    <input type="button" value="F" onClick="addToField('F');">
</form>

Comments

0

Your JSFiddle is way wrong. You're question here is better. You want to be using document.getElementById('field').value += crd; instead of document.testing.field.value += crd;

try this:

<form name="testing" action="test.php" method="get">Chords:
    <textarea id="field" name="field"> </textarea> ---note the addition of the ID parameter
    <input type="button" value="G" onClick="AddToField('G');">
    <input type="button" value="C" onClick="AddToField('C');">
    <input type="button" value="Am" onClick="AddToField('Am');">
    <input type="button" value="F" onClick="AddToField('F');">
</form>

<script>
function AddToField(c) {
    document.getElementById('field').value += c;
};
</script>

Also functions shouldn't be camelCase but Pascal case ;)

1 Comment

Thanks Hugo, big help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.