Materialize - How to dynamically select options in multiple select? - javascript

I have a multiple select element and I would like to dynamically select a mixture of the options like so:
I am able to dynamically select one option but that's all,
document.getElementById('update_days_of_the_week').selectedIndex = 2;
document.getElementById('update_days_of_the_week').selectedIndex = 3;
<div class="row">
<div class="input-field col s4">
<select id="update_days_of_the_week" multiple>
<option value="" disabled selected>Choose your days of the week</option>
<option value="Monday">Monday</option>
<option value="Tuesday">Tuesday</option>
<option value="Wednesday">Wednesday</option>
<option value="Thursday">Thursday</option>
<option value="Friday">Friday</option>
<option value="Saturday">Saturday</option>
<option value="Sunday">Sunday</option>
</select>
<label>Days of the week</label>
</div>
</div>
The above code, obviously only selects index 3 as selectedIndex = 2 is replaced.

Using jQuery you could do something like this :
$('#update_days_of_the_week').val(['Monday', 'Friday'])
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<select id="update_days_of_the_week" multiple>
<option value="" disabled selected>Choose your days of the week</option>
<option value="Monday">Monday</option>
<option value="Tuesday">Tuesday</option>
<option value="Wednesday">Wednesday</option>
<option value="Thursday">Thursday</option>
<option value="Friday">Friday</option>
<option value="Saturday">Saturday</option>
<option value="Sunday">Sunday</option>
</select>

Try using setAttribute() method instead selectedIndex which accepts only one value.
document.addEventListener('DOMContentLoaded', function(){
const instance = M.FormSelect.init(document.querySelector('select'))
});
const elSelect = document.getElementById('update_days_of_the_week')
/*
* With the disabled option in "elOptions"
*/
const elOptions = elSelect.querySelectorAll('option')
// Unselect the "Choose your days of the week" option
elOptions[0].removeAttribute('selected')
// Select the wanted options
elOptions[2].setAttribute('selected', 'selected') // Tuesday
elOptions[3].setAttribute('selected', 'selected') // Wednesday
/*
* Without the disabled option in "elOptions"
*/
// const elOptions = elSelect.querySelectorAll('option:not([disabled]')
// elOptions[1].setAttribute('selected', 'selected') // Tuesday
// elOptions[2].setAttribute('selected', 'selected') // Wednesday
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet"/>
<div class="row">
<div class="input-field col s4">
<form>
<label>Days of the week</label>
<select id="update_days_of_the_week" multiple>
<option value="" disabled selected>Choose your days of the week</option>
<option value="Monday">Monday</option>
<option value="Tuesday">Tuesday</option>
<option value="Wednesday">Wednesday</option>
<option value="Thursday">Thursday</option>
<option value="Friday">Friday</option>
<option value="Saturday">Saturday</option>
<option value="Sunday">Sunday</option>
</select>
</form>
</div>
</div>

Related

How can I update the value of my selection

I am making a piano website that makes random melodies based on their scales. But when I choose a certain key and/or scale and/or mode(different kind of scale), the dropdown doesn't update in JS.
JS Code:
const specifiedNote = document.querySelector('#keys').value;
const majorMinor = document.querySelector('#types').value;
const mode = document.querySelector('#modes').value;
//Checking to see if it changes ever 4 seconds after I select a different value in the drop box
setInterval(()=>{
console.log(specifiedNote, majorMinor, mode);
}, 4000);
HTML Code:
<div class="keys">
<select name="keys" id="keys">
<option value="C">C</option>
<option value="C#">C#</option>
<option value="D">D</option>
<option value="D#">D#</option>
<option value="E">E</option>
<option value="F">F</option>
<option value="F#">F#</option>
<option value="G">G</option>
<option value="G#">G#</option>
<option value="A">A</option>
<option value="A#">A#</option>
<option value="B">B</option>
</select>
<select name="types" id="types">
<option value="Major">Major</option>
<option value="Minor">Minor</option>
</select>
<select name="modes" id="modes">
<option value="None">None</option>
<option value="Dorian">Dorian</option>
<option value="Phrygian">Phrygian</option>
<option value="Lydian">Lydian</option>
<option value="Mixolydian">Mixolydian</option>
<option value="Aeolian">Aeolian</option>
<option value="Locrian">Locrian</option>
</select>
<select name="amount" id="amount">
<option value="4">4 Notes</option>
<option value="8">8 Notes</option>
<option value="16">16 Notes</option>
</select>
<button class="create">RELODY!</button>
</div>
If you look at the console, you'll see the value is the same over 10
times, but the values in the drop downs are different. How do I fix this?
You must read the element again in the the interval function :
setInterval(()=>{
specifiedNote = document.querySelector('#keys').value;
majorMinor = document.querySelector('#types').value;
mode = document.querySelector('#modes').value;
console.log(specifiedNote, majorMinor, mode);
}, 4000);
You must be reading the value inside the timeout.
Or another method you can do is, make a change event handler for the selects instead of the setTimeout, so the functions work when the select boxes are changed, not periodically.
//Checking to see if it changes ever 4 seconds after I select a different value in the drop box
setInterval(()=>{
const specifiedNote = document.querySelector('#keys').value;
const majorMinor = document.querySelector('#types').value;
const mode = document.querySelector('#modes').value;
console.log(specifiedNote, majorMinor, mode);
}, 4000);
<div class="keys">
<select name="keys" id="keys">
<option value="C">C</option>
<option value="C#">C#</option>
<option value="D">D</option>
<option value="D#">D#</option>
<option value="E">E</option>
<option value="F">F</option>
<option value="F#">F#</option>
<option value="G">G</option>
<option value="G#">G#</option>
<option value="A">A</option>
<option value="A#">A#</option>
<option value="B">B</option>
</select>
<select name="types" id="types">
<option value="Major">Major</option>
<option value="Minor">Minor</option>
</select>
<select name="modes" id="modes">
<option value="None">None</option>
<option value="Dorian">Dorian</option>
<option value="Phrygian">Phrygian</option>
<option value="Lydian">Lydian</option>
<option value="Mixolydian">Mixolydian</option>
<option value="Aeolian">Aeolian</option>
<option value="Locrian">Locrian</option>
</select>
<select name="amount" id="amount">
<option value="4">4 Notes</option>
<option value="8">8 Notes</option>
<option value="16">16 Notes</option>
</select>
<button class="create">RELODY!</button>
</div>
Get Values Inside your set interval code like below.
setInterval(()=>{
let specifiedNote = document.querySelector('#keys').value;
let majorMinor = document.querySelector('#types').value;
let mode = document.querySelector('#modes').value;
console.log(specifiedNote, majorMinor, mode);
},

How to select multiple option automatically in jquery?

I am using multi-select picker. I want to automatically select options on ajax response.
I have data in this form
tuesday,wednesday,Thursday
here is a select picker
<select class="form-control kt-selectpicker" multiple="" name="operation_day[]" tabindex="-98">
<option value="monday" >Monday</option>
<option value="tuesday">Tuesday</option>
<option value="wednesday" >Wednesday</option>
<option value="thursday" >Thursday</option>
<option value="friday">Friday</option>
<option value="saturday" >Saturday</option>
<option value="sunday" >Sunday</option>
</select>
this is the variable which is having data
var operation_day = editData.attr('data-operation_day');
How i can automatically select those option which are in variable with help of jquery?
You can use .split(",") to convert them in array and then set value using selectpicker('val', operation_day.split(",")) lastly refresh your selectpicker.
Demo Code :
var operation_day = "tuesday,wednesday,thursday";
console.log(operation_day.split(","))
$('select').selectpicker('val', operation_day.split(",")); //split them and set value
$('select').selectpicker('refresh') //refresh ..selectpicker
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/css/bootstrap.min.css" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.14/dist/css/bootstrap-select.min.css">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.14/dist/js/bootstrap-select.min.js"></script>
<select class="form-control kt-selectpicker" multiple="" name="operation_day[]" tabindex="-98">
<option value="monday">Monday</option>
<option value="tuesday">Tuesday</option>
<option value="wednesday">Wednesday</option>
<option value="thursday">Thursday</option>
<option value="friday">Friday</option>
<option value="saturday">Saturday</option>
<option value="sunday">Sunday</option>
</select>
You can pass the array for multiple selections like below.
var operation_day = "tuesday,wednesday,thursday" //editData.attr('data-operation_day');
var arr = operation_day.split(',');
$(".kt-selectpicker").val(arr)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-control kt-selectpicker" multiple="" name="operation_day[]" tabindex="-98">
<option value="monday">Monday</option>
<option value="tuesday">Tuesday</option>
<option value="wednesday">Wednesday</option>
<option value="thursday">Thursday</option>
<option value="friday">Friday</option>
<option value="saturday">Saturday</option>
<option value="sunday">Sunday</option>
</select>
Note: It's case sensitive. thursday is not equal to Thursday.

click function execute multiple times on elements which has same class name

I used bootstrap multiselect js plugin, after i used in my code, I need to add one click event for each options i select so i bind the click event for that What happened is when i try to click the select option the function execute 2 times. (It supposed to execute only 1 time)
I want to know whats happening in my code, Can anyone explain me ?
My code HTML:
<div class="select-box">
<select id="demo1" multiple class="form-control course-list">
<option value="Javascript">Javascript</option>
<option value="Python">Python</option>
<option value="LISP">LISP</option>
<option value="C++">C++</option>
<option value="jQuery">jQuery</option>
<option value="Ruby">Ruby</option>
</select>
</div>
<div class="select-box">
<select id="demo2" multiple class="form-control course-list">
<option value="Javascript">Javascript</option>
<option value="Python">Python</option>
<option value="LISP">LISP</option>
<option value="C++">C++</option>
<option value="jQuery">jQuery</option>
<option value="Ruby">Ruby</option>
</select>
</div>
<div class="select-box">
<select id="demo3" multiple class="form-control course-list">
<option value="Javascript">Javascript</option>
<option value="Python">Python</option>
<option value="LISP">LISP</option>
<option value="C++">C++</option>
<option value="jQuery">jQuery</option>
<option value="Ruby">Ruby</option>
</select>
</div>
My code JS:
$(document).ready(function() {
$('.course-list').multiselect();
$('.select-box').each(function(){
$(this).find('.ms-options ul li').each(function(index){
$(this).attr('data-item-index',index);
$(this).attr('onclick','selectToggleItem(this)');
// $(this).bind('click', selectToggleItem);
});
});
});
function selectToggleItem(e){
console.log('test');
}
If i click the list item it call the function (selectToggleItem) 2 times Why ???
i used bootstrap-multiselect.js and css file for this.
You meet this problem when you click on the label because the event is triggered by both input and label tags. If you click on the checkbox, the selectToggleItem is triggered only once.
To prevent that behaviour, you can bind the event to the checkbox instead of the <li> tag.
$(document).ready(function() {
$('.course-list').multiselect();
$('.select-box').each(function(){
$(this).find('.multiselect-container li').each(function(index){
$(this).attr('data-item-index',index);
$(this).find("input[type=checkbox]").bind('click', selectToggleItem);
});
});
});
function selectToggleItem(e){
console.log('test');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/js/bootstrap-multiselect.min.js"></script>
<div class="select-box">
<select id="demo1" multiple class="form-control course-list">
<option value="Javascript">Javascript</option>
<option value="Python">Python</option>
<option value="LISP">LISP</option>
<option value="C++">C++</option>
<option value="jQuery">jQuery</option>
<option value="Ruby">Ruby</option>
</select>
</div>
<div class="select-box">
<select id="demo2" multiple class="form-control course-list">
<option value="Javascript">Javascript</option>
<option value="Python">Python</option>
<option value="LISP">LISP</option>
<option value="C++">C++</option>
<option value="jQuery">jQuery</option>
<option value="Ruby">Ruby</option>
</select>
</div>
<div class="select-box">
<select id="demo3" multiple class="form-control course-list">
<option value="Javascript">Javascript</option>
<option value="Python">Python</option>
<option value="LISP">LISP</option>
<option value="C++">C++</option>
<option value="jQuery">jQuery</option>
<option value="Ruby">Ruby</option>
</select>
</div>

jQuery - Autoselect option on selectbox doesn't function well

I have 2 select boxes. When I select an option on selectbox1, it automatically changes the corresponding value on selectbox2 regardless of value but order.
The thing is, the code is working fine until after a few tries. Then even if I change the option on selectbox1, it doesn't update the one on selectbox2.
To reproduce the issue; go through A to E, then repeat.
Code:
$(".firstSelectBox").change(function(e) {
var selectedOption = $("option:selected", this);
var idx = $(this).children().index(selectedOption)
var secChildIdx = $(".secondSelectBox").children()[idx];
$(".secondSelectBox").find(":selected").removeAttr('selected');
$(secChildIdx).attr("selected", "selected");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div class="control-group">
<div class="controls">
<label>First Selectbox</label><br/>
<select class="firstSelectBox validate[required]">
<option value="1">Select A</option>
<option value="2">Select B</option>
<option value="3">Select C</option>
<option value="4">Select D</option>
<option value="5">Select E</option>
</select>
</div>
</div>
<br />
<div class="control-group">
<div class="controls">
<label>Second Selectbox</label><br />
<select class="secondSelectBox validate[required]">
<option value="A">Select 1</option>
<option value="B">Select 2</option>
<option value="C">Select 3</option>
<option value="D">Select 4</option>
<option value="E">Select 5</option>
</select>
</div>
</div>
Also JSFiddle version: https://jsfiddle.net/153w074d/
No need for all that code, just work with selectedIndex:
$(".firstSelectBox").change(function(e) {
var selectedIndex = $(this).get(0).selectedIndex;
$(".secondSelectBox").get(0).selectedIndex = selectedIndex;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div class="control-group">
<div class="controls">
<label>First Selectbox</label><br/>
<select class="firstSelectBox validate[required]">
<option value="1">Select A</option>
<option value="2">Select B</option>
<option value="3">Select C</option>
<option value="4">Select D</option>
<option value="5">Select E</option>
</select>
</div>
</div>
<br />
<div class="control-group">
<div class="controls">
<label>Second Selectbox</label><br />
<select class="secondSelectBox validate[required]">
<option value="A">Select 1</option>
<option value="B">Select 2</option>
<option value="C">Select 3</option>
<option value="D">Select 4</option>
<option value="E">Select 5</option>
</select>
</div>
</div>
What happened in your original code is that, in some way, the selected attributes are being messed around. Try this: Change to each option from A to E, then start over from A, the selection stops working. Then inspect the second select to see that there are more than one option with selected="selected" attribute. Not sure what caused that tho.
#DontVoteMeDown's answer will certainly work, but the reason you're having this issue is because of the discrepancy between .prop and .attr. Both are similar, but don't refer to the same, identical underlying value.
If you change the below two lines to use the .prop value instead of .attr, your code will work. See the working code example below.
$(".secondSelectBox").find(":selected").removeAttr('selected'); // change to .removeProp
$(secChildIdx).attr("selected", "selected"); // change to .prop
$(".firstSelectBox").change(function(e) {
var selectedOption = $("option:selected", this);
var idx = $(this).children().index(selectedOption)
var secChildIdx = $(".secondSelectBox").children()[idx];
$(".secondSelectBox").find(":selected").removeProp('selected');
$(secChildIdx).prop("selected", "selected");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div class="control-group">
<div class="controls">
<label>First Selectbox</label><br/>
<select class="firstSelectBox validate[required]">
<option value="1">Select A</option>
<option value="2">Select B</option>
<option value="3">Select C</option>
<option value="4">Select D</option>
<option value="5">Select E</option>
</select>
</div>
</div>
<br />
<div class="control-group">
<div class="controls">
<label>Second Selectbox</label><br />
<select class="secondSelectBox validate[required]">
<option value="A">Select 1</option>
<option value="B">Select 2</option>
<option value="C">Select 3</option>
<option value="D">Select 4</option>
<option value="E">Select 5</option>
</select>
</div>
</div>
You can also use prop to select option.
$(".firstSelectBox").change(function(e) {
var selectedIndex = $(this).get(0).selectedIndex;
$('.secondSelectBox option:eq('+selectedIndex+')').prop('selected', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="control-group">
<div class="controls">
<label>First Selectbox</label><br/>
<select class="firstSelectBox validate[required]">
<option value="1">Select A</option>
<option value="2">Select B</option>
<option value="3">Select C</option>
<option value="4">Select D</option>
<option value="5">Select E</option>
</select>
</div>
</div>
<br />
<div class="control-group">
<div class="controls">
<label>Second Selectbox</label><br />
<select class="secondSelectBox validate[required]">
<option value="A">Select 1</option>
<option value="B">Select 2</option>
<option value="C">Select 3</option>
<option value="D">Select 4</option>
<option value="E">Select 5</option>
</select>
</div>
</div>

change select option by javascript

i have problem in javascript
i make carwebsite
i need to achieve functionality as per the image
when I choose company in "make" select box,
it shows me all classes. Then I need to choose a "class" from second dropdown and it should show me all Models
now i get one code
<script type="text/javascript">
$(document).ready(function(){
$('.car').change(function()
{ getcar = $(this).val();
//console.log(getcar);
$('.subcar').hide();
$('.'+getcar).show();
}); });
// end DOM
</script>
this is select (make)
<select name="car" class="car">
<option value="0" SELECTED="SELECTED">--Choose--</option>
<option value="Acura">Acura</option>
<option value="Alfa_Romeo">Alfa Romeo</option>
<option value="Aston_Martin">Aston Martin</option>
<option value="Audi">Audi</option>
<option value="Bentley">Bentley</option>
<option value="BMW">BMW</option>
<option value="Buick">Buick</option>
<option value="Cadillac">Cadillac</option>
<option value="Can_Am">Can Am</option>
<option value="Chery">Chery</option>
<option value="Chevrolet">Chevrolet</option>
<option value="Chrysler">Chrysler</option>
<option value="Citroen">Citroen</option>
<option value="Daihatsu">Daihatsu</option>
<option value="Dodge">Dodge</option>
<option value="Ducati">Ducati</option>
<option value="Ferrari">Ferrari</option>
<option value="Fiat">Fiat</option>
<option value="Ford">Ford</option>
<option value="GMC">GMC</option>
</select>
this is select (class)
<select name="branch_name" class="subcar Acura" style="display:none;">
<option value="0" SELECTED="SELECTED" DISABLED="DISABLED">- None -</option>
<option value="CL">CL</option>
<option value="CSX">CSX</option>
<option value="EL">EL</option>
<option value="ILX">ILX</option>
<option value="ZDX">ZDX</option></select>
<select name="branch_name" class="subcar Alfa_Romeo" style="display:none;">
<option value="0" SELECTED="SELECTED" DISABLED="DISABLED">- None -</option>
<option value="101">101</option>
<option value="156">156</option>
<option value="156CROSSWAGON">156CROSSWAGON</option>
<option value="Spider">Spider</option>
</select>
<select name="branch_name" class="subcar Aston_Martin" style="display:none;">
<option value="0" SELECTED="SELECTED" DISABLED="DISABLED">- None -</option>
<option value="DB9">DB9</option>
<option value="Healey">Healey</option>
<option value="Vantage">Vantage</option>
</select>
how can i make third select
???

Categories