Javascript 空字段验证 - 无法读取未定义的属性“值”

Javascript Empty field validation - Cannot read property 'value' of undefined

本文关键字:未定义 属性 读取 字段 验证 Javascript      更新时间:2023-09-26

我已经研究了几天,并从这里举了几个例子来验证日期字段,以确保它在移动到下一页之前不为空。 但不断得到无法读取未定义的属性,并且我已经尝试使用Joomla构建验证.js 它在这个自定义组件中不起作用, 我希望在这里得到一些帮助来解决这个问题。

这是 JavaScript

nextpage:function(){
var deliveryy=document.getElementsByName("customPlugin")[0].value;
    if(delivery == "" || delivery == null) {
    alert("filled out All Delivery Date & Time"); 
return false; } else { .........

这是点击按钮

<button type="button" id="productbuilder_next" class="productbuilder_pagination pbbutton btn" onclick="productbuilder.nextpage();"> Next</button>

这是我尝试验证它不为空的字段的原始数据

<input id="<?php echo $class.$rand ?>" class="required <?php echo $class ?>" required="true" type="text" value="" size="<?php echo $this->params->custom_size ?>" name="customPlugin[<?php echo $viewData[0]->virtuemart_customfield_id ?>][<?php echo $this->_name?>][comment]"><?php if($this->params->custom_populate_alternate_field){?>&nbsp;<input type="text" id="alternate<?php echo $rand?>" size="30">

生成

<input id="vmcustom-datetime1930516000" class="required vmcustom-datetime hasDatepicker" required="true" type="text" value="" size="10" name="customPlugin[176][datetime][comment]">

您正在寻找 DOM 中不存在的名称。这样,当您访问属性值时,它将引发此错误。

可以在此处使用类。只需在元素中添加一个类并在函数中搜索它。

.HTML:

<input id="vmcustom-datetime1930516000" class="required validDelivery vmcustom-datetime hasDatepicker" required="true" type="text" value="" size="10" name="customPlugin[176][datetime][comment]">

.JS:

var validDelivery = document.getElementsByClassName("validDelivery")[0].value;

JSFiddle: http://jsfiddle.net/t1g7cfrb/1/

试一试,让我知道它是否有帮助!

元素的名称是"validDelivery customPlugin[176][datetime][comment]"

你想用getElementsByName("customPlugin")来处理它。这是不正确的。

例如,您可以将类 customPlugin 添加到元素并使用 getElementsByClassName("customPlugin")[0] 处理它。