How To Find if a Select Element has Multiple Selected Items using jQuery

Today on the forums I saw a question that asked is it possible, through JavaScript, to find out if a user has selected any items in a drop down list, and if they have, prompt them with a confirm box asking them a question before performing the next piece of code. I said it was quite easy and here’s how I did it.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
script src="http://code.jquery.com/jquery-latest.js"
language="javascript" type="text/javascript"></script>
<
script language="javascript" type="text/javascript">
$(function() {
$("#Button1").click(function() {
if ($("#Select1 option").is(":selected")) {
if (confirm("Are you sure you want to delete?")) {
$("#Select1 option:selected").each(function() {
alert("Deleting: " + $(this).val());
});
}
}
});
});
</script>
</
head>
<
body>
<
select id="Select1" multiple="multiple">
<
option value="1">1</option>
<
option value="2">2</option>
<
option value="3">3</option>
</
select>
<
input id="Button1" type="button" value="button" />
</
body>
</
html>


When the user clicks the button, if they haven’t selected any items in the drop down list, they won’t be prompted, but if they have, then they will be. Another good use of jQuery!

Note: This code does not delete the items of the DropDownList.

See a Live Demo






About The Author

Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET and regular presenter at conferences and user groups throughout Australia. Being an ASP.NET Insider, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with JavaScript. He also blogs regularly at DotNetCurry.com. Follow him on twitter @malcolmsheridan

2 comments:

Anonymous said...

You might consider using one selector instead of two...

http://jsfiddle.net/PPqEm/

Malcolm Sheridan said...

@elijahmanor
Thanks for the code! One selector would be better than two.