0

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>
1
  • you include the jquery before your js file? Commented Apr 29, 2018 at 9:33

3 Answers 3

2

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>

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

3 Comments

Did you tried executing snippet ? I could see it working. Did you find any error in console ?
Nevermind, it worked after I removed the Event.preventDefault(); and used type="button".
@merkur0 - You had to put e.preventDefault(). And do not miss passed Event parameter as e. Glad it helped.
1

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>

Comments

1

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 )
    })
});

Comments

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.