Reputation:
I have a page in which i have to search for presence of element depending on first input in the first form only
<input type="text" /><!-- first input -->
<button></button>
<div>
<form><input value="3" /></form> <!-- first form -->
<form><input value="3" /></form>
</div>
and script
$("button").click(function()
{
if( $(this).next().children("form").first().has("input[value='" + $(this).prev().val() + "']") )
alert("Present");
else
alert("Absent");
});
But it's not working
Upvotes: 0
Views: 733
Reputation: 150070
The problem is that the .has()
method doesn't return a boolean, it returns a jQuery object, specifically it "constructs a new jQuery object from a subset of the matching elements". You need to check the length of that object to see if any elements matched:
if($(this).next().children("form").first()
.has("input[value='"+$(this).prev().val()+"']").length != 0)
Demo: http://jsfiddle.net/mmQHB/
Upvotes: 0
Reputation: 119877
You can check the presence of an element by checking the length of the collection a query returns:
For example, if i were to check if i had forms:
var forms = $('form').length //0 if none, at least 1 if any
Upvotes: 2