user3590304
user3590304

Reputation: 69

Get variable input value on button click

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

Answers (4)

Jay Blanchard
Jay Blanchard

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

Naveen Chandra Tiwari
Naveen Chandra Tiwari

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

akshaykumar6
akshaykumar6

Reputation: 2257

This'll solve the issue

$('button').click(function () {
    var value = $(this).prev().val();
    console.log(value);
});

Upvotes: 0

Milind Anantwar
Milind Anantwar

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');

Working Demo

Upvotes: 3

Related Questions