How do I get the value of a textbox using jQuery

In jQuery, there are multiple approaches available to retrieve the current value of an input element.

// use the id to select the element. $("#textfield").val();
// use to select with DOM element. $("input").val();
// use type="text" with input to select the element $("input:text").val();

The jQuery val() method serves the purpose of retrieving the value of an element. This function is versatile in both setting and retrieving values. When used to retrieve values, it returns the value attribute of the first element in the selection. Typically, the val() method is employed with HTML form elements for effective data manipulation.

<input type="text" id="textfield"> txtVal = $("#textfield").val()
run this source code Browser View
Full Source | jQuery
<!DOCTYPE html> <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> function getValue() { txtVal = $("#textfield").val() alert(txtVal); } </script> </head> <body> <input type="text" id="textfield"> <button type="button" id="btn" onclick="getValue()">Get Textbox Value</button> </body> </html>

Using JavaScript

If you want to use straight JavaScript to get the value, here is how:

document.getElementById('textfield').value

Using DOM element


Get value of an input text box with jQuery

The following method shows how you can use this one directly on your input element.

$(document).ready(function(){ $("#textfield").keyup(function(){ alert(this.value); }); });

Set the value in an input text box | jQuery

You can use various methods to set current value of an input element in jQuery.

// use to add "text content" to the DOM element. $("input").val("text content");
// use the id to add "text content" to the element. $("#textfield").val("text content");
// use type="text" with input to add "text content" to the element $("input:text").val("text content");
run this source code Browser View

Full Source| jQuery
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script type="text/javascript"> function setValue() { txtVal = document.getElementById('textfield').value $("#setTextfield").val(txtVal); } </script> </head> <body> <input type="text" id="textfield"> <button type="button" id="btn" onclick="setValue()">Set Textbox Value</button><br><br> <input type="text" id="setTextfield"> </body> </html>

Conclusion

To acquire the content of a textbox using jQuery, the val() method proves invaluable. By employing this method, you can seamlessly retrieve the value attribute of the specified input element, effectively obtaining the textbox's content for further processing.