The value of the JQUERY input field to store in a variable

I can not commit the value entered by the user in the text box to a variable.

I don't want to use <form> , is there any other way to do this?

  <html> <head> <style> p { color:blue; margin:8px; } </style> <script src="http://code.jquery.com/jquery-latest.js"></script> </head> <body> <input type="text" id="txt_name" /> <script type="text/javascript"> value = $("#txt_name").val(); $("#dom_element").text(value); </script> </body> </html> 
+7
source share
3 answers

If you want to get the value that the user enters, you need to do this in response to some kind of event. The keyup event occurs (believe it or not) when the user types and issues the key. If you mask the keyboard, you can update your variable with every keystroke, but you must also catch the β€œchange” to allow insertion and drag-and-drop changes that do not use the keyboard. The change event occurs when a user changes a field, and then clicks or tabs from it.

In addition, at the moment, your value variable is global, but if all you use for it is to set the value of another field, you do not need it at all:

 $("#txt_name").on("keyup change", function() { $("#dom_element").text(this.value); }); // OR, if you need the variable for some other reason: $("#txt_name").on("keyup change", function() { var value = this.value; // omit "var" to make it global $("#dom_element").text(value); }); 

Note that there will be a dom element in the this event handler function, so you can and should get its value directly without jQuery.

If you are using an older version of jQuery, use .bind() instead of .on() .

+11
source

do you mean this?

Script:

 jQuery(function(){ $("#txt_name").keypress(function() { var value = $("#txt_name").val(); $("#myDiv").text(value); }); }); 

HTML:

 <form> <fieldset> <input id="txt_name" type="text" value="Hello World" /> </fieldset> </form> <div id="myDiv"></div> 

I hope you will be helped.

+3
source
 <script> $('#txt_name').keyup(function(){ value = $("#txt_name").val(); $("#dom_element").val(value); }); </script> 

this is from api.jquery.com :

The .text () method cannot be used for input or scripting a form. To set or get the text value of input elements or textarea, use the .val () method. To get the value of a script element, use the .html () method.

As in jQuery 1.4, the .text () method returns the value of text and CDATA nodes, as well as element nodes.

+1
source

All Articles