Using JavaScript or jQuery, how to check if the selection box matches the original value?

Just wondering if there is a way to check if the value of the drop-down list matches the original value during page load (when the value was set using selected = "yes")?

I suppose I could use PHP to create the source values ​​as JavaScript variables and check them out, but there are several selection fields, and I try to keep the code as concise as possible!

+3
source share
4 answers

This is not too complicated. This will track the value for each selecton the page:

$(document).ready(function() {
    $("select").each(function() {
        var originalValue = $(this).val();

        $(this).change(function() {
            if ($(this).val() != originalValue)
                $(this).addClass('value-has-changed-since-page-loaded');
            else
                $(this).removeClass('value-has-changed-since-page-loaded');
        });
    });
});

value-has-changed-since-page-loaded ( ) , , .

, , .

+7
$(document).ready(function() {
    var initialSelectValue = $('#yourselect').val();

    // call this function when you want to check the value
    // returns true if value match, false otherwise
    function checkSelectValue() {
        return $('#yourselect').val() === initialSelectValue;
    }
});

PS. selected="selected" not selected="yes".

+1

, :

var select_values = [];

$(document).ready(function() {
    $("select").each(function() {
        select_values[$(this).attr('name')] = $(this).val();
    });
});

, , :

function has_select_changed(name) {
    return $("select[name="+name+"]").val() != select_values[name];
}
+1

:

$('select').each( 
  function(){ 
    if( this.options[ this.selectedIndex ].getAttribute('selected') === null ){
          alert( this.name +' has changed!') 
    }
});

:

, selectElement < select/ > elementYou ,

selectElement.selectedIndex

< option/ > , ,

selectElement.options[ selectElement.selectedIndex ]

Now that you know which selection element is selected, you can find out if this element has the selected = 'selected' attribute (as in the source code, it does not change - this is not the same as the. DOM node, which is true for the currently selected option item and changes when the selection changes)

0
source

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


All Articles