1

I would like to change the form's action property when a button is clicked

I have two buttons in a form and when each button is clicked each should post data to own url.

html:

<form method="post">
<input type="button" value="Edit Selected..." />
<input type="button" value="Delete Selected..." />
...
</form>
KoolKabin
  • 17,157
  • 35
  • 107
  • 145
  • 2
    You'd be better off making those buttons into submits, giving them a name, then determining which one was clicked on the server. – Quentin Apr 04 '11 at 09:26
  • Why don't you use `if/else` to see that which value is received and process according to it. – Jack Billy Apr 04 '11 at 09:54

2 Answers2

4

using jQuery

<form method="post" id="form1">
<input type="button"  data-url="action2"  value="Edit Selected..." />
<input type="button" data-url="action1" value="Delete Selected..." />
...
</form>

script:-

$(document).ready(function(){

    $('input[type*="button"]').click(function(){
    var url = $(this).attr('data-url');


     $('#form1').attr('action',url);   

    });

});
Gowri
  • 16,587
  • 26
  • 100
  • 160
  • can we directly refer the form without using the #form1 just like by parent or form – KoolKabin Apr 04 '11 at 11:25
  • yeah sure, you can use $('form') – Gowri Apr 05 '11 at 03:37
  • no it won't.... to select particular form you need to correct selector here you can learn about selectors http://www.w3.org/TR/CSS2/selector.html in other way use id for form – Gowri Apr 05 '11 at 06:43
  • can't we just grab the form from the button inside it? – KoolKabin Apr 05 '11 at 06:50
  • modify that selector $('#form1 input[type*="button"]') here is working demo http://jsfiddle.net/HhMbV/ – Gowri Apr 05 '11 at 07:01
  • @KoolKabin: $(this).closest('form') will give you the correct form around the clicked button. **[closest](http://api.jquery.com/closest/)** is one of my favorite traversal methods :-) And please, don't curse on stackoverflow or Jesus. – Oliver Apr 16 '14 at 11:49
2

GOD it was so similar to native javascript that i missed it...

i am not sure its plane javascript or with jquery but i got the following code exactly as i needed and worked fine:

        $('#cmdDeleteButton').click(function(){
            this.form.action = "http://newurl.com";
        });
KoolKabin
  • 17,157
  • 35
  • 107
  • 145