I don't have much experience with javascript so I' not sure if/how this can be done. So I have a number of select components with a couple of options. One of these options for all of the components is "All".
Now I need to make sure that no more than one component has "All" selected. I'm using some input fields and making some validations to make sure this condition stands. However I can't see how I can do the following. When a user selects "All" from a field, and this is not allowed because there is already an "All" on the page, put the previous selection in it's place.
So far what I have is (component being the current select component):
selectedName = component.options[component.selectedIndex].innerHTML;
if (selectedName == 'All') {
if (emptyAllSpace() == 1) {
//here I do all the mumbo jumbo needed and assign to the hidden field the name of
//the component
}
else {
//Here is where I should put back the old selection value.
}
}
Now the else branch is where I need to figure something out. So how can I / how difficult would it be to get the select开发者_开发技巧ed option before the currently selected one.
I'm also interested how difficult it would be because I could also go another route and just put as selected the first option that is not 'All' but I would rather avoid this if it's no too time consuming.
Regards, Bogdan
Use the onchange event for the select. First store the default value, and reassign it on change. Or use 2 variables which keep the last 2 selected options(?).
UPDATE
Use the onfocus
to get the value before it changes, http://jsfiddle.net/gQHqj/ .
In this handler you could register the following onchange
, and have that value stored in the closure (onfocus's scope object).
UPDATE 2
I knew something was a bit suspicious, but didn't have time to inspect, if the user doesn't move to another element or click somewhere the element is still in focus, and the onfocus
will not be called, while onchange
will (if the user changes the value), with the wrong prev value. So I came up with a bugfix, you should have this structure : http://jsfiddle.net/gQHqj/4/
You could keep the previously selected value in a variable. This variable's value would be populated on form/page load and update only in case the selection is correct. Otherwise, you will revert the selection to its value.
精彩评论