简体   繁体   中英

jQuery display text input on page

I have a form with a text input field and a button. What I am trying to achieve is that after the user types something in the text input field and clicks the button, the text he typed in the box will be displayed in the span underneath the form. For some reason it doesn't work and I am trying to figure out why.

My HTML:

             <form>
                <input type="text" id="textInput">
                <button id="submitButton" class="btn btn-primary">Submit</button>
             </form>

                <span id="guests"></span>

My JS/jQuery:

$(document).ready(function() {
    $("#submitButton").on("click", function() {
        var input = $("#textInput").val()
        $("#guests").html(input)

    })
});

The JS file in which I have my JS code is linked in the head like this:

<head>

<script src="guestList.js"></script>

</head>

You will need Event.preventDefault(); .

Every time you click on button, page is being refreshed so no value is displayed. Default action of <Button> is to submit the form hence page is reloaded(Submitted).

Another easier option would be to set type = "button" hence button will not act as Submit button.

 $(document).ready(function() { $("#submitButton").on("click", function(e) { e.preventDefault(); var input = $("#textInput").val() $("#guests").html(input) }) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input type="text" id="textInput"> <button id="submitButton" class="btn btn-primary">Submit</button> </form> <span id="guests"></span> 

Your button submits the form so page refreshes. Just set Button type as type="button"

>  <button id="submitButton" type="button" class="btn btn-primary">Submit</button>

HTML:

<form>
    <input type="text" id="textInput">
    <input type="submit" value="Submit" id="submitButton">
</form>

<span id="guests"></span>

JQuery:

$( document ).ready( function() {
    $( "form" ).submit( function(e) {
        e.preventDefault();
        var input = $( "#textInput" ).val();
        $( "#guests" ).html( input )
    })
});

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