Code Review: Effective? Will this work?

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>
    // the code:
    function IsSelectChanged(select){
        var options = select.options,
            i = 0,
            l = options.length;
        // collect current selected and defaultSelected
        for (; i < l; i++) {
            var option = options[i];
            // if it was selected by default but now it is not
            if (option.defaultSelected && !option.selected) {
                return true;
            }
            // if it is selected now but it was not by default
            if (option.selected && !option.defaultSelected) {
                return true;
            }
        }
        return false;
    }

    // implementation:
    $("select").change(function(){
        doSomethingWithValue( IsSelectChanged(this) );
    });
</script>

select, / , ( ).

- - ? ?

+3
3

false && true true && false, !==, , return true, .

if(option.defaultSelected !== option.selected) {
    return true;
}

, , while, .

var options = select.options,
    l = options.length;
while ( l-- ) {
   ...

.

+1

, , "" , XOR ( 2 if), ? IIRC, JS XOR ( ) [^ https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_Operators]. XOR ^ 1 0 , :

if ((option.defaultSelected ? 1 : 0) ^ (option.selected ? 1 : 0)) { return true }

( @some , . );

if (option.defaultSelected ^ option.selected) { return true }

, if .

+5

,

$("select option:selected").doSomething();
$("select option.defaultSelected").doSomething();

, .

+1

Source: https://habr.com/ru/post/1771581/


All Articles