Kyle Coots
Kyle Coots

Reputation: 2131

Target correct form input value Ajax and PHP

I have a script like this:

  $(function() {
     $(".btn_bookmark").click(function() {

   var name = $("input.???").val(); 
   base_url = '<?php echo base_url() ?>';

    $.ajax({
            url: base_url+"bookmark/bookmark_item/"+name,
            success: function() {
                    // do something on success
            }
         });
    return false;
    });
});

And my form is inside a PHP loop like so:

foreach($page->result() as $row){
   echo '<form name="" method="post" action="">';
   echo '<input type="hidden" name="'$row->name'" id="'.$row->id.'" size="30" value="'.$row->val.'" />';
   echo '<input type="submit" name="submit" class="btn_bookmark" id="submit_btn" value="Bookmark" />';
   echo '</form>';
}

The problem is each of the forms hidden input name, id, and value are different/dynamic from a MySQL database. So how would I select the correct value for the input?

Upvotes: 1

Views: 260

Answers (3)

Jim
Jim

Reputation: 22646

Rather than grabbing var name = $("input.???").val();

You can grab the hidden input like this:

$(this).parent().find('input[type=hidden]').val();

This gets the parent of the element triggering the event (in this case the form) then grabs the hidden input child of this parent.

Upvotes: 2

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

$(".btn_bookmark").click(function() {
    var name = $(this).prev().val();
    base_url = '<?php echo base_url() ?>';

    $.ajax({
            url: base_url+"bookmark/bookmark_item/"+name,
            success: function() {
                    // do something on success
            }
         });
    return false;
    });
});

This way you'll get the previous element, which is the hidden one.

Upvotes: 2

ssj1980
ssj1980

Reputation: 391

The implementation is different from yours, but it should work.

Try this:

foreach($page->result() as $row){
   echo '<form name="" method="post" action="">';
   echo '<input type="hidden" name="'$row->name'" id="bkmark'.$row->id.'" size="30" value="'.$row->val.'" />';
   echo '<input type="submit" name="submit" class="btn_bookmark" id="submit_btn" value="Bookmark" onClick="bookmarkThis(\'#bkmark' . $row->id . '\');" />';
   echo '</form>';
}

And your js will be:

$(function() {
     boomarkThis = function(someId) {
         var name = $(someId).val();
         base_url = '<?php echo base_url() ?>';

          $.ajax({
                url: base_url+"bookmark/bookmark_item/"+name,
                success: function() {
                        // do something on success
                }
             });
        return false;
        });
     }

Upvotes: 0

Related Questions