jQuery form submit - how to append data?

2019-07-25 04:45发布

问题:

I have a form that I want to submit the standard way (not Ajax), using jQuery.

Here is my code:

<form id="myform" action="post.php" method="post">
  <input type='text' value='12' name="student_id"/>
  <button data-action="delete" class="form-button"><i class="icon-ok"></i>
  </button>
  <button data-action="approve" class="form-button"><i class="icon-ok"></i>
  </button>
</form>

$(document).ready(function(){

    $('.form-button').click(function(e){

    //which button clicked 
    var button_action = $(this).attr(" data-action");

    //how do I append button_action to post data??

    //submit form
    $("#myform").submit();

    });

});


How do I add the value "data-action" of the button that was clicked to the post parameters so that I an use it in my PHP file, to basically know which button was clicked?

回答1:

One easy way is to use a hidden input

<form id="myform" action="post.php" method="post">
    <!-- use this input to store the clicked button value -->
    <input type='hidden' name="action" />
    <input type='text' value='12' name="student_id" />
    <button data-action="delete" class="form-button"><i class="icon-ok"></i></button>
    <button data-action="approve" class="form-button"><i class="icon-ok"></i></button>
</form>

then

$(document).ready(function () {
    $('.form-button').click(function (e) {
        var $form = $("#myform");
        $form.find('input[name="action"]').val($(this).data("action"))

        $form.submit();
    });
});


回答2:

Submit buttons do this naturally, no need for scripting. If it has a name and value, a submit button will submit that name=value pair with the form if it is the one that is clicked.

Just add type="submit" name="action" to the <button> elements. and change data-action to value, or make value a duplicate of data-action.



回答3:

Use a hidden field,

<form id="myform" action="post.php" method="post">
  <input type='text' value='12' name="student_id"/>
  <input type='hidden' name="action"/>
  <button data-action="delete" class="form-button"><i class="icon-ok"></i>
  </button>
  <button data-action="approve" class="form-button"><i class="icon-ok"></i>
  </button>
</form>

Here is your Jquery,

$(document).ready(function(){

$('.form-button').click(function(e){

//which button clicked 
var button_action = $(this).attr(" data-action");

$('input[name="action"]').val(button_action);

//submit form
$("#myform").submit();

});

});