Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQUERY input field value to be stored in a variable

I am unable to capture the value typed by a user in the textbox into a variable.

I do not 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>
like image 763
user1114409 Avatar asked Dec 24 '11 13:12

user1114409


People also ask

How can we store data in variable in jQuery?

jQuery(element). data(key,value); // Store arbitrary data associated with the matched elements. or declare your variable outside the function.

How can we store textbox value in variable using jQuery?

To get the textbox value, you can use the jQuery val() function. For example, $('input:textbox'). val() – Get textbox value.

How do you assign a variable to the input field?

Sometimes we need to set a default value of the <input> element, This example explains methods to do so. This property set/return the value of value attribute of a text field. The value property contains the default value, the value a user types or a value set by a script.

How do I set the value of a element in jQuery?

jQuery val() Method The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element.


1 Answers

If you want to get a value that the user types then you need to do so in response to some kind of event. The keyup event occurs (believe it or not) when a user is typing and releases a key. If you trap keyup you can update your variable with every keystroke but you should trap "change" as well to allow for paste and drag'n'drop changes that don't use the keyboard. The "change" event occurs when the user modifies the field and then clicks or tabs out of it.

Also, at the moment your value variable is global, but if all you are using it for is to set the value of another field you don't 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 within the event handler function this will be the dom element so you can and should get its value directly without jQuery.

If you're using an old version of jQuery use .bind() instead of .on().

like image 194
nnnnnn Avatar answered Sep 28 '22 11:09

nnnnnn