I have a table in which the information is generated automatically for each line I have a button which in turn has an input type = 'hidden' element:
<table>
<tr>
<td>ROW1</td>
<td>
<input type="hidden" id="id_1" value="1" />
<button id="bttn_1">DEL</button>
</td>
</tr>
<tr>
<td>ROW2</td>
<td>
<input type="hidden" id="id_2" value="2" />
<button id="bttn_2">DEL</button>
</td>
</tr>
<tr>
<td>ROW3</td>
<td>
<input type="hidden" id="id_3" value="3" />
<button id="bttn_3">DEL</button>
</td>
</tr>
</table>
If I press button 3 from the bttn_3 id then I can take the value from the hidden input with the id_3 id.
CodePudding user response:
You can do it like this:
$('button[id^=bttn_]').click(function() {
var val = $(this).siblings("input").val()
})
$('button[id^=bttn_]')
will select all buttons where the id
starts with bttn_
$(this).prev("input")
means that we will select the input that is associated with the button clicked.
Demo
$('button[id^=bttn_]').click(function() {
console.log($(this).siblings("input").val())
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>ROW1</td>
<td>
<input type="hidden" id="id_1" value="1" />
<button id="bttn_1">DEL</button>
</td>
</tr>
<tr>
<td>ROW2</td>
<td>
<input type="hidden" id="id_2" value="2" />
<button id="bttn_2">DEL</button>
</td>
</tr>
<tr>
<td>ROW3</td>
<td>
<input type="hidden" id="id_3" value="3" />
<button id="bttn_3">DEL</button>
</td>
</tr>
</table>