Search code examples
javascriptmootoolsmootools1.2

Using Mootools getElements('[selected] to find if ANY option is selcted


Can someone please help me find if there is any option selected I currently have this

 var Selected = $$('myslected_id').getElements('[selected]') ;
 if(Selected==null){
       $('selectedresult').set('text','Nothing Selected');
 }else{
       $('selectedresult').set('text','Something Selected');
 }


<div id="selectedresult"></div>


<select id="myslected_id" name="myslected_name"  multiple="multiple">

 <optgroup label="mylabel">
  <option value="1">Value1</option>
  <option value="2" selected="selected">Value1</option>
                <option value="3">Value2</option>
 </optgroup>
</select>

current form select should output Something Selected

Thank you!


Solution

  • first of all you misspelled 'myselected_id' on your <select>

    <select id="myselected_id" name="myselected_name"  multiple="multiple">
    
     <optgroup label="mylabel">
      <option value="1">Value1</option>
      <option value="2" selected="selected">Value1</option>
      <option value="3">Value2</option>
     </optgroup>
    </select>
    

    mootools section

    var Selected = $$('#myselected_id option[selected]');
    
    if (Selected.length == 0) {
        $('selectedresult').set('html', 'nothing selected');
    } else {
        $('selectedresult').set('html', 'Something Selected');
    }
    

    Here is the Jsfiddle This will grab all options elements that are selected. Your understanding of usage for $$ isn't correct. Please read this section. Also, an empty array does not equal to null in javascript.

    Mootools 1.2.5 Element Doc