简体   繁体   中英

Calling jQuery's AJAX function inside of each

I'd like to have it so that for each button inside the table row that is clicked on, the value of the accompanying input field is fetched and sent along as data to a PHP file that executes a query.

<script type="text/javascript">
    $("tr").each(function() {
          var password = $(this +" td input").val();

          $(this +" td button").click(function(){
              $.ajax({  
                  type:"POST",  
                  url:"script.php",  
                  data:"password="+ password,
              });
          });
     });
</script>
<?php
      for($i=0;$i<10;$i++) {
           echo "<tr>
                     <td>
                         <input type='text' maxlength='15' value=''/>
                        <button>Change</button>
                     </td>
                </tr>";
      }
?>

I can't seem to select the input field and button in each row though. Any ideas?

You can't concatenate an object with a string like that and get a valid selector.

You would need to do something like either of these:

$(this).find('td input')
$('td input', this)

In addition, the loop is unnecessary. I would simplify like this:

$('button').click(function (e) {
    e.preventDefault();

    $.ajax({
        type: "POST",
        url: "script.php",
        data: "password=" + $(this).siblings('input[type=text]').val(),
    });

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM