yossi
yossi

Reputation: 3164

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?

Upvotes: 0

Views: 795

Answers (2)

Mehran Hatami
Mehran Hatami

Reputation: 12961

The point is when the input tag gets inserted to the page, no matter it is in the page load or in your dynamic JavaScript codes, if it has the value attribute your selector query would use it or if you change your input's value using setAttribute in JavaScript or .attr() in jQuery, their value attribute actually gets changed, but if you change it with .value in JavaScript or .val() in jQuery or simply change the value in the page as a textbox, the attribute won't change, so you better not use value attributes in your selectors, because they are not reliable, an instead use $("[name*='data\\[Filter\\]']") and filter it as @JasonP has pointed out.

Upvotes: 1

Jason P
Jason P

Reputation: 27022

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;
});

Upvotes: 2

Related Questions