Jones
Jones

Reputation: 197

Using jQuery to update a span element with form input data but its not updating

I have an h2 element which has styled content (css) inside this I also have a span element called highlight. I want to update this with a text input on the submit button being clicked.

the result I get (on click) is the original text clears out, then is refreshed into the span again so it still shows "John Smith".

//index.html
<span id="highlight">John Smith</span>
<form action="" class="form-inline">
   <input id="name" type="text" placeholder="Enter name" size="35">
   <input type="submit" value="Submit" class="button-btn">
</form>

//app.js 
$(function(){
    let name = $('#name').val();
    $('.button-btn').click(function(){
        $('#highlight').text(name);
    });
});

Its getting frustrating as I think I am doing it right, but obviously not. Thank you in advance for a resolution.

Upvotes: 0

Views: 294

Answers (1)

Mamun
Mamun

Reputation: 68933

The reason is you are taking the value of the input element on page load and the value is empty. You should take the value from the input inside the click event handler function:

$(function(){
  console.log($('#name').val() === ""); //true
  $('.button-btn').click(function(e){
    let name = $('#name').val();
    $('#highlight').text(name);
    e.preventDefault(); // prevented the submission of the form for demo
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="highlight">John Smith</span>
<form action="" class="form-inline">
   <input id="name" type="text" placeholder="Enter name" size="35">
   <input type="submit" value="Submit" class="button-btn">
</form>

Upvotes: 2

Related Questions