benedict_w
benedict_w

Reputation: 3608

jQuery Add an Element if Does Not Exist

I'm using jQuery to add content to an html form if it does not already exist - is there any way more succinct than this to test if a hidden field with a given value is already present in the form?

$("form").find("input[type='hidden'][value='" + $content.find("input[type='hidden']").val() + "']").length === 0

Upvotes: 0

Views: 997

Answers (1)

Guillaume Poussel
Guillaume Poussel

Reputation: 9822

When using concatenation in jQuery selectors, you should be careful about escaping special chars (like quotes). What if your input value is, for example, Let's go? Your jQuery selector becomes input[type='hidden'][value='Let's go'] and is invalid.

I'd rather go with filter() function:

$("form input[type='hidden']").filter(function() { return $(this).val() == $content.find("input[type='hidden']").val(); }).length === 0

Upvotes: 1

Related Questions