jQuery. Get text input field's value on button clicking event? -


html:

<div id="search">   <input id="term" type="text" value="enter search" />   <button id="hit" type="button" name="">search</button> </div> 

jquery:

$(document).ready(function() {   var term = $('#term').val();   $('#hit').click(function() {     alert(term);   }); }); 

the problem , no matter type in input field, hit button, alert original input value "enter search".

how can fix it?

the problem you're having whole block of code gets executed on dom ready event.

var term = $('#term').val(); being evaluated once , storing 'enter search' in term variable. why no matter change value to, variable still holds initial value when page rendered.

instead should more following:

jquery

$(document).ready(function() {   $('#hit').click(function() {     alert($('#term').val());   }); }); 

in bit of code, value of element id term evaluated when click event listener fires.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -