when the is validated with jQuery?

How do I change the "action" of a <form> when the <radio> is validated with jQuery?

<form action="1.html">
    <input type="radio" id="check1" name="check" />
    <input type="radio" id="check2" name="check" />
</form>

      

What I want to implement:

when check2 is checked, change action to "2.html"

when the "check1" checkbox is checked, change the "action" value to "1.html"

+2


source to share


4 answers


This should take care of your problem.



$(function(){
    $('#check1').click(function() {
        $(this).parent().attr('action', '1.html');
    });

    $('#check2').click(function() {
        $(this).parent().attr('action', '2.html');
    });
});

      

+4


source


While the answers above are correct, you have to be careful doing this kind of thing.

For example, let's say you click check2. He changes the action. You submit a form or navigate to another page. You will now click the Back button.

The browser reloads the page *, resetting the form action to the value specified in the HTML. But! Browsers remember the previous values ​​set in the form fields, so check2 is still selected without receiving a click event: the state of the radio stations does not match the state of the action form.



To avoid such problems, you should always check the form values ​​on page load and update whatever depends on them.

In general, you should try to have one action, and the host script server decides what to do, not change the action on the fly. This avoids errors like above and stops form breaking for non-JS UA.

*: Firefox cannot reload the page if it is still stored in the DOM cache of the loaded page.

+2


source


The following should work:

$("#check1").click
(
  function()
  {
    $("form").attr("action", "1.html");
  }
);

$("#check2").click
(
  function()
  {
    $("form").attr("action", "2.html");
  }
);

      

0


source


$('[name="abc"][value="abc"]').click(function () {

$(".test").attr("action", "http://localhost/test.php");

});


$('[name="def"][value="def"]').click(function () {


$(".test").attr("action", "http://localhost/test1.php");


});



<form name="form" class="test" action="http://localhost/test.php">   
<input type="radio" name="abc" value="abc" />   
<input type="radio" name="def" value="def" />   
</form>  

      

0


source







All Articles