Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery get id from element

Tags:

html

jquery

I have a problem in Jquery. Here's part of my code in php file.

echo '<form action="add.php" method="post" id="'.$data["pro_id"].'">';
echo '<input style="display:none" type="text" name="img_link" value="'.$data["img_link"].'">';                   
echo '<input style="display:none" type="text" name="pro_url" value="'.$data["pro_url"].'">';
echo '<input style="display:none" type="text" name="pro_price" value="'.$data["pro_price"].'">';                    
echo '<input style="display:none" type="text" name="total_fb" value="'.$data["total_fb"].'">';                    
echo '<input style="display:none" type="text" name="pro_id" value="'.$data["pro_id"].'">';
echo '<input style="display:none" type="text" name="pro_name" value="'.$data["pro_name"].'">';
echo '</form>';

I need to submit the form but stay on the same page so I used the code below. It really works on not turning to other page but how can I get the ID of this form? When I output id but the result will be NoneType.

$('form').live('submit', function() {
  $.post($(this).attr('action'), $(this).serialize(), function(response) {
    var id = $(this).attr('id');
    document.write(id);
  }, 'json');
  return false;
});
like image 793
許家瑄 Avatar asked Jun 25 '26 13:06

許家瑄


1 Answers

You're using the right approach, but your issue is that this in the $.post() call does not refer to the element which triggered the submit event. As such you need to move that line in to the outer scope.

There's also a couple of things which need addressing here. Firstly note that live() was deprecated a long time ago. You should check what version of jQuery you're using, as it should be at least 1.12.1, or better still 3.3.1 (at time of writing), and you should be using on() instead.

Secondly you should not use document.write(). Instead you could select the element to be updated using jQuery then call html() on it. Try this:

$(document).on('submit', 'form', function(e) {
  e.preventDefault();
  var id = this.id;
  $.post(this.action, $(this).serialize(), function(response) {
    $('#targetElement').html(id);
  }, 'json');
});
like image 190
Rory McCrossan Avatar answered Jun 28 '26 06:06

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!