0

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.

1 Answer 1

2

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>

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

3 Comments

Thanks for your help. works great! not sure about e.preventDefault() but will google it
@Jones, you are most welcome, I have added that for demo purpose to stay on the same page, you can find more on that ....developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
Thank you helped greatly. My functionality is working great.

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.