简体   繁体   中英

JQuery attribute (empty) value selector, not working

The elements & the code.

HTML

<input value="" name="data[Filter][address]" type="text" />
<input value="" name="data[Filter][client]" type="text" />
<input value="" name="data[Filter][tenant]" type="text" />
<input value="" name="data[Filter][contract_end_date]" type="text" />

Javascript

console.log($("[name*='data\\[Filter\\]'][value!='']").serialize());

The problem: even if they are all empty, they are serialized.
Why?

You're looking at the value attribute. You can filter off of the value property instead:

http://jsfiddle.net/Y2P6w/

var $filledElems = $("[name*='data\\[Filter\\]']").filter(function () {
    return $.trim(this.value).length;
});

关键是输入标签何时插入页面,无论它是在页面加载中还是在动态JavaScript代码中,是否具有选择器查询将使用的value属性,或者是否使用setAttribute在其中更改输入的值jQuery中的JavaScript或.attr() ,它们的value属性实际上已更改,但是如果在JavaScript中使用.value或jQuery中的.val()进行更改,或者只是将页面中的值更改为文本框,则该属性不会更改,因此最好不要在选择器中使用值属性,因为它们不可靠,而应使用$("[name*='data\\\\[Filter\\\\]']")并按@JasonP所指出的进行过滤出来。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM