Reputation: 69
not sure if this is even possible, I have a page with mutiple inputs,each input has a button. is there anyway of getting the inputs value on button click, without hardcoding the inputs id?
example
js
$('button').click(function () {
var inputcontent = $('input').prop('id');
console.log(inputcontent);
});
html
<input type="text" id="1">
<button type="button">Go!</button>
<input type="text" id="2">
<button type="button">Go!</button>
<input type="text" id="3">
<button type="button">Go!</button>
<input type="text" id="99">
<button type="button">Go!</button>
Upvotes: 3
Views: 1316
Reputation: 34416
You're not targeting the item that you want the id from, the input just prior to the button. Use prev(0 to do that. In addition, id is really an attribute, not a property, so you should do this -
$('button').click(function () {
var inputID = $(this).prev().attr('id'); // gets the id of the input that precedes the button
console.log(inputID);
});
Upvotes: 0
Reputation: 5123
You already doing it right, just change a little bit in your code. You have to find out the value of the input field, which is placed just before your button on which you will click. So your code should be:
$('button').click(function () {
var inputcontent = $(this).prev().prop('id');
console.log(inputcontent);
});
Upvotes: 1
Reputation: 2257
This'll solve the issue
$('button').click(function () {
var value = $(this).prev().val();
console.log(value);
});
Upvotes: 0
Reputation: 82231
$('input').prop('id')
returns id of first matched element in selector. To target the input before each button, you need to use .prev()
along with $(this)
.
Try this:
$(this).prev().attr('id');
Upvotes: 3