Reputation: 582
I have an application with info page and edit page the info page shows the info. in the edit page i have fields with selectbox etc etc
I want to use same code for both. So I tried
if($('#product').has('option'))
{
console.log('hasSelect')
}
else{
console.log('NOSELECTNO')
}
in single page there is no option or select avaible but in the edit it is.
How can I make sure it will work (and why is this not working)
edit tried this 2:
var attr = $('#product div').attr('select');
if (typeof attr !== typeof undefined && attr !== false) {
console.log("welmetselect")
}
else
{
console.log("zonderselect")
}
EDIT: HTML
<div id= product>
<div>some more divs</div>
<div> in 1 of the div we have <select><option></option></select></div>
</div>
And html infopage
<div id= product>
<div>only information</div>
<div>only text </div>
</div>
Upvotes: 1
Views: 38
Reputation: 6742
I think you need something like this:
if ($("#product option").length )
If you don't have an option, the length will be 0 (and therefore false)
Upvotes: 1
Reputation:
First of all, you could just give them different IDs, or a class like .info
and .edit
, and simply check $('#product').hasClass('info')
. I do not recommend checking for a specific descendant to identify an element anyway, because you want your code to be as flexible as it can be, and if you decide to add a select element to your info page in the future, for example, to filter out specific items to get info on, your code totally breaks.
Second, why your code is not working, is this.
var attr = $('#product div').attr('select');
select
is not an attribute, it's a child. Use children('select')
(if it's a direct child) or find('select')
(if it's not a direct child).
As a sidenote, you can simplify typeof attr !== typeof undefined
to typeof attr !== 'undefined'
because we already know typeof undefined
is returning 'undefined'
.
Upvotes: 1