0

I have an input and two buttons, each of which are supposed to change the text within the input field. If I put the single line of code within onclick directly, it works perfectly. If I move the line to a separate function and attempt to call it via onclick, nothing happens, and I don't know why.

I've looked at many other SO questions about onclick, but none of them seemed to help with this. I'm stumped. JSFiddle is here: https://jsfiddle.net/wjw00h44/2/

Relevant code:

<div class="container">
    <div class="row">
        <div class="col-sm-8">
            <input type="text" class="form-control" id="noun-sentence" placeholder="Enter a sentence here">
        </div>
        <button type="button" class="btn btn-default" onclick="document.getElementById('noun-sentence').value = 'go away'">Check</button>
        <button type="button" class="btn btn-default" id="noun-button" onclick="changeWords()">Check2</button>
    </div>
    <p id="test_p"></p>
</div>

<script>
    function changeWords() {
        document.getElementById('noun-sentence').value = 'go away';
        return false;
    }
</script>
2
  • 1
    It works: jsfiddle.net/gerardofurtado/d876kfdx/1 Commented Jul 23, 2016 at 14:49
  • It sure does, I had the load type of the javascript wrong. My real code still didn't work until I stripped it down to just this, so my problem must be elsewhere. Thanks for the sanity check. :) Commented Jul 23, 2016 at 19:06

1 Answer 1

2

In js fiddle, click on the settings gear icon in the javascript window and change how the script loads. Don't put it in either of the 'on' events, but either directly in the head or body elements. Then click 'run' and try again.

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

2 Comments

That works! My real code still didn't work until I stripped it back down to just the code I used in the fiddle, but then it's fine so my problem must be elsewhere. Thank you!
I saved this on my machine and opened it in safari and it worked with both button clicks just fine, I don't see any browser-specific reasons why it wouldn't do it in others too: pastebin.com/xVWyczBg

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.