0

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?

.prev doesnt work as there is a span directly after input

example

js

$('button').click(function () {


var inputcontent = $(this).prev('input').attr('id');
console.log(inputcontent);

});

html

<input type="text" id="1">
<span class="input-group-btn">
<button type="button">Go!</button>
</span>

1 Answers1

3

You need to use .parent() here since input is the immediate previous sibling of parent <span> of the button:

var inputcontent = $(this).parent().prev().attr('id');

Fiddle Demo

Side note: id started with number is invalid HTML4 markup. Reference

Community
  • 1
  • 1
Felix
  • 37,892
  • 8
  • 43
  • 55