简体   繁体   中英

JavaScript Form - changeable URL's for the submit button

I need to make a form, example:

<form id="myform" name="myform" method="get">
  <input type="radio" checked="checked" name="Answer" value="yes" />Yes
  <input type="radio" name="Answer" value="no" />No
  <input id="submit" name="submit" src="images/submit.jpg" type="image" />
</form>

Questions:

1. How can I set a URL to the submit button (on click)?

2. How can i change this URL depending on when the user selects either the Yes or No answer?

Set the form action attribute to the YES URL

$('input:radio').on('click', function(){
    if($(this).val() == "yes"){
        $('#myform').attr('action', 'YES_URL');
    }
    else {
        $('#myform').attr('action', 'NO_URL');
    }
});

A submit button fires the event submit to a adress that is defined in the action attribute from form tag. So here comes one option:

<script type="text/javascript">
function mytarget ()
{
  var myFormObject = document.myforma;
  var chk = false;
  for (i = 0; i < myFormObject.Answer.length; i++)
  {
    if (myFormObject.Answer[i].checked && myFormObject.Answer[i].value == 'yes')
    {
        myFormObject.action = "http://urltforthevalueYes.com";
        chk = true;
        break;
    } else if (myFormObject.Answer[i].checked && myFormObject.Answer[i].value == 'no') {
        myFormObject.action = "http://urltforthevalueNo.com";
        chk = true;
        break;
    }
  }

  if (chk == true) {myFormObject.submit();} else {alert("Please select an option");}
}
</script>

Update: I had to change my javascript code because there was two mistakes in there. Also added the new HTML code.

Changes you have to do:

  1. add the action attribute to the open form tag <form id="myform" name="myform" method="get" action="">

  2. Change the name of your submit button. The use of submit creates a conflict between your button and the javascript function <input id="send" name="send" src="images/submit.jpg" type="image" />

  3. Add at you submit button the attribute onClick with the reference to the method mytarget() <input id="send" name="send" src="images/submit.jpg" type="image" onClick="mytarget()"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM