PHP/Javascript Checkbox to change form action when checked

被刻印的时光 ゝ 提交于 2021-02-19 07:42:29

问题


This is what I got:

<form action="invoiceCreate.php" method="post">
<input type="checkbox" name="business" id="business" vaulue="yes" />

Basically when I check the "business" checkbox, I want the form action to change to BusinessInoiveCreate.php instead of InvoiceCreate.php.

What would be the best way to do so?


回答1:


$('#business').on('change', function(){
    if ($(this).is(':checked')) {
        $('form').attr('action', 'BusinessInoiveCreate.php');
    } else {
        $('form').attr('action', 'invoiceCreate.php');
    }
});

Working demo: http://jsfiddle.net/eV7vY/




回答2:


Since it's not specified, here's a simple way to do it without jQuery. Depending on browser compatibility you may need to attach the event listener differently, but the general concept is the same.

HTML

<form name="myForm" action="invoiceCreate.php" method="post">
  <input type="checkbox" name="business" id="business" vaulue="yes" />
</form>

Javascript

var form = document.getElementsByName("myForm")[0];
var checkBox = document.getElementById("business");

checkBox.onchange = function(){
  if(this.checked){
    form.action = "giveEmTheBusiness.php";
  }else{
    form.action = "invoiceCreate.php";
  }
  console.log(form.action);
};

Or similarly, bind an event to the submit

form.onsubmit = function(){
  if(checkBox.checked)
      form.action = "giveEmTheBusiness.php"
  else
      form.action = "invoiceCreate.php";
};

EXAMPLE



来源:https://stackoverflow.com/questions/15815663/php-javascript-checkbox-to-change-form-action-when-checked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!