I am trying to run 2 functions according to the value selected by drop-down box.
Code:
var activities = document.getElementById("stand");
activities.addEventListener("change", function() {
if (activities.options[activities.selectedIndex].value == "stand1") {
var footRight = new THREE.Mesh(new THREE.BoxGeometry(.040, 0.55, 0.05), wallMaterial);
partitionLeft.add(footRight);
footRight.position.set(-0.12, -0.11, 2);
} else {
var footRight = new THREE.Mesh(new THREE.BoxGeometry(.040, 0.55, 0.05), wallMaterial);
partitionLeft.add(footRight);
footRight.position.set(-4.12, -8.9, 6);
}
});
<div id="door-stand">
<label>Select the stand type:</label>
<select id="stand">
<option class="stand1" value="stand1"> Stand 1 </option>
<option class="stand2" value="stand2"> Stand 2 </option>
</select>
</div>
The issue is even-though the values from the drop-down list keep changing, any of the above functions ain't trigger.
I tried to print something when the value changed in drop-down list; but, anything did not print at all.
There is a console error when I change the values in the drop-down. The console error pops up only when changing the values. That's why I haven't noticed. It says
wallMaterial not defined
As you can see, after removing all the unnecessary code, this simple snippet works as expected:
const activities = document.getElementById('stand');
activities.addEventListener('change', (e) => {
console.log(`e.target.value = ${ e.target.value }`);
console.log(`activities.options[activities.selectedIndex].value = ${ activities.options[activities.selectedIndex].value }`);
});
<select id="stand">
<option class="stand1" value="stand1">Stand 1</option>
<option class="stand2" value="stand2">Stand 2</option>
</select>
This means there might be something else wrong in your code:
Maybe something is erroring out:
const activities = document.getElementById('stand');
activities.addEventListener('change', (e) => {
console.log('Change START');
activities.nonexistentFunction();
console.log('Change END');
});
<select id="stand">
<option class="stand1" value="stand1">Stand 1</option>
<option class="stand2" value="stand2">Stand 2</option>
</select>
Maybe you have some other change listeners that are calling Event.stopImmediatePropagation():
const activities = document.getElementById('stand');
activities.addEventListener('change', (e) => {
e.stopImmediatePropagation();
console.log('Change 1');
});
activities.addEventListener('change', (e) => {
console.log('Change 2');
});
<select id="stand">
<option class="stand1" value="stand1">Stand 1</option>
<option class="stand2" value="stand2">Stand 2</option>
</select>
You can use this.value to access the value of selected option inside your callback function:
document.getElementById('stand').onChange = function(){
console.log(this.value);
});
Related
Given a standard select as per below, is is possible by jQuery (or otherwise) to trigger a change event on individual options - As multiple may be selected, I don't want to trigger on the select but on the option?
<select multiple="">
<option>Test 2</option>
<option>Testing 3</option>
</select>
Something like:
$(`option`).trigger(`change`);
One way is to keep a reference of the last state of the multi-select, then compare to find the most recently clicked option.
let sels = [];
$(`select`).on(`change`, function() {
$(this).val().forEach(v => {
if (sels.indexOf(v) === -1) {
console.log(`The option most recently selected is ${v}`);
}
})
sels = $(this).val();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple="">
<option value='2'>Test 2</option>
<option value='3'>Testing 3</option>
</select>
There is no change on an option. If you want it to act like a user is selecting option by option in the select, you would need to select the option and trigger the change event on the select.
const mySelect = document.querySelector("#mySelect");
mySelect.addEventListener("change", function () {
const selected = Array.from(mySelect.querySelectorAll("option:checked")).map(x => x.value);
console.log(selected);
});
function triggerEvent(elem, event){
const evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true );
elem.dispatchEvent(evt);
}
const values = ['1','2','4'];
values.forEach(val => {
const opt = mySelect.querySelector(`[value="${val}"]`);
if (opt) {
opt.selected = true;
triggerEvent(mySelect, 'change');
}
});
/*
const values = ['1','2','4'];
const options = mySelect.querySelectorAll("option");
options.forEach(opt => {
const initial = opt.selected;
opt.selected = values.includes(opt.value);
if (opt.selected !== initial) {
triggerEvent(mySelect, 'change');
}
});
*/
<select id="mySelect" multiple>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
The real solution is why is your page not set up to handle default values? Seems like you should just be able to call a method with the values and be done. Seems odd to rely on events.
given:
<select id="mySelect">
<option>..</option>
...
</select>
Using the select id, how can I trigger a click event on one of the options? I tried attaching the event directly to the select, but this triggers an event whenever the select is clicked on (even if there are no options). Oh, and it is a multi-select (although I don't think that matter).
You want the 'change' event handler, instead of 'click'.
$('#mySelect').change(function(){
var value = $(this).val();
});
$('#mySelect').on('change', function() {
var value = $(this).val();
alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<select id="mySelect">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
<option value='8'>8</option>
</select>
EXAMPLE
you can attach a focus event to select
$('#select_id').focus(function() {
console.log('Handler for .focus() called.');
});
The problem that I had with the change handler was that it triggered on every keypress that I scrolled up and down the <select>.
I wanted to get the event for whenever an option was clicked or when enter was pressed on the desired option. This is how I ended up doing it:
let blockChange = false;
$element.keydown(function (e) {
const keycode = (e.keyCode ? e.keyCode : e.which);
// prevents select opening when enter is pressed
if (keycode === 13) {
e.preventDefault();
}
// lets the change event know that these keypresses are to be ignored
if([38, 40].indexOf(keycode) > -1){
blockChange = true;
}
});
$element.keyup(function(e) {
const keycode = (e.keyCode ? e.keyCode : e.which);
// handle enter press
if(keycode === 13) {
doSomething();
}
});
$element.change(function(e) {
// this effective handles the click only as preventDefault was used on enter
if(!blockChange) {
doSomething();
}
blockChange = false;
});
You can also try this to get previous value of select and the clicked value.
HTML
<select name="status">
<option value="confirmed">confirmed</option>
<option value="packed">packed</option>
<option value="shiped">shiped</option>
<option value="delivered">delivered</option>
</select>
script
var previous;
$("select[name=status]").focus(function () {
previous = this.value;
}).change(function() {
var next = $(this).val()
alert("previous: "+previous+ " and Next: "+ next)
previous = this.value;
});
<select name="data" id = 'cohort' class="form-control" style = "width:215px; margin-left:20px; margin-bottom:8px ; height:30px" >
<option value = 0>All</option>
<option value = 1>Diseases</option>
<option value = 2>Drugs</option>
<option value = 3>Procedures</option>
</select>
const element = document.getElementById("cohort");
const event = new MouseEvent("mousedown");
element.dispatchEvent(event);
What I have done in this situation is that I put in the option elements OnClick event like this:
<option onClick="something();">Option Name</option>
Then just create a script function like this:
function something(){
alert("Hello");
}
UPDATE:
Unfortunately I can't comment so I'm updating here
TrueBlueAussie apparently jsfiddle is having some issues, check here if it works or not: http://js.do/code/klm
its working for me
<select name="" id="select">
<option value="1"></option>
<option value="2"></option>
<option value="3"></option>
</select>
<script>
$("#select > option").on("click", function () {
alert(1)
})
</script>
One possible solution is to add a class to every option
<select name="export_type" id="export_type">
<option class="export_option" value="pdf">PDF</option>
<option class="export_option" value="xlsx">Excel</option>
<option class="export_option" value="docx">DocX</option>
</select>
and then use the click handler for this class
$(document).ready(function () {
$(".export_option").click(function (e) {
//alert('click');
});
});
UPDATE: it looks like the code works in FF, IE and Opera but not in Chrome.
Looking at the specs http://www.w3.org/TR/html401/interact/forms.html#h-17.6 I would say it's a bug in Chrome.
I have a set of input/options:
<input type="checkbox" id="Devices001Master" class="Metals" value="Steel" onchange="ReDraw()">
<select id="Devices001" onchange="Devices001func()">
<option value="Steel">Steel</option>
<option value="Steel_1">Steel 1</option>
<option value="Steel_2">Steel 2</option>
<option value="Steel_3">Steel 3</option>
<option value="Steel_4">Steel 4</option>
<option value="Steel_5">Steel 5</option>
</select>
I'm able to, onchange, change the value of the input based on what's being selected in the options. Followed by my redraw function that works exactly as intended. This works fine for 1 set at a time:
function Devices001func(){
let Devices001Master = document.getElementById("Devices001Master");
let Devices001 = document.getElementById("Devices001");
Devices001Master.value = Devices001.value;
ReDraw();
};
My problem: Say I have something like 100 sets of input/options all with different types of "Metals". I could reproduce my 6-line "Devices001func()" for each of the 100 sets but that's 600 lines. I would gladly appreciate anyone who can point me to a vanilla JS approach to take here.
Cheers!
You can make use of event bubbling:
document.body.addEventListener('change', event => {
const masterElement = document.getElementById(event.target.id + 'Master');
if (masterElement !== null) {
masterElement.value = event.target.value;
ReDraw();
};
});
I have HTML :
<select id="select">
<option selected="selected" value="amon_amarth">Amon Amarth</option>
<option value="arch_enemy">Arch Enemy</option>
<option value="children_bodom">Children of_bodom</option>
<option value="dark_tranquillity">Dark tranquillity</option>
<option value="death">Death</option>
<option value="ensiferum">Ensiferium</option>
<option value="korpiklaani">Korpiklaani</option>
<option value="norther">Norther</option>
<option value="white_skull">White skull</option>
</select>
<button id="play">play</button>
Then I receive value from select option:
$(document).ready(function() {
$("select").on('change', function () {
let value = $(this).val().toString();
let clicksound = ss_soundbits('sound/' + music.value);
$('#play').click(function () {
// ss_soundbits('sound/' + music.value).playclip();
clicksound.playclip();
console.log(music);
console.log(value);
console.log(music.value);
});
})
});
console.log(music) - is my object, it is ok:
Object { amon_amarth: "amon_amarth_the_pursuit_of_vikings_(NaitiMP3.ru).mp3", arch_enemy: "Arch_Enemy-09_Ravenous_(muzroom.online).mp3", children_bodom: "children_of_bodom_are_you_dead_yet_(NaitiMP3.ru).mp3", dark_tranquillity: "dark_tranquillity_-_haven_2000_-_dark_tranquillity_-_rundown_(zf.fm).mp3", death: "death_-_painkiller_gon_nad_dzhudas_prist_(zf.fm).mp3", ensiferum: "ensiferum-ahti_(mp3CC.com).mp3", korpiklaani: "korpiklaani-midsummer-night_(mp3CC.com).mp3", norther: "Norther - Last Breath (ouronlyhope.org).mp3", white_skull: "white-skull-high-treason_(mp3CC.com).mp3", siplyi: "white-skull-high-treason_(mp3CC.com).mp3", … }
console.log(music) - is my value, it is ok as well: norther
But when I am trying to apply my value to Object (music.value) it says: undefined
Nevertheless it works if I put
<button onclick="clicksound.play()">
And have following code in my js file:
let clicksound = ss_soundbits('sound/' + music.amon_amarth);
What am I doing wrong? I spent all day to solve this problem. I can fix it with different buttons/div's but I still want to understand how can I fix current issue.
Thanks!
Please let me know if this is the result you're trying to achieve:
Btw, amazing musical taste :)
let music = {}
$(document).ready(function() {
$("select").on('change', function() {
let value = $(this).val();
music.value = value;
// let clicksound = ss_soundbits('sound/' + music.value);
$('#play').click(function() {
// ss_soundbits('sound/' + music.value).playclip();
// clicksound.playclip();
console.log(music);
console.log(value);
console.log(music.value);
});
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select">
<option selected="selected" value="amon_amarth">Amon Amarth</option>
<option value="arch_enemy">Arch Enemy</option>
<option value="children_bodom">Children of_bodom</option>
<option value="dark_tranquillity">Dark tranquillity</option>
<option value="death">Death</option>
<option value="ensiferum">Ensiferium</option>
<option value="korpiklaani">Korpiklaani</option>
<option value="norther">Norther</option>
<option value="white_skull">White skull</option>
</select>
<button id="play">play</button>
The dot notation of accessing values in an object is only when you are referring to the actual key itself. music.value means you want to retrieve the key-value pair whose key is literally called "value", which does not exist.
As per my comment, what you want is to use music[value] instead, where value is a variable that stores the reference you want.
On a side note, you should not be binding event handlers within event handlers: this causes the click event to be bound to the #play element every time a change event is fired, and this is extremely unperformant. See the refactored code below:
let clicksound;
$("select").on('change', function () {
let value = $(this).val();
clicksound = ss_soundbits('sound/' + music[value]);
});
$('#play').click(function () {
clicksound.playclip();
});
I want to change materialize select box value by jquery.
I am using $('#myselect').val('1'); on onchange event of other select box but it not works.
$("#select1").change(function() {
$('#myselect').val('1');
});
It appears to work fine for me, changing the first drop down, resets the value of the second drop down to 1.
I have done a rough implementation on jsFiddle: http://jsfiddle.net/55r8fgxy/1/
<select id="select1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<select id="myselect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
JS:
$(function() {
$("#select1").on('change', function() {
$('#myselect').val("1");
// re-initialize material-select
$('#myselect').material_select();
});
});
$('#myselect').formSelect() ;
The new method is formSelect(), use this after you have updated the select.
As suggested by #logikal, you have got to re-Initialize
$("#myselect").material_select()
In 2018 (Materialize v1.0.0-rc.2), first you have to set your option programmatically:
$('#SELECT-ID').find('option[value="SELECT-VALUE"]').prop('selected', true);
And then re-initialise the select input with:
$("#SELECT-ID").formSelect();
Hope it helps!
Rather than using .val(), it's cleaner to set value as usual with jQuery :
$('#my-select').find('option[value="my-value"]').prop('selected', true);
$("#my-select").material_select();
For a new materialize 1.0.0 use .select() instead of .material_select()
Solution without re-initialization.
function msValue (selector, value) {
selector.val(value).closest('.select-wrapper').find('li').removeClass("active").closest('.select-wrapper').find('.select-dropdown').val(value).find('span:contains(' + value + ')').parent().addClass('selected active');
}
Then just use
msValue($("#select_id"), "value_here")
This answer might be late but it might help someone else.
On Ready add the line below
$(document).ready(function () {
$('select').formSelect();
});
Each time you change an option within your Select add the line below
$("#select1").change(function() {
$('#myselect').val('1');
$('select').formSelect();
});
This is what worked for me, hope it helps.
Using delegated event fixes the problem for me.
HTML
<div class="input-field col s10" id="pickerContainer">
<select>
<option value="" disabled selected>Choose your option</option>
</select>
</div>
JS
$('#pickerContainer').on('change', 'select', function(){
console.log("got you");
});
Since JQuery is no longer a hard dependency of the Materialize library, one can easily update the select via the init static method with any of the lookup methods:
const reinitialize = (selector, value) => {
const element = document.querySelector(selector);
element.value = value;
const {
options
} = M.FormSelect.getInstance(element); //pass through initialization options;
return M.FormSelect.init(element, options);
};
A quick runnable demonstration:
(() => {
const reinitialize = (selector, value) => {
const element = document.querySelector(selector);
element.value = value;
const {
options
} = M.FormSelect.getInstance(element); //pass through initialization options;
return M.FormSelect.init(element, options);
};
const interval = (callback, delay = 250) => {
callback();
setTimeout(interval, delay, callback, delay);
};
M.AutoInit(); //initializes everything
interval(() => {
const id = "test";
const randVal = Math.floor(Math.random() * 3) + 1;
reinitialize("#" + id, randVal);
});
})();
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<div class="input-field col s12">
<select id="test">
<option value="" disabled selected>Choose your option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<label>Materialize Select</label>
</div>
Here is a version of the above for JQuery (to be fair to other answerers - this is a generalized version of this):
const updateSelect = (selector, value) => $(selector).val(value).formSelect();
Please, note that the actual core of every solution is (see docs):
you need to reinitialize the select component every time a value is updated non-natively
The rest depends on the version of Materialize used and whether one uses JQuery or not. It is also important to keep in mind that:
material_select() solutions are outdated! Use formSelect() as of Materialize 1.0.0
This is similar to what logikal answered but I think is cleaner:
$(".your-component-class").change(function(){
//your code..
//re-initialize component
$(this).material_select();
});
This was my solution in case it helps someone. I used a lot of what #Raold said.
the issue I had was the select was getting stuck when it's updated without the code below.
function updateSelect(value) {
var select = $('#myselectId');
$(select).val(value);
var text = $(select).find(':selected').text();
$(select).closest('.select-wrapper')
.find('li').removeClass("active")
.closest('.select-wrapper')
.find('.select-dropdown').val(text)
.find('span:contains(' + value + ')')
.parent()
.addClass('selected active');
}
Solution, I used in my project:
document.getElementById("mySelect").addEventListener("change", function()
{
console.log("Hello, World!")
});
I don't know if the event trigger gives you selected item or selected item's value - you can check it yourself!
const selectObj = document.querySelector('#select');
selectObj.value = "new value";
const {
options
} = M.FormSelect.getInstance(selectObj);
M.FormSelect.init(selectObj, options);