当值为空时如何隐藏附加的输入名称 [英] How to hide appended input names when the value is empty

查看:22
本文介绍了当值为空时如何隐藏附加的输入名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我有一个小脚本,可以将输入值列表及其名称附加到文本区域中.我想做的是在值为 0empty 时隐藏字段名称.

Hi all, I have a small script that appends a list of input values along with their names into a textarea. What I'd like to do is hide the field name when the value is 0 or empty.

脚本如下:

<script>
  function showValues() {
    var fields = $(".content :input").serializeArray();
    $("#contentlist_copy").empty();
    jQuery.each(fields, function(i, field){
      $("#contentlist_copy").append(field.value + " " + field.name + ", ");
    });
  } 
  $("input").change(showValues);
  showValues();     
</script>

我知道这是一个基本问题,感谢您的帮助.

I know it's an elementary question and I appreciate your help.

推荐答案

我认为您应该使用 .val() 方法来设置 textarea 的值.您还可以使用 jQuery.map() 方法将字符串数组放在一起,然后将它们连接起来.如果 jQuery.map() 方法的回调函数返回 null 或 undefined,则不会将该项目添加到数组中.

I think you should use the .val() method to set the value of a textarea. You can also use the jQuery.map() method to put together an array of strings and then join them. If the callback function for the jQuery.map() method returns null or undefined, the item is not added to the array.

function showValues() {
    var fields = $(".content :input").serializeArray();
    var tokens = jQuery.map(fields, function(field) {
            return (field.value && field.value != '0') ? (field.value + ' ' + field.name) : null;
        });
    $("#contentlist_copy").val(tokens.join(', '));
}

更新:

上面的代码试图维护您的大部分原始代码,但您确实不需要调用 .serializeArray().在您询问使用标题"而不是名称"的评论中.下面的代码就是这样做的:

The code above tried to maintain much of your original code, but you really don't need to call .serializeArray(). In the comments you asked about using the "title" instead of the "name". The following code does that:

function showValues() {
    var tokens = [];
    $('.content :input').each(function() {
        var $input = $(this);
        if (($input.val() != '') && ($input.val() != '0')) {
            tokens.push($input.val() + ' ' + $input.attr('title'));
        }
    });
    $('#contentlist_copy').val(tokens.join(', '));
}

这篇关于当值为空时如何隐藏附加的输入名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆