0

I have a dynamic loop pulling data from a sql table. How can I get the value of the specific mile_id saved into a js variable when the delete button is pressed? It is noted that there will be multiple forms due to the form being inside the loop.

FORMs

while($row = mysqli_fetch_array($result)){
  echo '
  <form>
    <input type="hidden" id="mile_id" value="'.$row['mile_id'].'" />
    <input type="button" id="delete" value="DELETE'.$i.'" />
  </form>';
}

JS

$(document).ready(function(){
  $('form #delete').click(function(e){
    var $mile_id = $('#mile_id') // this returns [object Object]
    var yes = confirm("Are you sure?");
    if (yes){
      alert($mile_id);
    }
    else{
      return false;
    }
  });
});
Rob
  • 69
  • 1
  • 9
  • 2
    It returns `[object Object]` because you're using `alert` and everything gets stringified. Use `console.log` for debugging. – elclanrs Jan 20 '14 at 20:10
  • id's need to be unique, every row will have an input with an id of mile_id. And look into `val` from jquery to get the value of an input. – John V. Jan 20 '14 at 20:12

4 Answers4

1

This answer might be interesting for you in order to retrieve the value from the selected element.

Community
  • 1
  • 1
Jim Aho
  • 9,932
  • 15
  • 56
  • 87
0

You dont need hidden input as you can use data-value and fetch the value in jquery.

while($row = mysqli_fetch_array($result)){
  echo '
  <form>
    <input type="button" class="delete" value="DELETE'.$i.'" data-value="'.$row['mile_id'].'" />
  </form>';
}

JS

$(document).ready(function(){
  $('form .delete').click(function(e){
  var $button = $(this) // this returns [object Object]
  var yes = confirm("Are you sure?");
  if (yes){
    alert($button.data("value"));
  }
  else{
    return false;
  }
 });
});
Harry Bomrah
  • 1,658
  • 1
  • 11
  • 14
0

use $('#mile_id').val() instead only $('#mile_id')

Hugo S. Mendes
  • 1,076
  • 11
  • 23
0

When you submit the form you can check the id in php. You can write a query serversided to delete the items where id = $_GET['mile_id'] (or $_POST).

But you're actually question was how to get value in js. you can achieve that with $("#mile_id").val();

But you wants:

$(this).find("#mile_id").val();

Edit: you can't have multiple forms because you're using id's. Make classes of the id's and make you're jquery right.

So:

$(document).ready(function(){
  $('form .delete').click(function(e){
    var $mile_id = $(this).find(".mile_id").val(); //this returns you wants
    var yes = confirm("Are you sure?");
    if (yes){
      alert($mile_id);
    }
    else{
      return false;
    }
  });
});
ArjanSchouten
  • 1,360
  • 9
  • 23