Home > Blockchain >  How to use an option in a selection element to run a function depending on the selected option
How to use an option in a selection element to run a function depending on the selected option

Time:07-08

I aim to use a selected option (item01) on a selector element to run a specific function and this function should then apply a class to each of the objects inside of the array (array01) using the ids of the objects that correspond to elements on a different part of the web page.

This is what I have written, but I can not figure out what to do to make it work.

let array01 = [{id:"07-01"}, {id:"05-01"}, {id:"05-03"}, {id:"05-05"}, {id:"05-07"}, {id:"05-09"}, {id:"05-11"}, {id:"05-13"}, {id:"05-05"}, {id:"06-05"}, {id:"07-08"}, {id:"07-11"}, {id:"06-13"}]

const test = array01.map(item => item.id);

$("#item1").on("click", function() {
  test.forEach(element => (("#"   element).addClass("mySpecialClass")));
});
<select id="selector" >
  <option selected>Preset</option>
  <option value="item1"  id="item1">item1</option>
  <option value="item2"  id="item2">item2</option>
  <option value="item3"  id="item3">item3</option>
</select>

CodePudding user response:

The simplest way to do what you require would be to match the elements which should have the class to the selected option's value. In the example below I've done this by placing the classes to group the elements in the HTML.

Note in the example below that it's using the change event of the select, not the click on the option elements. The latter is not very reliable across all browsers.

$('#selector').on('change', e => {
  $('.item').removeClass('mySpecialClass');
  $('.'   e.target.value).addClass('mySpecialClass');
});
.mySpecialClass {
  background-color: #C00;
  color: #FFF;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<select id="selector" >
  <option selected>Preset</option>
  <option value="item1">item1</option>
  <option value="item2">item2</option>
  <option value="item3">item3</option>
</select>

<div >item1</div>
<div >item2</div>
<div >item3</div>

<div >item1 item2</div>
<div >item3 item2</div>

<div >item1 item3</div>
<div >item2 item3</div>

<div >item1 item2 item3</div>

  • Related