为什么我似乎无法正常实现此功能?

时间:2018-04-24 12:19:19

标签: javascript html function

我在外部.js文件中有一些代码如下:

function creditConfirm (){
 textboxVType = document.getElementById('textboxType');
 textboxVName= document.getElementById('textboxName');
 textboxVNumber = document.getElementById('textboxNumber');
 textboxVCode = document.getElementById('textboxCode');
 textboxVAmount = document.getElementById('textboxAmount');

 if (textboxVType && textboxVName && textboxVNumber && textboxVCode && textboxVAmount =! " "){
     alert("Accepted");
     //All items made null

 }
 else{
     alert("Try again");
 }
}

然后我也有一些HTML代码:

<p1> Credit card type: </p1>

<input type = "text" id "textboxType">

<h1> </h1>

<p1> Name: </p1>

<input type = "text" id "textboxName">

<h1> </h1>

<p1> Number: </p1>

<input type = "text" id "textboxNumber">

<h1> </h1>

<p1> Security code: </p1>

<input type = "text" id "textboxCode">

<h1> </h1>

<p1> Donation amount: </p1>

<input type = "text" id "textboxAmount">

<button onclick="creditConfirm()">Confirm</button>  

我尝试做的是,如果所有项目都已填写以打印第一个文本,如果缺少一个项目,则打印第二个文本并允许他们再次尝试。但是,当我进入网站时,要么填写所有方框,要么留下一个未填写的,然后单击确认按钮,没有任何反应。我处于一个非常基本的JavaScript级别,我们的老师似乎拒绝教我们所以我可能错过了一个非常明显的错误,任何人都可以发现任何会导致这种情况失效的事情

4 个答案:

答案 0 :(得分:2)

您没有正确检查if语句中的值元素。

在具有if(或&&)条件的||语句中,每个条件都必须完整且独立。

此外,要检查表单字段中的数据,您必须检查其value属性。

您还有=!而不是!=

if(textboxVType.value !="" && 
   textboxVName.value != "" && 
   textboxVNumber.value !="" && 
   textboxVCode.value !="" && 
   textboxVAmount.value != "") {}

答案 1 :(得分:0)

你要检查dom元素是否真实(只要你在html中声明它们就会一直存在),而不是检查它们是否有值集

将您的if更改为

if (textboxVType.value && textboxVName.value && textboxVNumber.value 
   && textboxVCode.value && textboxVAmount.value){
     alert("Accepted");
 }

答案 2 :(得分:0)

1)运营商=!不存在。 !=确实如此。

2)textboxVType textboxVName textboxVNumber textboxVCode textboxVAmount =! " "是4个不同的条件。你不能以这种方式分解条件。相反,您必须以这种方式编写textboxVType.value != " " && textboxVName.value != " " && textboxVNumber.value != " " && textboxVCode.value != " " && textboxVAmount.value != " " .value用于访问您获得的DOM元素的值。

3)如果您想检查文本框是否为空,请使用!= ""代替!= " "(仅检查文本框是否只包含空格)

答案 3 :(得分:0)

虽然我很感谢你刚开始使用JS,这可能略高于你的舒适区,但你可能会对写下来并分别检查输入ID的所有值的快捷方式感兴趣:

我们在此处使用querySelectorAll获取所有输入,然后使用some检查每个输入的值。如果其中任何一个为空,则会提示“已接受”,否则请再次尝试。

function creditConfirm() {
  const inputs = document.querySelectorAll('input');
  const emptyField = [...inputs].some(input => input.value === '');
  if (!emptyField) {
    alert("Accepted");
  } else {
    alert("Try again");
  }
}

Short demo on JSFiddle