If you want to read the text from an input box like this in jQuery, you can follow one of the following approaches :
1. Using val() function
Here is the syntax :
var str = $('#txt_name').val();
Example :
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { alert($("#txt1").val()); }); }); </script> </head> <body> <p id="p1">Enter text :</p> <input type="text" id="txt1" /> <br /> <br /> <button>Click me</button> </body> </html>
Output :
Note :
You can set a new value in the textbox using the val() method by passing the new text to the val() method as shown below :
$("#txt1").val("new text")
2. Using prop(‘value’)
We can also use $(“#txt1”).prop(‘value’) to read the text from the textbox.
$(document).ready(function() { $("button").click(function() { alert($("#txt1").prop('value')); }); });
3. JavaScript way
If you want to use JavaScript to get the value, you can use :
document.getElementById('txt_id').value
© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post