Reputation: 14250
I have a question regarding the user input field issue.
I am trying to grab the data from the input field after user enter something.
My html:
<div>texts here <input type='text'></input></div>
<div>
<table>
<tr>
<td>cell here</td>
<td>cell here</td>
</tr>
<tr>
<td>another cell here</td>
<td><input type='text'></input></td>
</tr>
</table>
</div>
My js
var test = $('input).val();
var test2 = $('input).html();
console.log(test)
console.log(test2)
Both of them will show the first texts that are entered in the first input field but not the second within the table.
Can someone please help me about it? Thanks a lot!
Upvotes: 0
Views: 930
Reputation: 15913
Give id's to your input fields and then extract .like
<td><input type='text' id='abc'></input></td>
the extract
var test = $('#abc').val();
Upvotes: 1
Reputation: 1115
try
$('input').each(function(){
var value = $(this).val();
console.log(value);
});
Upvotes: 0
Reputation: 28837
Give a unique ID to the inputs and your problem is solved.
<div>texts here <input id="input_one" type='text'></input></div>
<div>
<table>
<tr>
<td>cell here</td>
<td>cell here</td>
</tr>
<tr>
<td>another cell here</td>
<td><input id="input_two" type='text'></input></td>
</tr>
</table>
</div>
And then use:
var test = $('#input_one').val();
var test2 = $('#input_two').val();
console.log(test)
console.log(test2)
Another option, if you don't want to use ID but know their position in the DOM tree you can use:
var test3 = $('input').eq(0).val();
var test4 = $('input').eq(1).val();
Upvotes: 2
Reputation: 54619
$('input')
refers to a jQuery object with multiple elements, calling a function like val()
or html()
will return the value of the first matched element only.
To get all values you'd need to loop through each element in the object:
$('input').each(function(){
console.log($(this).val());
});
Upvotes: 2
Reputation: 6344
You really should add classes or identifiers to the input. That'll make it easier. For example:
<input type='text' class='name'/>
Then in jQuery:
$(".name").val();
Secondly, you can grab the individual values without changing your HTML like such:
var test = $("div > input").val();
var test2 = $("table input").val();
The reason your code wasn't working is becuase using a simple $("input") will get all of the input values. So, $("input").val() was returning the first .val() found by the selector, which is the first input.
Upvotes: 0
Reputation: 12341
Well, you're grabbing them incorrectly. As you're not identifying them with an id or class or anything like that, jQuery interpretes it as "the first input" in both cases.
var test = $('input').val();
var test2 = $('table input').val(); // Grabs the value of the
// input inside the table
console.log(test);
console.log(test2);
Upvotes: 1