0

I have this code:

  console.log($(domElem).attr('selected'));

  console.log(typeof $(domElem).attr('selected'));

  if($(domElem).attr('selected') == true);
  {
      alert("there is one element selected");
  }

The output is:

false
boolean
false
boolean
false
boolean
...

I expected "this is a selected element" didn't was showed never, but it is showed as many time as items are there.

jQuery 1.3.2

Any idea?

Javier

JJJ
  • 32,902
  • 20
  • 89
  • 102
tirenweb
  • 30,963
  • 73
  • 183
  • 303

2 Answers2

0

Putting a semi colon after the condition as:

if($(domElem).attr('selected') == true);  
 {
       alert("there is one element selected");  
 } 

terminates the "if" statement and is the same as if you wrote:

if($(domElem).attr('selected') == true){}; 
alert("there is one element selected");

change it to:

if($(domElem).attr('selected') == true)
{
       alert("there is one element selected");
}
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
0

This is a hard question to answer since it's a bit unclear as to what you want to achieve.

If it's just checking if a list item is selected or not this is how I'd do it:

The HTML (yes I took it off of w3schools, sorry! why this is bad):

<select id="selectedLIST">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
</select> 

The jQuery

var list = $('#selectedLIST');
$(list).change(function(){
    $.each(list.children(), function(index, value){
        if($(value).attr('selected') === true){
            alert("there is one selected");
        }
    });
});

This will produce a list that when a user selects a new element in the list will produce a popup saying "this is one selected" based on the attribute "selected" on the HTML tag.

Also, putting semi-colons after if-statements "terminates" that statement.

Also forgetting to put semi-colons will force the JS engine to do semi-colon insertions.

Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92