简体   繁体   English

无法检查输入是否有价值

[英]Can not check if input has value or not

I want to loop through array of ids and check if value exists or not and do stuff code below: 我想遍历id数组并检查value是否存在,并在下面做一些代码:

function checkBillingFields() {

var inputIDS = [ "#billing_first_name", "#billing_last_name", "#billing_company", "#billing_phone", "#billing_address_1", "#billing_address_2", "#billing_city", "#billing_city"];

var arrayLength = inputIDS.length;

for (var i = 0; i < arrayLength; i++) {

    console.log(inputIDS[i]);

    if ($("inputIDS[i]").val().length == 0){

        $('.woocommerce-billing-fields__field-wrapper').appendTo('.billing-fields');

        $(".billing-heading").css({'margin-top': '100px'});

    }else{
        $(".expand-billing").css({'display': 'none'});
    }

}

}

checkBillingFields();

I get error Cannot read property 'length' of undefined. 我收到错误消息无法读取未定义的属性“长度”。 I use local storage to store inputs and it works fine tested. 我使用本地存储来存储输入,并且经过了良好的测试。

Any ideas are helpful as I been researching and trying to fix that but nothing worked. 在我进行研究并尝试解决该问题时,任何想法都很有帮助,但没有任何效果。

Replace your if statement with 将if语句替换为

if ($(inputIDS[i]).val().length == 0)

This will use jQuery directly with value from array and not with string literal as used in your case. 这将直接将jQuery与数组中的值一起使用,而不是与您的情况中所使用的字符串文字一起使用。

To really make sure you don't get any errors anymore, do it like this 要真正确保您不再遇到任何错误,请按照以下步骤进行操作

//First check if element actually exists in DOM
var tmp = $(inputIDS[i]);
if (tmp.length == 1 && tmp.val().length == 0) {

}

Just like your console.log() use the same in your if statement 就像console.log()if语句中使用一样

console.log(inputIDS[i]); 
if ($(inputIDS[i]).val().length == 0){

inputIDS[i] // returns #billing_first_name if i = 0 inputIDS[i] //如果i = 0,则返回#billing_first_name
"inputIDS[i]" would return "inputIDS[i]" "inputIDS[i]"将返回"inputIDS[i]"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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