Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

html - Convert javascript of checkbox to select type

Earlier the code for the checkbox was

<li class="list-group-item">
       <div class="form-check">
        <label class="form-check-label">
          <input type="checkbox" class="form-check-input common_check" value="<?= $row['Year']; ?>" id="Year"><?= $row['Year'];  ?>
        </label>
       </div>
  </li>

and js for this to get the filtered text was

function get_filter(text_id)
{
  var filterData = [];
  $('#'+text_id+':checked').each(function(){
     filterData.push($(this).val());
   });
  return filterData;
}

Now if I want to turn this to select option menu bar

<option class="common_check" value="<?= $row['Year']; ?>" id="Year"><?= $row['Year'];  ?>

So what should be the javascript for this??

question from:https://stackoverflow.com/questions/65873596/convert-javascript-of-checkbox-to-select-type

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are a couple of things you need to change:

  1. It looks like you are allowing the user to select multiple option. For that, make sure multiple attribute is assigned to your select element.

  2. Add an onchange handler to your select

  3. Filter all selected indexes

<select id="mySelect" onchange="handler()" multiple>
   <option id="some-id" value="some-value"></option>
</select>

var filtered;
function handler() {
    const selector = document.getElementById('mySelect');
    const selected = Array.prototype.filter.call(selector.options, o => o.selected);
    filtered = selected.map(s => s.value);
}

Every time you change an option (deselecting it, or adding one) the handler will reassign the array. This will save you the effort of keeping the array unique by not having to check the array every time to see if the value already exists or not.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...