Reputation: 59
This is just a sample, my program I am writing jQuery seems to be the better route with some of the features I am using. Anyways this is the issue. On my second div I click the edit button I want to alert the value of the text box when I click the edit button.
Yes this might be duplicate, however the answer from other stack questions have said for me to use the class instead of Id. Which I have, however the jquery only affects the first div. When I click edit on the first div it alerts 251. But when i click edit on the 2nd div it alerts 251 i want it to alert 351. Thanks Stack.
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(document).ready(function(){
$('.editdet').click (function() {
alert($('.addet').val());
});
});
</script>
</head>
<body>
<div class = "newbox">
<form class = "something">
<table>
<tr>
<td>
<input type="text" id="addet" class = "addet" value="251"/>
<input type="button" id="editdet" class = "editdet" value="Edit"/>
</td>
</tr>
</table>
</form>
</div>
<br>
<div class = "newbox">
<form class = "something">
<table>
<tr>
<td>
<input type="text" id="addet" class = "addet" value="351"/>
<input type="button" id="editdet" class = "editdet" value="Edit"/>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
Upvotes: 2
Views: 127
Reputation: 3503
use
<input onclick="edit()" type="button" id="editdet" class = "editdet" value="Edit"/>
with
<script>
function edit() {
alert($(this).prev().val());
}
</script>
Upvotes: 1
Reputation: 8246
This is because $('.addet')
is a collection of all the elements with the class name addet
.
Then when you're doing .val()
on the collection, it is grabbing the first value in the collection, which is the first one on the page, and therefore 251
You need to get the addet
that is relative to the editdet
you've clicked on. You can achieve this with the prev()
function:
$('.editdet').click (function() {
alert($(this).prev('.addet').val());
});
which will get the previous element.
Wherever your element is, you need to traverse the DOM structure relative to where the current element ($(this)
) is.
Some helpful jQuery functions for traversing the DOM structure
Upvotes: 4
Reputation: 531
Try this one,
$(".addet").each(function() {
alert($(this).val());
});
Upvotes: 0
Reputation: 591
You can try it with this code:
<script>
function edit() {
alert($(this).parent().find(".addet").val());
}
</script>
Upvotes: 0
Reputation: 5640
First of all you can't have similar ID. The second things is you don't target properly your value.
What you need to use is Sibiling/Previous Selector
$(document).ready(function(){
$('.editdet').click (function() {
alert($(this).prev().val());
});
});
In this specific case shall work
Upvotes: 3