hiDayurie
hiDayurie

Reputation: 92

jQuery Get Value From Looping in PHP

I'm using jQuery. Now I want to get value base on ID value from textbox loop.

Example :

<?php
while
{
$id = $d['id'];
?>
<input type="text" name="text" id="txt" value="<?php echo $id; ?>"/>
<input type="submit" class="btn_confirms" id="txt<?php echo $id; ?>" value="Go"/>
<?php
}

and jQuery like this:

$(function() {
$(".btn_confirms").click(function()
{
var txt_id = $('#txt').val();
alert(txt_id);
}
});

Example if I have 3 data. The problem is, when I click button Go, it just show first value of PHP loop. Another button Go 2 & 3 is show same value.

Any help, please.

Upvotes: 0

Views: 1288

Answers (2)

Satish Sharma
Satish Sharma

Reputation: 9635

you can try this

<?php
while
{
    $id = $d['id'];
?>
    <input type="text" name="text" id="txt<?php echo $id; ?>" value="<?php echo $id; ?>"/>
    <input type="submit" class="btn_confirms" id="btn<?php echo $id; ?>" textbox_id="#txt<?php echo $id; ?>" value="Go"/>
<?php
}
?>
<script>
$(function() {
    $(".btn_confirms").click(function()
    {
        var textbox_id = $(this).attr('textbox_id');
        var textbox_val = $(textbox_id).val();
        alert(textbox_val);
    });
});
</script>

DEMO

Upvotes: 0

Shomz
Shomz

Reputation: 37711

You can't have duplicate IDs on the page, they should be unique. For repeating elements either use classes, or make IDs unique (like you're doing for the buttons).

Something like this should work:

<input type="text" name="text" id="txt<?php echo $id; ?>" value="<?php echo $id; ?>"/>
<input type="submit" class="btn_confirms" id="button<?php echo $id; ?>" value="Go"/>

Then, to fetch the id of the input field from the click function, you can do something like this:

$(".btn_confirms").click(function()
{
    var txt_id = $(this).attr('id').replace('button', 'txt');
    var value = $('#'+txt_id).val();
    alert(txt_id + ": " + value);
})

See it here: http://jsfiddle.net/shomz/R9s2R/

Upvotes: 3

Related Questions