Reputation: 1449
have 5 Select controls on a page, each with the same option values and when I select one value in first dropdown, I shouldn't be allowed to select the same value again in the others. I tried something like below.
$("#div").find(".selectClass").live("change", function (e) {
var selectedValue = $(this).val();
var controlId = $(this).attr("id");
var isPropertyAlreadySelected = false;
$("#div").find(".selectClass").each(function () {
var currentSelect = $(this);
if (controlId != currentSelect.attr("id") && currentSelect.val() == selectedValue) {
isPropertyAlreadySelected = true;
}
});
e.preventDefault();
return false;
});
EDIT: Removed check on the flag "isPropertyAlreadySelected"; but still I'm able to select other dropdown values.
Even if I do a "return false" or "e.preventDefault()", the value is still getting selected in the other dropdowns. Please point me in the right direction. Thanks in advance!!
Upvotes: 1
Views: 661
Reputation: 21881
Save the current selected item on the dropdown and work with this little helper :)
<select id="s1" class="selectClass">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<select id="s2" class="selectClass">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
.
$(document).on("change", ".selectClass", function(ev) {
var cur = $(this),
text = cur.find("option:selected").text(),
isAlreadySelected;
isAlreadySelected = $(".selectClass").not("#" + this.id).filter(function() {
return $(this).find("option:selected").text() === text;
});
if (isAlreadySelected.length) {
cur.prop("selectedIndex", cur.prop("selIdx") || 0);
}
cur.data("selIdx", cur.prop("selectedIndex"));
});
Upvotes: 0
Reputation: 45715
As others have mentioned, it seems not possible, as the value already changed.
Please see this related question and solution: jQuery prevent change for select
Here is a minimal reproduce of the issue in jsFiddle
Upvotes: 1
Reputation: 4197
The problem you are running in is, that the value of the select has already changed when your change event fires.
You need to have a list of the currently selected values and reset the changed option here:
if (isPropertyAlreadySelected) {
// Reset here
}
Just fill an array with the values that are selected at page load and update this array every time an option gets selected.
I have just tested with the mousedown event. This one fires before the option realy got selected. Try here: http://jsfiddle.net/g3rsF/1/
This will not solve for all cases, as the user can select by keypress also.
Upvotes: 1