What are the ways to get and render an input value using jQuery?
Here is one:
//Get
var bla = $('#txt_name').val();
//Set
$('#txt_name').val(bla);
There is one important thing to mention:
$("#txt_name").val();
will return the current real value of a text field, for example if the user typed something there after a page load.
But:
$("#txt_name").attr('value')
will return value from DOM/HTML.
For those who just like me are newbies in JS and getting undefined
instead of text value make sure that your id
doesn't contain invalid characters.
Try this. It will work for sure.
var userInput = $('#txt_name').attr('value')
To get the textbox value, you can use the jQuery val()
function.
For example,
$('input:textbox').val()
– Get textbox value.
$('input:textbox').val("new text message")
– Set the textbox value.
You have to use various ways to get current value of an input element.
METHOD - 1
If you want to use a simple .val()
, try this:
<input type="text" id="txt_name" />
Get values from Input
// use to select with DOM element.
$("input").val();
// use the id to select the element.
$("#txt_name").val();
// use type="text" with input to select the element
$("input:text").val();
Set value to Input
// use to add "text content" to the DOM element.
$("input").val("text content");
// use the id to add "text content" to the element.
$("#txt_name").val("text content");
// use type="text" with input to add "text content" to the element
$("input:text").val("text content");
METHOD - 2
Use .attr()
to get the content.
<input type="text" id="txt_name" value="" />
I just add one attribute to the input field. value=""
attribute is the one who carry the text content that we entered in input field.
$("input").attr("value");
METHOD - 3
you can use this one directly on your input
element.
$("input").keyup(function(){
alert(this.value);
});