Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 991
user3590304 Avatar asked Apr 02 '26 08:04

user3590304


2 Answers

$('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

like image 134
Milind Anantwar Avatar answered Apr 03 '26 22:04

Milind Anantwar


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

 });
like image 35
Naveen Chandra Tiwari Avatar answered Apr 03 '26 22:04

Naveen Chandra Tiwari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!