Explanation
This is the part of the script that checks if the user and the values in the form have changed. If the user tries to leave the page after changing the value, they receive a warning through onbeforeunload and they are given the opportunity to leave the page or stay.
The tricky part is defining the changed state (multiple) of the select list ... in which this question applies. I just wanted to find out if anyone could detect any potential problems with how this is done.
Someone mentioned that it might not make sense to always use the default value for comparisons. However, in this case it makes sense. If the user changes the value and then proceeds to return it to the original before moving from the page, they probably do not want "you have changed your place on the page, will you leave or will you stay?" a warning appears.
The code below is for checking the selection list ( <select>) to see if the attributes "selected" are the same as the default attributes. It should work with multiple choice lists, as well as with individual selection lists.
Function IsSelectChanged' should returntrue if the selected option(s) are not the same as the default andfalse "if the selected parameters match the default settings.
The code:
<select>
<option selected="selected">Opt 1</option>
<option>Opt 2</option>
</select>
<script>
function IsSelectChanged(select){
var options = select.options,
i = 0,
l = options.length;
for (; i < l; i++) {
var option = options[i];
if (option.defaultSelected && !option.selected) {
return true;
}
if (option.selected && !option.defaultSelected) {
return true;
}
}
return false;
}
$("select").change(function(){
doSomethingWithValue( IsSelectChanged(this) );
});
</script>
select, / , ( ).
- - ? ?