0

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?

3
  • 1
    Well your elements do not have an attribute value with a value of "" so they will be selected. Commented Feb 25, 2014 at 17:44
  • mmmm.. tried it now, no change. (edited, thanks) Commented Feb 25, 2014 at 17:47
  • 1
    Well when the value changes, the attribute does not change. jsfiddle.net/9Jg86 Commented Feb 25, 2014 at 17:53

2 Answers 2

2

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;
});
Sign up to request clarification or add additional context in comments.

2 Comments

And the value attribute is not the place to look at, because... ?
The value attribute doesn't change when someone types in the field, or when you assign a new value using .val() or .value. It's the value property that changes. Also, as epascarello just commented, your elements don't even have a value attribute.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.