根据用户选择将值从JavaScript发送到php文件

时间:2018-02-08 09:50:34

标签: javascript php jquery html html5

我正在将值从Javascript发送到php文件,它在收集完所有值后工作正常。

Step1工作正常,因为这两个字段都是必填字段,而在第二步中它是在选择所有字段时发送值。但是在step2中有一些条件元素,比如第一个选项pillers“yes”是,它不会要求第二个值,但我的代码期望所有值一起发送,我如何根据用户选择发送值以及其他值为false还是null?

function btnSubmit(step,userid)
{

 //If Step 1
    if(step == 'step1') {
        var Name = document.getElementById("name").value;
        var DoB = document.getElementById("thedate").value;
        //Create a Variable catVar Having the Var Name and Var DoB Concatinated with a --

        var catVar = Name + "--" + DoB;

    }
    else if(step == 'step2') {

         var pillers = document.getElementById("point1pillers").value;
         var pillersthird = document.getElementById("point3pillers").value;
         var  old = (document.querySelector("[name=status2]:checked").value);
         var  together = (document.querySelector("[name=status3]:checked").value);
         var  left = (document.querySelector("[name=status4]:checked").value);

         var catVar = pillers + "--" + pillersthird + "--" + old + "--" + together + "--" + left;
    }
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {

    }
  }
xmlhttp.open("GET","/wp-content/themes/xerius_main/kinderbijslag_calculator/validations/btnSubmit.php?q="+step+"&q2="+userid+"&q3="+catVar,true);
xmlhttp.send();
}

2 个答案:

答案 0 :(得分:0)

您应该检查网址的q3参数值。 但是对于你的问题,你可以尝试测试pillers值

  var pillers = document.getElementById("point1pillers").value;
    var catVars = '';
    if (pillers === 'yes') {
        // get other fields
        catVar = pillers + "--" + pillersthird + "--" + old + "--" + together + "--" + left;
    } else {
        // get other fields
        catVars = 'the value when pillers is not yes'; 
    }

答案 1 :(得分:0)

如果未设置值并且未选中复选框,则只需将所有变量的默认值设置为null希望它可以帮助您

    if(step == 'step2') {
    var pillers = document.getElementById("point1pillers").value;
    if (pillers.length < 1)
        pillers = null;
    var pillersthird = document.getElementById("point3pillers").value;
    if (pillersthird.length < 1)
        pillersthird = null;
    var old = (document.querySelector("[name=status2]:checked") != null ?
        document.querySelector("[name=status2]:checked").value : null);

    var together = (document.querySelector("[name=status3]:checked") != null ? document.querySelector("[name=status3]:checked").value : null);

    var left = (document.querySelector("[name=status4]:checked") != null ? document.querySelector("[name=status4]:checked").value : null);


    var catVar = pillers + "--" + pillersthird + "--" + old + "--" + together + "--" + left;
}