简体   繁体   中英

Basic Javascript onclick function call not working

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM