January 16, 2010

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


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

comments

2 Responses to "How To Find if a Select Element has Multiple Selected Items using jQuery"
  1. elijahmanor said...
    January 18, 2010 8:08 AM

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

    http://jsfiddle.net/PPqEm/

  2. Malcolm Sheridan said...
    January 18, 2010 2:34 PM

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

 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions