How to add additional data in my JQUERY submit?

前端 未结 3 1561
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-15 14:26

In my razor view, I\'m using a Html.BeginForm. In it I have two elements where when I set clic, should submit the form but I need to add an additional string pa

相关标签:
3条回答
  • 2021-01-15 14:49

    You could add a hidden input with the name and value you require in your form. This value will be submitted along with all the other form items.

    <input type="hidden" name="someName" value="someValue" />
    

    Edit for comment:

    If you give each of your submit buttons the value as an attribute you could grab it in the click handler and then append a hidden field with the value inside the form. Something like:

    $(function(){
       $('#form input[type=submit]').click(function(e) {
           var val = this.getAttribute("data-param");
           $(this).closest('form').append('<input type="hidden" name="param" value="' + val + '" />");
       });
    });
    

    Untested, just a hunch. Hope that the form submit event does not get fired before the button click event. Also you will need to handle the enter event and key press etc.

    Why don't you want to use ajax?

    0 讨论(0)
  • 2021-01-15 14:51

    On your form sumbit try like this:

            $("form").submit(function(){
               $.ajax({     
                    type: 'POST',  
                    url: "/Quiz/Index",
                    dataType: "json",
                    data: $("form").serialize() + '&parameter=param1' ,   
                    success: function () { 
                        alert("Successful"); 
                    }
                    error: function(){
                        alert('error');
                    }
    
                }); 
            });
    

    Hope it helps.


    Edit

    Try like this in your jQuery function:

    $('form').append('&param=a');
    
    0 讨论(0)
  • 2021-01-15 14:58

    Based on your comments, the easiest thing for you to do is make your buttons of type submit and give them a name. If they have a name, the value of the button that is clicked will be sent automatically with the form post, see: sending form's submit button's value?

    Example:

    When the a button is clicked, parameter will be posted with value a. Likewise for b and c. If the none button is clicked, no value will be sent and parameter will be null (shown for demonstration purposes, you may not need this).

    @using (Html.BeginForm("Index", "Quiz", FormMethod.Post, new { id = "form" }))
    {
        ...
    
        <input type="submit" value="a" name="parameter" />
        <input type="submit" value="b" name="parameter" />
        <input type="submit" value="c" name="parameter" />
        <input type="submit" value="none" />
    }
    
    0 讨论(0)
提交回复
热议问题