首页 > 解决方案 > Long delay when my jQuery function fires due to a large amount of values in my select form elements

问题描述

I have a .php page with about two hundred select form elements on it. The element values are being populated by a .txt file in the same directory using PHP:

<?php

$schoolselected = 'schools.txt';
$eachlines1 = file($schoolselected, FILE_IGNORE_NEW_LINES);

?>

and

<select name="schoolselected001">
    <option value="" disabled selected>Select School...</option>
    <option value=" " <?php if(isset($_POST['schoolselected001'])) echo "selected"; ?>></option>
       <?php foreach($eachlines1 as $lines1){
            echo "<option value='".$lines1."'>$lines1</option>";
        }?>
</select>

Each select form element have the same name but with 001 through 200.

I'm using this jQuery function to disable an option when selected to prevent doubling up:

<script>
$(document).ready(function(){
$('select[name*=schoolselected]').on('click', function() {
  $('option').prop('disabled', false);
  $('select[name*=schoolselected]').each(function() {
    var val = this.value;
    $('select[name*=schoolselected]').not(this).find('option').filter(function() {
      return this.value === val;
    }).prop('disabled', true);
  });
}).change();
});
</script>

Everything works perfectly and there was no delay when I tested with ten values but now with two hundred values, there is a 10-12 second delay each time I click any of the select form elements.

Are there any tweaks I can do to the existing code to remove the delay? Or maybe I'm taking the wrong approach? I looked into caching the data but had no luck finding a solution. If I disable the jQuery function there is zero delay. Any help or suggestions would be appreciated.

标签: phpjquery

解决方案


So many questions to what you are trying to achieve

Why 200 select dropdowns?

Why did you use 'on click' on a select? you want 'on change' event right?

your code is slow because you are iterating twice over your 200 selects

here is the working code

<script>
$(document).ready(function(){

var lastSelectedValue = {};

$('select[name*=schoolselected]').on('change', function() {

var currentSelect = this.attributes.name.value;
var oldValue = lastSelectedValue[currentSelect];
lastSelectedValue[currentSelect] = this.value;

    $('select[name*=schoolselected]').not(this).each(function() {
        if(oldValue){
         $(this).find("option[value='"+oldValue+"']").prop('disabled', false);
        }
        $(this).find("option[value='"+lastSelectedValue[currentSelect]+"']").prop('disabled', true);
    });
    
});
});
</script>

推荐阅读