简体   繁体   中英

Alert when user select the same <option> in dynamically created <selects>

I have a PHP page that creates multiple selects depending on how many the page before it gives it and creates the same number of options that there are selected (it's to choose the priority).

<select name="select1" id="idSelect" onchange="javascript:SelectOnChange();">
    <option value="Select one">Select one</option>
    <option value="1">1</option>
    <option value="2">2</option>
</select>

What I want to do is, whenever the user chooses an option that was already selected in another selection, to show an alert in order to let them know that their choice has already been taken and deny the change.

I want to compare the currently selected option to every previously selected option every time the user selects something from every select .

Basically your looking for a change event to loop through each select and notify duplicates.

$("select").change(function() {
    var currentSelection = this.value;
    $("select").each(function() {
        if (this.value == currentSelection)  {
            alert("you've already chosen this!");
        } 
    });
});

Something like this should work

  • Listen for change events
  • Get the element's seletedIndex
  • Grab all of the selects with getElementsByTagName()
  • Loop through and get the selected index
  • Compare to see if used

This could maybe work :

var $selects = $('select');

// WHen a select is changed.
$selects.onchange(function() {
    // Storing it's selected value, assuming there is only one per select.
    var value = $(this).selected().first().attr('value');
    var $changedSelect = $(this);
    // For each select...
    $selects.each(function() {
        var $otherSelect = $(this);
        // ...that is not the one that just changed.
        if( ! $otherSelect.is($changedSelect)) {
            // If that other select's selected value is the same as the changed one's
            if($otherSelect.selected().first().attr('value') === value) {
                alert('...');
            }
        }
    });
}

I didn't try it though, you might have to change a few details in it if it doesn't work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM