skip to Main Content

I am starting up with Jquery and would like to do the following:

Submit and store a text with Jquery, and replace the text in the HTML with this.

How do I exactly do this?

    <section>
            <label for="name">Name</label>
            <input type="text" id="name">
            <input type="submit" id="submit">
            <p class="output">Hello <strong>Text that needs to be replaced</strong></p>
        </section>

I tried something like:

$(function () {
   $( "#name")
   .on ("submit", function() {
    let value = $(this ).val();
    $("strong").text( value );
  });
});

But this didn’t work. How can I achieve this?

2

Answers


  1. You have several mistakes in your javascript, it should be

    $(function () {
       $("#submit")
       .on("click", function() {
        const value = $("#name").val();
        $("strong").text( value );
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <section>
        <label for="name">Name</label>
        <input type="text" id="name">
        <input type="submit" id="submit">
        <p class="output">Hello <strong>Text that needs to be replaced</strong></p>
    </section>
    Login or Signup to reply.
  2. Try this code:

    <section>
            <label for="name">Name</label>
            <input type="text" id="name">
            <input type="submit" id="submit">
            <p class="output">Hello <span id='strong'>Text that needs to be replaced</span></p>
    </section>
    
    
      $( "#submit").on("click", function() {
        let value = $("#name").val();
        $("#strong").text( value );
      });
    

    Test it here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search