Get previously selected value or prevent default on select - javascript

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

Related

Select item from multiple select menu

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>

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/

Changing form select class when any option is selected apart from one

so i have a working feature that when a user selects any option on my select input, will change the selects class.
This works fine, but what i want is that if the user selects the first option again, then the class gets changed back.
the first option is set as a placeholder, i cant give it a value as i only want the information to be posted if any other options are selected.
I also cant set the input as disabled as i want the user to be able to reselect it after, incase they dont want to post that data.
its a long check list and i am posting the data as an array.
here is a jsfiddle to what i currently have:
http://jsfiddle.net/SD7cd/1/
Code:
<select id="sel1" class="selectoption" name="desc[]">
<option selected="selected">Select an option...</option>
<option value="1">Option 1</option>
</select>
JS:
document.getElementById("sel1").onchange = function() {
if(this.value != null && this.value != undefined)
{
this.className = "selectoption-okay";
}
};
I'd use the .selectedIndex property over the value like this:
document.getElementById("sel1").onchange = function () {
this.className = (this.selectedIndex != 0) ? "selectoption-okay":"selectoption";
};
jsFiddle example
One problem when you used if(this.value != null && this.value != undefined) is that the first option will have a value even though you didn't explicitly assign it. An option element's value will default to its contents if no value is expressly given, no it won't ever be null or undefined.
Per MDN:
The textual content of this attribute represents the label explaining
the option. If it is not defined, its default value is the text
content of the element.
Can you try this, When you select the option Select an option..., if you have not assigned the value='' then Select an option... will be taken as a value.
So Added
<option selected="selected" value="">Select an option...</option>
^^^^^^^^
HTML:
<select id="sel1" class="selectoption" name="desc[]">
<option selected="selected" value="">Select an option...</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
Javascript:
document.getElementById("sel1").onchange = function() {
this.className = "selectoption";
if(this.value != '' )
{
this.className = "selectoption-okay";
}
};
DEMO: http://jsfiddle.net/SD7cd/4/

Alternative to .change in jquery?

I'm trying to fire an ajax event, and passing the value of select list options as arguments in the ajax call. Unfortunately, I'm firing the call on the .change event, and it is passing the values of the select option before the new option has been selected (i.e passing the previously selected options values). Is there an event which will get the current values of the option selected? Much thanks in advance,
<select id='theList'>
<option> Option 1</option>
<option> Option 2</option>
</select>
In the JS:
$('#theList').change( function() {
$.getJSON('Home/MethodName', { var1: Option1Value, var2: MiscValue}, function(data) {
//Execute instructions here
}
)});
I wanted to use .trigger, but I think that fires beforehand as well.
I think .change() is what you want, but you're misusing it. The change event fires after the value has changed. In your handler, you need to read the new value:
$('#theList').change( function() {
var value = $('#theList').val();
$.getJSON('Home/MethodName', { your_key: value }, function(data) {
// ...
}
)});
You also might want to set values on your <option> tags:
<option value="something"> Option 2</option>
You must be doing something wrong when getting the current select value. The following works correctly for me.
http://jsfiddle.net/TJ2eS/
<select id="demo">
<option value=""></option>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
$("#demo").change(function() {
alert("current select value " + $(this).val());
});
A word of warning, .change is now defunct, you should use...
.on('change', function()
Like that.

Categories

Resources