-1

I wish to check if anything in my multiple dropdown list has been selected using javascript.

<select name="id" id="id" size=22 multiple >

And also if any checkboxes has been checked

<input type="checkbox" name="inst" class="asa" value="inst1"> 
<input type="checkbox" name="inst" class="asa" value="inst2">
0

3 Answers 3

1

try this code

DEMO

var selectVal = document.getElementById('id');
var selectCount = 0;
var values = [];
for (var i = 0; i < selectVal.options.length; i++) {
  if (selectVal.options[i].selected) {
    selectCount++;
    values.push(selectVal.options[i].value);
  }
}

for checkbox

<input type="checkbox" name="inst" class="asa" id="check1" value="inst1"> 
<input type="checkbox" name="inst" class="asa" id="check2" value="inst2">

var check1 = document.getElementById("check1").checked;
alert(check1);
var check2 = document.getElementById("check2").checked;
alert(check2);
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! didn't knew loops would be needed
0

Try

var select = document.getElementById('id');

var selected  = [];
for(var i =0 ; i < select.options.length; i++){
    if(select.options[i].selected){
        selected.push(select.options[i].value);
    }
}
if(selected.length == 0){
    alert('not selected');
}

Demo: Fiddle

Comments

0

HTML:

<select name="id" id="three" size=22 multiple>
    <option value="thevalue">Option</option>
</select>

<select name="id" id="four" size=22 multiple>
    <option value="thevalue" selected="selected">Option</option>
</select>

JS:

var one = document.getElementById("one");
var two = document.getElementById("two");
var three = document.getElementById("three");

if(one.checked)
    console.log("one = checked!");
else
    console.log("one != checked");

if(two.checked)
    console.log("two = checked!");
else
    console.log("two != checked");

if(three.value)
    console.log("something is selected in three!");
else
    console.log("nothing is selected in three");

if(four.value)
    console.log("something is selected in four!");
else
    console.log("nothing is selected in four");

Fiddle covering both the checkbox and select.

Obviously this is a very verbose example, but you can trim it down to take away what you need.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.