JS getting value from select option applying to object - undefined - javascript

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();
});

Related

Issue with get selected option and return

I have an issue with the return value in js. I need to return it because I wanna use it in
var rusiavimas = selectedServices();
So, my function looks like this.
function selectedServices()
{
var selectedServices = [];
$('.common_change').change(function(){
selectedServices = $(this).val();
alert(selectedServices);
});
return selectedServices;
}
My HTML code
<select name="rusiavimas" class="common_change" id="cars">
<option value="none" selected disabled hidden>
Pasirinkite variantą
</option>
<option value="naujausi">Naujausi viršuje</option>
<option value="pigiausi" >Pigiausi viršuje</option>
<option value="brangiausi">Brangiausi viršuje</option>
</select>
Then I select the option, in the alert function I get the correct value, but in my return, it's not returning it.
Your code contains a lot of problem, I try to fix them below
Your JS script is always return an empty array, because when you call the function var rusiavimas = selectedServices(); the inner .change function is not runs and not change the value of the array
var selectedServices = [];
$('.common_change').change(function(){
selectedServices.push($(this).val());
if(selectedServices.length > 0){
alert("selected service: " + selectedServices.toString());
}
console.log(selectedServices);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="rusiavimas" class="common_change" id="cars">
<option value="none" selected disabled hidden>
Pasirinkite variantą
</option>
<option value="naujausi">Naujausi viršuje</option>
<option value="pigiausi" >Pigiausi viršuje</option>
<option value="brangiausi">Brangiausi viršuje</option>
</select>
Each time after changing your array it gives to your array the last common value.
The best way as was said an comments use selectedSerices.push($(this).val());
You can also use deep copy, which is less recommended in your case selectedSerices = [...selectedSerices, $(this).val()]. I guess it will help you!

Get the value from the select tag in html, i know this will show that is possibly duplicate but please take a look

I am trying to get the value from the selector tag in html and pass it to another function which is called myFunction. But the error says that it is null.
< script >
(function() {
var selector = document.getElementById("carSelector");
var value = selector[selector.selectedIndex].value;
console.log(value);
document.getElementById('carsButton').onclick = function() {
myFunction(value);
};
}());
</script>
<div class="selectList">
<select name="cars" id="carSelector">
<option value="audi">Audi</option>
<option value="volvo">Volvo</option>
<option value="Kia">Kia</option>
</select>
<button id="carsButton" type="button">Show car</button>
</div>
The code should get the car type from the selector and pass it to the function myFunction.
Slight typo (id should be carsButton) and I rearranged the code a little - you were expecting a named function - but not providing one.
You don't really need the named function - you could just log the selected value to the console within the onclick handler - but so that you can practise passing values between function - I left it in.
Also - you only need "(function() {}) if you are using jQuery - oits not needed for this - but again - I left it in - in case you needed it for something else.
(function() {
document.getElementById('carsButton').onclick = function() {
var selector = document.getElementById("carSelector");
var value = selector.value;
myFunction(value);
};
function myFunction(value) {
console.log(value);
}
}());
<div class="selectList">
<select name="cars" id="carSelector">
<option value="audi">Audi</option>
<option value="volvo">Volvo</option>
<option value="Kia">Kia</option>
</select>
<button id="carsButton" type="button">Show car</button>
</div>
You can just get the value of the <select> - it'll be the value of the selected option:
function show() {
var select = document.getElementById("carSelector");
var value = select.value;
console.log(value);
}
<select name="cars" id="carSelector">
<option value="audi">Audi</option>
<option value="volvo">Volvo</option>
<option value="Kia">Kia</option>
</select>
<button id="carsButton" type="button" onclick="show()">Show car</button>
you probably meant to get the item from selector.options, selector won't have anything at selector.selectedIndex it will be undefined
var value = selector.options[selector.selectedIndex].value;

addEventListener onchange dropdown selected value Javascript

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);
});

Change value of materialize select box by jquery

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);

Get custom html attribute from <select> control with JQuery

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

Categories