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
Tweet
2 comments:
You might consider using one selector instead of two...
http://jsfiddle.net/PPqEm/
@elijahmanor
Thanks for the code! One selector would be better than two.
Post a Comment