选择器细化 - >每个非空输入

时间:2012-10-31 19:15:55

标签: jquery

可以对此使用一点帮助,似乎应该有一个更清晰的方法来写出来。

我想选择#endowment div中的每个文本输入,这不是空的。 另外,我正在写一个名为'dyn_hidden'的div,我希望在每个输入中附加一个值。所以在每个模糊我删除所有内容,然后添加每个模糊。有更好的方法吗?

谢谢!

jQuery("#endowment input[type='text']").blur( function() {

    // Empty out dyn_hidden div
    jQuery('#dyn_hidden').html('');

    jQuery("#endowment input[type='text']").each(function() {
        if(jQuery(this).val() !== "") { 
            end_fund      = '<input type="hidden" name="fund[]" value="'+jQuery(this).attr('title')+'">';                                                                                                                  
            end_amount    = '<input type="hidden" name="amount[]" value="'+jQuery(this).val()+'">';
            jQuery('#dyn_hidden').append(end_fund, end_amount);
        }
    });
});

2 个答案:

答案 0 :(得分:1)

您可以执行in this question

之类的操作
 $('#button').click(function() {

    var emptyTextBoxes = $('input:text').filter(function() { return this.value == ""; });
    var string = "The blank textbox ids are - \n";

    emptyTextBoxes.each(function() {
      string += "\n" + this.id;
    });
    alert(string);
  });

答案 1 :(得分:1)

首先,当DOM加载时,您可以将所有隐藏的输入插入到div中。 因此,当调用输入模糊时,您只需更改与该特定值对应的隐藏输入。

您可以使用HTML 5属性存储该特定文本框的信息..

这样的东西..你也可以消除页面上重复身份的可能性..

jQuery(function() {
    // Insert all the input corresponding to the textboxes initially
    jQuery("#endowment input[type='text']").each(function(i) { // Use i in each as iterator to store the data-attribute
        // Store the value of the textbox in the data-id attribute
        // Add the data-attribute to the textbox that stores the index
        // of corresponding textbox
        $(this).attr('data-id', i);
        var end_fund = '<input type="hidden" name="fund[]" data-param="title-' + i + '" value="' + jQuery(this).attr('title') + '">';
        var end_amount = '<input type="hidden" name="amount[]" data-param="value-' + i + '" value="">';
        jQuery('#dyn_hidden').append(end_fund, end_amount);
    });

    // Blur function of text box
    jQuery("#endowment input[type='text']").blur(function() {
        // Just change the value of corresponding input field..
        if (this.value !== "") {
            var $index = $(this).data('id');
            // Find the hidden input with data-param= "value + $index  inside
            // the #dyn_hidden  div  
            // And then set the value to it...
            $('#dyn_hidden input[data-param="value-' + $index + '"]').val(this.value);
        }
    });
});​

<强> CODE