Reputation: 87
I have a question getting the values from a textbox using jquery. My code is as follows:
<table width="500" border="0">
<tr>
<td><input type="text" class="quantity" /></td>
<td><input type="button" class="btn" p_id="item2" value="submit" /></td>
</tr>
<tr>
<td><input type="text" class="quantity" /></td>
<td><input type="button" class="btn" p_id="item3" value="submit" /></td>
</tr>
<tr>
<td><input type="text" class="quantity" /></td>
<td><input type="button" class="btn" p_id="item4" value="submit" /></td>
</tr>
</table>
<script>
$(document).ready(function(){
$('.btn').click(function(){
var p_id = $(this).attr("p_id");
var q_ty = $('#quantity').val();
$.post("updateQty.php",{p_id:p_id, q_ty:q_ty},function(result){
alert(result);
});
});
});
</script>
I have managed to get the ID for the items, but I can't get the values for the textbox that is selected.
Upvotes: 0
Views: 52
Reputation: 9561
Since all of your textboxes have the same ID, you won't be able to select the value of any particular one the way you are doing it.
Instead, you could get the closest <tr>
element based on the button that was clicked, then find the input and get the value that way.
Eg.
<table width="500" border="0">
<tr>
<td><input type="text" class="quantity-input" /></td>
<td><input type="button" class="btn" p_id="item2" value="submit" /></td>
</tr>
<tr>
<td><input type="text" class="quantity-input"/></td>
<td><input type="button" class="btn" p_id="item3" value="submit" /></td>
</tr>
<tr>
<td><input type="text" class="quantity-input" /></td>
<td><input type="button" class="btn" p_id="item4" value="submit" /></td>
</tr>
</table>
<script>
$(document).ready(function(){
$('.btn').click(function(){
var row = $(this).closest('tr');
var p_id = $(this).attr("p_id");
var q_ty = row.find(".quantity-input").val();
$.post("updateQty.php",{p_id:p_id, q_ty:q_ty},function(result){
alert(result);
});
});
});
</script>
Note, each input has a class to select on, rather than the id.
Upvotes: 1
Reputation: 4084
There are several input with id = quantity...I think you should change them so that you can differentiate by concat the p_id you find
<table width="500" border="0">
<tr>
<td><input type="text" id="quantity_item2" /></td>
<td><input type="button" class="btn" p_id="item2" value="submit" /></td>
</tr>
<tr>
<td><input type="text" id="quantity_item3" /></td>
<td><input type="button" class="btn" p_id="item3" value="submit" /></td>
</tr>
<tr>
<td><input type="text" id="quantity_item4" /></td>
<td><input type="button" class="btn" p_id="item4" value="submit" /></td>
</tr>
</table>
<script>
$(document).ready(function(){
$('.btn').click(function(){
var p_id = $(this).attr("p_id");
var q_ty = $('#quantity_' + p_id).val();
$.post("updateQty.php",{p_id:p_id, q_ty:q_ty},function(result){
alert(result);
});
});
});
</script>
Upvotes: 0