PHP / Javascript复选框在选中时更改表单操作

时间:2013-04-04 15:38:01

标签: php javascript checkbox postdata

这就是我得到的:

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

基本上,当我选中"business"复选框时,我希望表单操作更改为BusinessInoiveCreate.php而不是InvoiceCreate.php

最好的方法是什么?

2 个答案:

答案 0 :(得分:4)

由于没有指定,这里有一个简单的方法没有jQuery 。根据浏览器兼容性,您可能需要以不同方式附加事件侦听器,但一般概念是相同的。

<强> 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);
};

或类似地,将事件绑定到submit

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

EXAMPLE

答案 1 :(得分:3)

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

工作演示:http://jsfiddle.net/eV7vY/