Home > Back-end >  How do I use the submit()-function to read out a form and show the content
How do I use the submit()-function to read out a form and show the content

Time:01-12

I want to use the submit()-function to read out a text from a form-field and display it again. But, upon pressing the submit-button nothing happens. With a diffrent event-handler like keyup() everything works fine. Any suggestions?

$(function() {
    $("#name")
    .on("submit", function(e) {
        e.preventDefault();
        var namenew = $(this).val();
        $("p.show").html("Hello <strong>"   (namenew)   "</strong>");
    });  
});
<section>
        <label for="name">Name</label>
        <input type="text" id="name">
        <input type="submit" id="submit">
        <p >Hello <strong>Unknown</strong></p>
    </section>

CodePudding user response:

The submit event is fired on a form, not an input.

So you need to put a form inside <section>, and bind the handler to that. Then you need to use $("#name").val() to get the value of the input.

$(function() {
  $("#myform")
    .on("submit", function(e) {
      e.preventDefault();
      var namenew = $("#name").val();
      $("p.show").html("Hello <strong>"   (namenew)   "</strong>");
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
  <form id="myform" action="#">
    <label for="name">Name</label>
    <input type="text" id="name">
    <input type="submit" id="submit">
  </form>
  <p >Hello <strong>Unknown</strong></p>
</section>

  •  Tags:  
  • Related