How to hide appended input names when the value is empty

老子叫甜甜 提交于 2019-12-12 03:49:20

问题


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.

Here's the script:

<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.


回答1:


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(', '));
}

UPDATE:

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(', '));
}



回答2:


$("#contentlist_copy").append(field.value + (!field.value || field.value == "0" ? "" : " " + field.name) + ", ");

Update:

Try this if you want to hide the commas too

$("#contentlist_copy").append(field.value + (!field.value || field.value == "0" ? "" : " " + field.name) + (!field.value ? "" : ", "));



回答3:


Here's an approach:

$('input').change(function() {
    var valuePairs = $('.content :input').filter(function() {
        return this.value.length && this.value !== '0';
    }).map(function() {
        return this.value + ' ' + this.name;
    }).get();
    $('#contentlist_copy').val(valuePairs.join(', '));
});


来源:https://stackoverflow.com/questions/15836404/how-to-hide-appended-input-names-when-the-value-is-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!