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);
Related
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 have a select with loads of options. (Code below shortened for sake of example).
I want it to set the value of the input textfield "hoh" to "10" when you click/select all dropdown options, except one, that should set it to 50.
I imagined something like this would work, but its not. What am I doing wrong here?
<select>
<option onselect="document.getElementById('hoh').value = '50'">Hey</option>
<option onselect="document.getElementById('hoh').value = '10'">Ho</option>
<option onselect="document.getElementById('hoh').value = '10'">Lo</option>
....
</select>
<input type="text" id="hoh" value="10">
Something like this should work:
<script>
function myFunc(val) {
if (val == '50') {
document.getElementById('hoh').value = val;
} else {
document.getElementById('hoh').value = '10';
}
}
</script>
<select onchange="myFunc(this.value)">
<option value="1">one</option>
<option value="2">two</option>
<option value="50">fifty</option>
</select>
http://jsfiddle.net/isherwood/LH57d/3
The onselect event refers to selecting (or highlighting) text. To trigger an action when a dropbox selection changes, use the onchange event trigger for the <select> element.
E.g. Since you didn't already set the value attribute of your option tags.
<select id="myselect" onchange="myFunction()">
<option value="50">Hey</option>
<option value="10">Ho</option>
<option value="10">Lo</option>
....
</select>
and somewhere inside of a <script> tag (presumably in your HTML header) you define your javascript function.
<script type="text/javascript>
function myFunction() {
var dropbox = document.getElementById('myselect');
document.getElementById('hoh').value = dropbox[dropbox.selectedIndex].value;
}
</script>
I'm not sure it's wise to repeat the same value among different options in a droplist, but you could expand on this to implement the result other ways, such as if the sole option which will have value 50 is in a certain position, you could compare the selectedIndex to that position.
you could add an onchange event trigger to the select, and use the value of an option to show in the textbox
see http://jsfiddle.net/Icepickle/5g5pg/ here
<select onchange="setValue(this, 'hoh')">
<option>-- select --</option>
<option value="10">Test</option>
<option value="50">Test 2</option>
</select>
<input type="text" id="hoh" />
with function setValue as
function setValue(source, target) {
var tg = document.getElementById(target);
if (!tg) {
alert('No target element found');
return;
}
if (source.selectedIndex <= 0) {
tg.value = '';
return;
}
var opt = source.options[source.selectedIndex];
tg.value = opt.value;
}
Try this code
var inp = document.getElementById('hoh');
sel.onchange = function(){
var v = this.value;
if( v !== '50'){
v = '10';
}
inp.value = v;
};
I looked for a solution for this, but couldn't find it.
I have a simple select like this:
<select id="sltFiltroPedidos">
<option value="todos">Todos</option>
<option value="hoje">de hoje</option>
<option value="semana">da semana</option>
<option value="periodo">Período</option>
<option value="pedido">Número do pedido</option>
</select>
Always the user clicks on an option, a javascript event must be fired.
The onChange event in the select doesn't work for me, because the user can choose the same option, and the event must be fired as well.
I tried the onClick event on options. It works on IE and FF, but doesn't work on Chrome.
Any ideas how can I do it?
I wrote a code but it is not working on IE, just give it a try: http://jsfiddle.net/shahe_masoyan/scuhb/1/
<select id="sltFiltroPedidos">
<option value="todos">Todos</option>
<option value="hoje">de hoje</option>
<option value="semana">da semana</option>
<option value="periodo">Período</option>
<option value="pedido">Número do pedido</option>
</select>
var isOpen = false;
$('#sltFiltroPedidos').on('mouseup', function () {
if (isOpen){
alert(this.value);
}
isOpen = !isOpen;
});
As per your question you can do following :-
<select id="sel" onblur="showme()">
<option value="todos" >Todos</option>
<option value="hoje" >de hoje</option>
<option value="semana" >da semana</option>
<option value="periodo" >Período</option>
<option value="pedido" >Número do pedido</option>
</select>
But i don't know this right option or not. But this will work as you told.
function showme()
{
alert(document.getElementById('sel').value);
}
You can try onclick like,
var prevValue=$('select').val();
$('select').on('click',function(){
if(prevValue==this.value) // code for same values
// your code to run
});
I had the same issue. In my task, I needed to get the value of the selected option. This helped me:
let selectedOption = "";
<select>.addEventListener("change", event => {
selectedOption = event.target.value
});
The select variable is, obviously, the tag .
It might look strange, but select takes the value of the chosen option, that's why the code works.
Use:
$('#sltFiltroPedidos').on('change', function() {
alert( this.value );// or this.val()
});
Hope this will work for you
I was wondering what am I doing wrong here?
I have the following HTML:
<select name="somename" id="DropDownList1">
<option value=""></option>
<option value="1" valp="7700000000000000">Item 1</option>
<option value="2" valp="7C08000000000000">Item 2</option>
<option value="3" valp="5800000000000000">Item 3</option>
</select>
And the following JS/JQuery code that is called when the page loads:
$('#DropDownList1').change(function () {
onChangeDropDownList1(this);
});
function onChangeDropDownList1(obj) {
var vP = $(obj).attr('valp');
alert("valp=" + vP);
};
As the result I get "valp=undefined"
this in context of the .change() refers to the <select> rather than the <option>, so you're not getting the node with the valp attribute.
$('#DropDownList1').change(function () {
onChangeDropDownList1(this);
});
function onChangeDropDownList1(obj) {
// Get the selected option
var vP = $(obj).find(':selected').attr('valp');
alert("valp=" + vP);
};
Here is a demonstration.
The change function is providing you the select which was updated not the option. You need to query the :selected value out of it. Once you have the selected option you can query for the valp attribute
function onChangeDropDownList1(obj) {
var vP = $(obj).find('option:selected').attr('valp');
alert("valp=" + vP);
};
Fiddle: http://jsfiddle.net/Jpfs3/
Pass the option, not the select:
onChangeDropDownList1($(this).children(':selected'));
or, grab the option from the passed select:
var vP = $($(obj).children(':selected')).attr('valp');
Just put the JS code before the end of the body