Select item from multiple select menu - javascript

This is a strange bug I have in my script.
When I click the option "Test", the alert appears.
However when I select it (using the control key) it doesn't alert.
As a test, ctrl select 'Desktop' then click 'Test'. You'll see no Alert :(
Why is this?
JS:
var $cb = document.querySelector("#equipments");
$cb.addEventListener("change", function() {
if ($cb.value == "test") {
// if true
alert("Selected!");
} else {
// false
}
})
HTML
<select id="equipments" name="equipments[]" multiple="multiple" class="form-control" multiple data-live-search="true" required>
<option value="laptop">Laptop</option>
<option value="desktop">Desktop</option>
<option value="test" >Test</option>
<option value="none">None</option>
</select>
Fiddle: https://jsfiddle.net/0mvngqsc/

You cannot. The change event does not define ctrlKey, as you have noted.
change is an event which uses the base event interface, which does not handle ctrlKey. To have ctrlKey defined, you need to use a TouchEvent, MouseEvent, or KeyboardEvent.

there is a property called selectedOptions which gives us the object of the selected items.i am just iterating through that object using for of.unfortunately couldn't get it working on change event.i hope this helps you to reach your results
var $cb = document.querySelector("#equipments").selectedOptions;
var $sb = document.querySelector("#submit");
$sb.addEventListener("click", function () {
for (let el in $cb) {
console.log($cb[el].value);
if ($cb[el].value == "test") {
// if true
alert("Selected!");
}
else {
// false
}
}
})
<select id="equipments" name="equipments[]" multiple="multiple" class="form-control" multiple
data-live-search="true" required>
<option value="laptop">Laptop</option>
<option value="desktop">Desktop</option>
<option value="test">Test</option>
<option value="none">None</option>
</select>
<button id="submit">Submit</button>

Related

How to set new value of the Angular directive "ng-init" depending on the value of a <select> dropdown box?

So I want to set a value for ng-init if a specific option is selected. If that specific option is not selected yet, or is changed away from, I'd like to delete the ng-init value.
<select id="exSelect" onchange="checkButton()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<textarea type="text"
class="form-control"
ng-model="vm.request.description"
name="description" id="description"
rows="10" placeholder="Must be atleast 50 characters."
ng-minlength="50"
required>
</textarea>
function checkButton()
{
var dropdownValue = document.getElementById("exSelect");
if (dropdownValue.value == "3") {
//Why does this not work?
document.getElementById("description").ng-init = 'Example attribute setting';
} else {
document.getElementById("description").ng-init = '';
}
}
This code is super simplified example version of what I am working on right now, but overall a similar idea of what I am trying to do as a small part of a much larger program. So I would like for the checkButton() function to run each time a new option is selected. If 3 is selected, I would like the if statement to execute and set the "ng-init" attribute of the element with the Id of "description" as the text in the function. If another option is selected, I would like for the checkButton() function to run again and it will set the the ng-init attribute as empty.
First use the ng-model and ng-change directives:
<select id="exSelect" ng-model="vm.sel1" ng-change="vm.checkButton()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
Then in your controller:
vm.checkButton = function() {
if (vm.sel1 == "3") {
vm.request.description = 'Example attribute setting';
} else {
vm.request.description = = '';
};
});

How to always trigger function of <select> tag

I wrote a select tag (have default selected) and take the option value to trigger another js function:
var selectElement = document.getElementById("sel");
function somefunction() {
console.log(selectElement.value);
};
<select id="sel" onchange='somefunction()'>
<option selected="selected" value='yes'>Yes</option>
<option value='no'>No</option>
<option value='all'>All</option>
</select>
However, if I keep the onchange event, it only triggers the function when I change the selection. I also want to trigger the function when page is loaded with the default selection that i have set (which is Yes in the above example).
Thanks.
Add an onload function to your body tag:
<body onLoad='somefunction()'>
What I would recommend is to build an independent function for calculating the selected index. Then I would manually map a variable to the <select> element, and attach an onchange() handler than calls this function, passing itself in as a parameter.
With this setup, you have both a function to calculate the selected value of any <select> element, and the target <select> element already mapped to a variable for easy access. You can then simply pass that variable into the function on page load:
/* Function to grab the selection, which takes a `<select>` element as a parameter */
function getSelectedIndexes(select) {
for (var i = 0; i < select.options.length; i++) {
if (select.options[i].selected) {
return i;
}
}
}
var select = document.getElementsByTagName("select")[0];
select.onchange = function(e) {
console.log(getSelectedIndexes(this)); // Selection on change
}
console.log(getSelectedIndexes(select)); // Default selection
<select>
<option disabled selected> Select
</option>
<option selected="selected" value='yes'> Yes
</option>
<option value='no'> No
</option>
<option value='all'> All
</option>
</select>
Hope this helps! :)
Why don't you call the function when the window is loaded? I guess that will solve
your problem.
window.onload = function() {
if (selectEl.value) // or use (selectEl.value == "yes)
somefunction()
};
var selectEl = document.getElementById("sel");
function somefunction() {
console.log(selectEl.value);
}
<select id="sel" onchange='somefunction()'>
<option selected="selected" value='yes'>Yes</option>
<option value='no'>No</option>
<option value='all'>All</option>
</select>

JQuery , syncronized selection option

I have to tag in my jsp with two identical select option.
I want that anytime I am chaining one , the second (that is in the bottom ) will change too.
<select class="groups">
<option class='America' value='America'>America</option>
<option class='Europe' value='Europe'>Europe</option>
<option class='Asia' value='Asia'>Asia</option>
<select>
<select class="groups">
<option class='America' value='America'>America</option>
<option class='Europe' value='Europe'>Europe</option>
<option class='Asia' value='Asia'>Asia</option>
<select>
So for instance anytime I am choosing Europe ( or any other ) I want all of my select get updated with the same value.
without jquery:
document.getElementsByClassName("groups").forEach(function(element){
element.onchange = function(event) {
document.getElementsByClassName("groups").forEach(function(x){
x.value = event.target.value;
});
}
});
with jquery:
$('.groups').onchange = function(e){
$('.groups').forEach(function(x){
x.val(e.currentTarget().val)
});
}

how to change a value of drop down and to trigger a onchange functions in javascript

I was wondering if it is possible to change a value of a dropdown box dynamically and to trigger an ajax onchange function assigned to this dropdown at the same time.
so far I can only change the value of a dropdown box but the onchange function is not being called.
here is the dropdown:
<select name="ProductSelector" id="ProductSelector" onchange="getItems(this.value)">
<option value="">--Select Item--</option>
<option value="one"> Option one</option>
<option value="two"> Option Two</option>
<option value="three"> Option Three</option>
</select>
when I do this operation:
document.getElementById("ProductSelector").value = "one";
the value of the dropdown is changing, but the getItems function is not being triggered.
What am I doing wrong or may be there is another way to change a value of the doropdown which will allow me to trigger my ajax function as well?
I don't want to use JQuery. I just wandering why the function is not working if I use dinamic change and on manual change it works fine?
So, you are changing the value with JavaScript and the change event isn't triggering. So, lets trigger it then.
Trigger the event change every time you change the value via JavaScript.
No jQuery used.
Try this:
function changeVal() {
var elem = document.getElementById("ProductSelector"),
event = new Event('change');
elem.value = "one";
elem.dispatchEvent(event);
}
function getItems(val) {
alert(val);
}
changeVal();
<select name="ProductSelector" id="ProductSelector" onchange="getItems(this.value)">
<option value="">--Select Item--</option>
<option value="one">Option one</option>
<option value="two">Option Two</option>
<option value="three">Option Three</option>
</select>
I mostly do it this way:
HTML:
<select class="class-name">
<option value="1">1</option>
<option value="2">2</option>
</select>
jQuery:
$(".class-name").on("change", function() {
var value = $(this).val();
$.ajax({
type: "post",
url: "your-php-script.php",
data: { 'value' : value },
success: function (data) {
alert('This has changed');
}
);
});
Problem is changing the value with JS will not trigger the change event. Best solution would be to write a function which changes the value and triggers the change event manually.
HTML
<select name="ProductSelector" id="ProductSelector">
<option value="">--Select Item--</option>
<option value="one"> Option one</option>
<option value="two"> Option Two</option>
<option value="three"> Option Three</option>
</select>
JS (no jQuery)
//define the element so we can access it more easily
var element = document.getElementById('ProductSelector');
//define the event we want to trigger manually later
var event = new Event('change');
//add eventlistener which is triggered by selecItem()
element.addEventListener('change', function(event) {
getItems(event.target.value);
});
function getItems(val) {
alert(val);
}
//set the value and trigger the event manually
function selectItem(value){
//select the item without using the dropdown
element.value = value;
//trigger the event manually
element.dispatchEvent(event);
}
//using a function with the option you want to choose
selectItem("three");
JSFiddle
Use the working JSFiddle: Note that you have to uncomment the last line of code.
<html>
<body>
Select your favorite value:
<select id="mySelect">
<option value="value1">value1</option>
<option value="value2">value2</option>
<option value="value3">value3</option>
<option value="value4">value4</option>
</select>
<script>
$(document).ready(function() {
$( "#mySelect" ).change(function() {
var value = $(this).val();
$.ajax({
type: "post",
url: "request-url.php",
data: { 'value' : value },
success: function (data) {
alert('the ajax request has been send');
}
);
});
});
</script>
</body>
</html>
You can try removing the onchange="" attribute from the select input and just use the jQuery to check for changes:
$('body').on('change', "#ProductSelector", function(){
var id = $(this).val();
//now do your ajax call with the value selected
});
"What am I doing wrong or may be there is another way to change a value of the doropdown which will allow me to trigger my ajax function as well?"
Another way of adding the event listener is by doing it "unobtrusive style".
document.getElementById('ProductSelector').addEventListener('change', function(event) {
getItems(event.target.value);
});
function getItems(val) {
// Todo: whatever needs to be done :-)
alert(val);
}
<select name="ProductSelector" id="ProductSelector">
<option value="">--Select Item--</option>
<option value="one">Option one</option>
<option value="two">Option Two</option>
<option value="three">Option Three</option>
</select>
http://jsfiddle.net/dytd96cb/

Get previously selected value or prevent default on select

Is it possible on <select> get previously selected value or prevent default somehow? For example i have
<select id="select_site" name="sites" selectedindex="0">
<option value="">Please select site</option>
<option value="4">first</option>
<option value="5" selected="selected">second</option>
<option value="8">third</option>
</select>
So if selected option with null value i need to restore previously selected second value.
You can bind a change event handler to the element and store the new value in a variable. If the value is an empty string, set it to whatever is in the variable:
$('#select_site').change(function() {
if (this.value === '') {
this.value = $(this).data('previous_value');
}
else {
$(this).data('previous_value', this.value);
}
}).triggerHandler('change'); // <- trigger change event to get initial value
DEMO
no js needed:
<select id="select_site" name="sites" selectedindex="0">
<optgroup label="Please select site">
<option value="4">first</option>
<option value="5" selected="selected">second</option>
<option value="8">third</option>
</optgroup>
</select>
demo: http://jsbin.com/obeker/1/
ref: https://developer.mozilla.org/docs/HTML/Element/optgroup
No you cannot do that because the change event is fired after the select is focused out, not before the selection is changed. There is no native "onbeforechange" event but you can remove the empty value once the selection is changed so it is no longer available.
Code to do this:
$('select').change(function (event) {
$this = $(this);
if ($this.val() !== '') {
$this.children('option:first').remove();
}
});

Categories

Resources