4

I need to change the method attribute of my form with javascript (jQuery or pure).

My form has method="post", i try to change it with:

$("#submit-button").click(function(){ 
    var url = $('input[id=url]').val();
    var method = $('#method option:selected').val();
    $("#form-test").attr("action", url); 
    $("#form-test").attr("method", method);
    $("#form-test").submit();
});

This code works on Chrome and I8 but not on Firefox. The action is set correctly and also method variable contains "get" or "post" correctly. Any idea?

SOLVED: I was using an old version of jquery (copy&paste fault), i've upgraded to 1.7.1 and now it works, with the same code...

2
  • Is "form" the ID of your form ? Think you are missing this.
    – hop
    Feb 8, 2012 at 17:52
  • yes, form was the id of the form. now i changed to form-test
    – aberti
    Feb 8, 2012 at 20:01

4 Answers 4

15

this is my code, and it works just fine on both IE/FF/Chrome

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
function changeMethod() {
    $("#myPost").attr("method", "get");
}
</script>

<form method="post" id="myPost">
    <input type="text" name="abc" id="abc" value="Something" />

    <input type="submit" value="submit" onclick="changeMethod()" />
</form>
3
  • I've updated my code, now it should be equivalent to the your. But method is not changed.
    – aberti
    Feb 8, 2012 at 20:02
  • Which version of firefox are u running on? I tested on FF10. Maybe there are difference between versions.
    – Churk
    Feb 9, 2012 at 1:45
  • I was using FF8 but now i've upgrade to FF10. Seems to be the same... $("#form-test").attr("method", method); doesn't change the method attribute of the form.
    – aberti
    Feb 9, 2012 at 9:34
1

Try this:

$(function(){
    $("#form").attr("method", "get");
});
1

You need put code after you declaration of form.

<form id="form"> ... </form>
<script>
   $("#form").attr("method", "get");
</script>
3
  • I need to change at the submit time.
    – aberti
    Feb 8, 2012 at 20:06
  • Ok. test your $('#method option:selected').val() and view your return. If use select tag, remember, you need select item list to command work fine.
    – Jones
    Feb 8, 2012 at 23:19
  • Thanks Jones but i'm sure that $('#method option:selected').val() returns exactly what i expect.
    – aberti
    Feb 9, 2012 at 9:14
0

maybe you can write the code like this

$("#myPost").prop("method","get")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.