首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据填充的必填字段构建和操作数组

根据填充的必填字段构建和操作数组
EN

Stack Overflow用户
提问于 2015-12-03 06:00:48
回答 3查看 71关注 0票数 5

我正在尝试找出一种明智的方式来显示和操作尚未填充到表单中的必填字段数组/列表-这只是为了将此信息输出给用户,并在用户浏览和填充字段时从列表中删除每一项(作为一种进度指示器)。对如何最好地处理这个问题有什么想法吗?

我在想一些事情,大致如下:

代码语言:javascript
复制
var reqFields = [];

jQuery('label.required').each(function() {
    console.log(jQuery(this).text());

    reqFields.push(jQuery(this).text());
});

jQuery('.custom-field').on('input', function() {
    if (jQuery('.required-entry').filter(function() {
            return this.value.length === 0;
        }).length === 0) {
        // Remove this from the list/array
    } else {

    }
});
EN

回答 3

Stack Overflow用户

发布于 2015-12-03 06:09:25

在输入事件中,检查该值并相应地在数组中添加/删除项。

代码语言:javascript
复制
var reqFields = [];

jQuery('label.required').each(function() {
    console.log(jQuery(this).text());
    reqFields.push(jQuery(this).text());
});

jQuery('.custom-field').on('input', function() {
    if (this.value) {
        // Remove this from the list/array
        reqFields.splice(jQuery(this).index(),1);
        // jQuery(this).index() havent tried, else just compute index some other way
    } else {
       // add back if cleared out
       reqFields.push( jQuery('label.required').eq(jQuery(this).index()).text());
    }
});
票数 1
EN

Stack Overflow用户

发布于 2015-12-03 06:25:25

每次必填字段的输入发生变化时,您可以简单地将reqFields数组重新分配给输入为空的必填字段列表,而不是删除条目。

代码语言:javascript
复制
var reqFields = [];

jQuery(function() {
  jQuery('.requiredFields').on('input', function() {
    reqFields = jQuery('.requiredFields').filter(function() {
      return this.value.length === 0;
    });
  });
});
票数 1
EN

Stack Overflow用户

发布于 2015-12-03 06:54:05

检查下面的基本示例,在input上使用each遍历所有具有required-entry类的字段,并检查空字段,最终将消息附加到跨越#msg的字段,以通知用户哪些字段是必需的。

希望这能有所帮助。

代码语言:javascript
复制
$('.required-entry').on('input', function() {
    $('#msg').empty();
  
    $('.required-entry').each(function() {
         if ( $(this).val().length == 0 )
             $('#msg').append('Field <b>'+$(this).prev('label').text()+'</b> is required.<br/>');
    });
});
代码语言:javascript
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class='required'>First Name</label>
<input type='text' id='first_name' name='first_name' class='required-entry' required/>
<br/>
<label class='required'>Last Name</label>
<input type='text' id='last_name' name='last_name' class='required-entry' required/>
<br/>
<label class='required'>Email Address</label>
<input type='text' id='email' name='email' class='required-entry' required/>
<hr/>
<br/>
<span id='msg'></span>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34053911

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档