If radio button checked, then submit to different

2020-04-20 12:15发布

问题:

I have this:

<form method="post" id="kl" action="step2.php">

<input type="radio" name="rubrik" value="bussines"></input>
<input type="radio" name"rubrik" value="private"></input>

<input type="image" value="submit" src="/images/submit.png" alt="Submit" />

</form>

What i bassicaly want is: When the second radio button is checked, to submit the form to step2a.php, a different file. How can i do this? Jquery, Javascript, php?

回答1:

You could do this with JavaScript (bind a submit listener that checks the value of the radio button and then sets the action property of the form), but it would be simpler and more reliable to do something (server side) along the lines of:

<form ... action="step-selector.php">

and

<?php
    if (isset($_POST['rubrik']) && $_POST['rubrik'] == 'bussines') {
        include('step2.php');
    } elseif (isset($_POST['rubrik']) && $_POST['rubrik'] == 'private') {
         include('step2a.php');
    } else {
         include('error-state.php');
    }
 ?>


回答2:

you can do this by modifying the Form into:

<form method="post" id="kl" action="step2.php">

<input type="radio" class="radio" rel="step2.php" name="rubrik" value="bussines"></input>
<input type="radio" class="radio" rel="step2a.php" name"rubrik" value="private"></input>

<input type="image" value="submit" src="/images/submit.png" alt="Submit" />

</form>

I added rel attribute to radio buttons. each has a value of the url. I also added a class to get the element with jQuery.

Now, you will need some Javascript, i will use jQuery code:

$('.radio').click(function (){
   rad = $(this);
   radRel = rad.attr('rel');
   $('form#kl').attr('action', radRel);
});


回答3:

There are multiple ways of doing it, depending on what you want exactly.

Check this one out, it might help you get there; Radio Button to open pages



回答4:

You can use form.submit() as onclick-handler (not onchange) and change the action, too.

<input type="radio" name"rubrik" value="private" onclick="this.parentNode.action='yourOtherFile.php'; this.parentNode.submit()"></input>