After typing something in an input, and clicking on the button, ".val()" return an empty value, any idea why?
HTML CODE:
<div class="mainClass">
<div class="class1" >
<div class="class2">
<h3>Settings 1</h3>
<label>
<span>Text 1:</span>
<input type="text" name="text">
</label>
<label>
<span>Text 2:</span>
<input type="text" name="text2">
</label>
</div>
</div>
<div class="class3" >
<div class="class4">
<h3>Settings 2</h3>
<label>
<span>Text 1:</span>
<input type="text" name="text">
</label>
<label>
<span>Text 2:</span>
<input type="text" name="text2">
</label>
</div>
</div>
</div>
<button id="Go" class="go" >GO </button>
JAVASCRIPT CODE:
$('#Go').on('click', function() {
alert($('.class1 input').val()); //return an empty value
$('.class1 input').val("test");
alert($('.class1 input').val()); //return test
});
EDIT:
Even this doesnt work, and here i have only one input so I can't type in the wrong one:
<div class="mainClass">
<div class="class1" >
<div class="class2">
<h3>Settings 1</h3>
<label>
<span>Text 1:</span>
<input type="text" name="text">
</label>
</div>
</div>
</div>
<button id="Go" class="go" >GO </button>
EDIT 2: I found a beginning of the problem...
When I am doing that:
$('.class1 input').each(function () {
alert($(this).attr('name') + " value:" +$(this).val() );
});
I get two "alert" like this:
text value:
text value:myinputText
So two created for one in my HTML, the first one is empty and the second one work well!
Looking closely to my page, i found that all element are duplicated( <select,field, input...
)
Any idea how is that possible? Am i calling two time my html file? And all my code is in a popup( I don't know if it can help) (I am new in Javascript and jQuery)
Thanks
val() method is primarily used to get the values of form elements such as input , select and textarea . When called on an empty collection, it returns undefined . When the first element in the collection is a select-multiple (i.e., a select element with the multiple attribute set), .
attr('value') returns the value that was before editing input field. And . val() returns the current value. Save this answer.
There's more than one element matching '.class1 input'
. You probably didn't fill the first one of the set.
From the documentation :
Get the current value of the first element in the set of matched elements.
While val('text')
fills all matching elements :
Set the value of each element in the set of matched elements
Which is why you see something in your second alert.
You'd better use a more selective selector. Usually we use an id, or a name if a form is used to send the values to a server.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With