опция: выбрано в jquery учитывается и в скрытой опции - PullRequest
1 голос
/ 30 января 2020

У меня есть требование в проекте, где я должен перейти от первого раскрывающегося списка ко второму раскрывающемуся списку при нажатии кнопки добавления и наоборот при нажатии кнопки удаления.

Здесь HTML:

jQuery( "#term_add" ).click(function() {
  addTerm();
});

jQuery( "#term_rem" ).click(function() {
  remTerm();
});
// this function is called when user clicks the add button in the terms section
function addTerm() {

  if ( jQuery("#all_terms :selected").length === 0 ) {
    alert('Please select at least one term from the Terms drop-down to add');
    return;
}

jQuery("#all_terms option:selected").each( function()
{ 

  var new_elem = jQuery(this).val();

  // show the option which was hidden by default
  jQuery('#terms option[value="' + new_elem + '"]').show();

  jQuery(this).hide();

});

  // Unselect the options selected in the all_terms dropdown
  jQuery("#all_terms option:selected").removeAttr("selected");

  // trigger cascading
  // Do Something
}

// this function is called when user clicks the remove button in the terms section
function remTerm() {

  var count_all_the_visible_options_in_terms_dropdown = 0;
  jQuery("#terms option").each(function()
  {
    if(!jQuery(this).is(':hidden')){
      count_all_the_visible_options_in_terms_dropdown = count_all_the_visible_options_in_terms_dropdown + 1;
    }
  });

  // If the user has not removed all the options from the "Selected Terms" drop-down then cascading should restart.
  console.log( 'count_all_the_visible_options_in_terms_dropdown 1 => ' + count_all_the_visible_options_in_terms_dropdown);
  if ( count_all_the_visible_options_in_terms_dropdown === 0 ) {
    // Do something

    } else {
    // Do something
    }

  if ( !count_all_the_visible_options_in_terms_dropdown ) {
    alert('Please select at least one term from the Selected Terms drop-down to remove');
    return;
  }

  jQuery("#terms option").each(function()
  {

    // Add $(this) to your selected list
    if(jQuery(this).is(':selected')){ 

      var new_elem = jQuery(this).val();

      // display the removed option in available terms dropdown..
      jQuery('#all_terms option[value="' + new_elem + '"]').show();

      // hide the option in the selected terms dropdown
      jQuery(this).hide();

  }

});

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<table class="formTable" cellspacing="0" cellpadding="0">
<tr>
    <td><h5>Available Terms</h5></td>
    <td>
        <div id="terms_div">
            <select multiple="" id="all_terms" name="all_terms" style="width:100px;">
			    <option value="Fall 2014" title="Fall 2014" style="display: block;">Fall 2014</option>
                <option value="Fall 2015" title="Fall 2015" style="display: block;">Fall 2015</option>
                <option value="Fall 2018" title="Fall 2018" style="display: block;">Fall 2018</option>
                <option value="SPRING 2015" title="SPRING 2015" style="display: block;">SPRING 2015</option>
                <option value="SPRING 2016" title="SPRING 2016" style="display: block;">SPRING 2016</option>
                <option value="SUMMER 2016" title="SUMMER 2016" style="display: block;">SUMMER 2016</option>
                <option value="Spring 2017" title="Spring 2017" style="display: block;">Spring 2017</option>                                  
			</select>
		</div>
    </td>
    </tr>
    <tr>
    <td class="title" style="vertical-align:middle;padding:20px;">
        <input class="btn_cn" title="Add terms to the report" type="button" id="term_add" name="term_add" value="add >>">
        <br><br>
        <input class="btn_cn" title="Remove terms from the report" type="button" id="term_rem" name="term_rem" value="<< remove">
    </td>
    </tr>
    <tr>
	<td class="title width20" style="width:0em;"><h5>Selected Terms</h5></td>
    <td>
        <div id="selected_terms_div">
            <select multiple="" class="filter menuItems" id="terms" name="terms" style="width:100px;">
			    <option value="Fall 2014" title="Fall 2014" style="display: none;">Fall 2014</option>
                <option value="Fall 2015" title="Fall 2015" style="display: none;">Fall 2015</option>
                <option value="Fall 2018" title="Fall 2018" style="display: none;">Fall 2018</option>
                <option value="SPRING 2015" title="SPRING 2015" style="display: none;">SPRING 2015</option>
                <option value="SPRING 2016" title="SPRING 2016" style="display: none;">SPRING 2016</option>
                <option value="SUMMER 2016" title="SUMMER 2016" style="display: none;">SUMMER 2016</option>
                <option value="Spring 2017" title="Spring 2017" style="display: none;">Spring 2017</option>                                  
			</select>
		</div>
    </td>
</tr>

В качестве первого шага нажмите кнопку удаления

count_all_the_visible_options_in_terms_dropdown 1 => 0  -- correct 

Теперь добавьте все термины FALL (термины, начинающиеся с FALL).

нажмите кнопку «Удалить» еще раз (во втором раскрывающемся списке ничего не выбрано)

count_all_the_visible_options_in_terms_dropdown 1 => 3 -- correct 

Теперь выберите хотя бы два условия и нажмите «Удалить».

count_all_the_visible_options_in_terms_dropdown 1 => 3 -- **INCORRECT**

Я не понимаю, почему это происходит?

1 Ответ

1 голос
/ 30 января 2020

Изменение видимости option элементов, как известно, ненадежно. Вы можете сделать логику c более точной, фактически перемещая элементы между select вместо того, чтобы скрывать или показывать их аналоги. Попробуйте это:

jQuery(function($) {
  $("#term_add").click(function() {
    addTerm();
    sortTerms();
  });

  $("#term_rem").click(function() {
    remTerm();
    sortTerms();
  });

  function addTerm() {
    if ($("#all_terms :selected").length === 0) {
      alert('Please select at least one term from the Terms drop-down to add');
      return;
    }

    $("#all_terms option:selected").appendTo('#terms').prop('selected', false);
  }

  function remTerm() {
    if ($("#terms :selected").length === 0) {
      alert('Please select at least one term from the Selected Terms drop-down to remove');
      return;
    }

    $("#terms option:selected").appendTo('#all_terms').prop('selected', false);
  }

  function sortTerms() {
    $('#terms, #all_terms').each(function() {
      $(this).children('option').sort(function(a, b) {
        return $(a).data('sort') < $(b).data('sort') ? -1 : 1;
      }).appendTo(this);
    });
  }
});
select {
  width: 100px;
}

.title {
  vertical-align: middle;
  padding: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="formTable" cellspacing="0" cellpadding="0">
  <tr>
    <td>
      <h5>Available Terms</h5>
    </td>
    <td>
      <div id="terms_div">
        <select multiple="" id="all_terms" name="all_terms">
          <option value="Fall 2014" data-sort="1" title="Fall 2014">Fall 2014</option>
          <option value="Fall 2015" data-sort="2" title="Fall 2015">Fall 2015</option>
          <option value="Fall 2018" data-sort="3" title="Fall 2018">Fall 2018</option>
          <option value="SPRING 2015" data-sort="4" title="SPRING 2015">SPRING 2015</option>
          <option value="SPRING 2016" data-sort="5" title="SPRING 2016">SPRING 2016</option>
          <option value="SUMMER 2016" data-sort="6" title="SUMMER 2016">SUMMER 2016</option>
          <option value="Spring 2017" data-sort="7" title="Spring 2017">Spring 2017</option>
        </select>
      </div>
    </td>
  </tr>
  <tr>
    <td class="title">
      <input class="btn_cn" title="Add terms to the report" type="button" id="term_add" name="term_add" value="add &gt;&gt;">
      <br><br>
      <input class="btn_cn" title="Remove terms from the report" type="button" id="term_rem" name="term_rem" value="&lt;&lt; remove">
    </td>
  </tr>
  <tr>
    <td class="title width20">
      <h5>Selected Terms</h5>
    </td>
    <td>
      <div id="selected_terms_div">
        <select multiple="" class="filter menuItems" id="terms" name="terms"></select>
      </div>
    </td>
  </tr>

Также обратите внимание, что jQuery 1.8.0 очень устарел. Вы должны обновить до 3.x

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...