Change selected item from inside onchange event - javascript

In the following select box:
var sval=1;
function foo(v) {
sval=Number(v);
}
...
<select name="sval" onchange="
if (confirm('...?')) foo(this.value); else $(this).val(sval);">
<option value="1">1
<option value="2">2
<option value="3">3
The idea is to confirm the selected item change. If not confirmed to change back to the old value.
if confirm returns true, all is working as expected
if confirm returns false, then the select always gets value 1, regardles of sval
Why changing the selected item does not work from inside the onchange handler?
EDIT: The following code based on ejay_francisco's answer does the proper job:
http://jsfiddle.net/4wCQh/33/
var vals = 1;
$("#svalue").change(function() {
if (confirm('...?'))
vals=Number(this.value);
else
$(this).val(vals);
});
but its not clear what is the reason that the inline code $(this).val(sval) resets the select to 1

I've modified your code and this is how i've done it
Working Fiddle :
Javascript :
$( "#svalue" ).change(function() {
if (confirm('...?')) {
vals =$('#svalue').val();
$('#svalue').val(this.options[this.selectedIndex].value);
}else{
$('#svalue').val(vals);
}
});
HTML :
<select id="svalue">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
EDITED :
here's how its done inline : working Fiddle
HTML:
<select name="sval" onchange="if (confirm('...?')) {foo(this.value);sval=(this.value);} else $(this).val(sval);">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
Javascript :
var sval=1;
function foo(v) {
$('#svalue').val(v);
}
apparently you forgot to change the value of sval to whatever the user has previously clicked. the code is sval=(this.value); on the onchange part.

Try
I think else part is not neccessary
Change to
<select name="sval" onchange="
if (confirm('...?')) foo(this.value);">

Your approach is absolutely horrible.
When ever you inline JavaScript events on elements it just looks ugly.
Why are you wanting to set the select value to the value it has as the currently selected value?
Could you just skip this $(this).val(sval = this.value;); and only have this sval = this.value;
I'm just really a huge fan as to keeping the code and values to a bare minimum where variables are not needed and also where code is not needed.
Give this a shot.
<script type="text/javascript">
var sval = 1;
var foo = function () {
if(confirm('...?')) {
$(this).val(sval = this.value);
}
else
{
$(this).val(sval);
}
};
setTimeout(function () {
document.getElementById('sval').onchange = foo;
}, 100);
</script>
<select id="sval">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

I have found the reason the code is not working.
It came out that there are differences between execution in fiddle and browser which made tracking the problem harder.
In the inline code of the onchange event a variable with the same name as name="sval" gets defined and because the name is the same with the integer variable from the global context, the code is not using the proper value to change select's value.

Related

Dropdown in HTML is empty at initialization due to Javascript

I've created in an html webpage a dropdown with four options. It worked well but I realized that when the page was refreshed, the value would reset itself to the first option. Since I wanted the user's choice to be kept in memory, I added a javascript code snippet that I found somewhere.
It works very well, except that at the initialization the default value of the dropdown is an empty field.
I would need the first option to be displayed at initialization.
I guess it's easy but I don't know JavaScript at all. Could you please help?
Here is what the code looks like:
<select name="options" id='dropdown'>
<option value="1">1st Option</option>
<option value="2">2nd Option</option>
<option value="3">3rd Option</option>
<option value="4">4th Option</option>
</select>
<!-- The script below helps to keep in memory the dropdown value after the page has been refreshed -->
<script type="text/javascript">
var selectedItem = sessionStorage.getItem("SelectedItem");
$('#dropdown').val(selectedItem);
$('#dropdown').change(function() {
var dropVal = $(this).val();
sessionStorage.setItem("SelectedItem", dropVal);
});
</script>
I think you should check if SessionStorage Key exists or not.
I have created working example of your code : https://jsfiddle.net/vieckys/Lwv1n8p7/7/
Here is HTML Markup:
<select name="options" id='dropdown'>
<option value="0" selected>--- select here ---</option>
<option value="1">1st Option</option>
<option value="2">2nd Option</option>
<option value="3">3rd Option</option>
<option value="4">4th Option</option>
</select>
and JS Code
let selectedItem = sessionStorage.getItem("SelectedItem");
if (selectedItem) {
$('#dropdown').val(selectedItem);
} else {
$('#dropdown').val(0);
}
$('#dropdown').change(function() {
let dropVal = $(this).val();
sessionStorage.setItem("SelectedItem", dropVal);
});
Let me know if you face any issue with this.
Based on your scenario, you can explicitly trigger the change event after the value is set for the dropdown using trigger('change') on the select dropdown. This will run the change function and will save the initial value in the sessionStorage. So, add this line of code, $('#dropdown').trigger('change') something like:
<script type = "text/javascript" >
var selectedItem = sessionStorage.getItem("SelectedItem");
$('#dropdown').val(selectedItem);
$('#dropdown').change(function() {
var dropVal = $(this).val();
sessionStorage.setItem("SelectedItem", dropVal);
});
$('#dropdown').trigger('change'); // trigger the change explicitly
</script>

Select2 Select Function Shows Previous Value

I'm using Select2 as a searching dropdown, however when I select an item in the list it keeps showing the previous value.
I initialize the Select2 dropdown:
$(document).ready(function() {
$(".ordersSelect").select2();
});
And then set all the options:
<select class="ordersSelect" style="width:75%;">
<option value>Select a priority...</option>
<option value="0">0</option>
<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>
</select>
So let's say I select 1, my console from this code:
// when value is selected
$('.ordersSelect').on('select2:selecting', function(e) {
var prioritySelection = $('.ordersSelect').select2('data')[0].text;
console.log("DATA: " + prioritySelection);
});
Will show "DATA: Select a priority...". If I then select say '3', the console will show "DATA: 1".
It keeps on showing the value from the previous selection. When I change "select2:selecting" to "select2:selected" the console message just never comes up.
What am I doing wrong here..?
First, you should definitely use select2:select.
select2:selecting is triggered before the result is selected..
$('select').on('select2:select', function (evt) {
// Do something
});
Second, you can get the data object/value from the event itself.
Check the evt.params.data property.
Got it using:
$('.ordersSelect').select2().on("change", function(e) {
var obj = $(".ordersSelect").select2("data");
console.log("change val=" + obj[0].id); // 0 or 1 on change
});
If anyone knows of a better way though, I am definitely up to hear it.

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/

jquery not getting value from select statement on change

This is really odd, but I am probably missing something simple. I have a simple select statement where a user can choose a value.
onChange calls a function getDrop2() which currently I am trying to get it to alert me which option is chosen.
my html is:
<select onChange= "getDrop2()" id = "drop1" >
<option value="0">All</option>
<option value="1">Alphabetical</option>
<option value="2">Brewery</option>
<option value="3">Style</option>
</select>
My Javascript is:
function getDrop2(){
var choice = $("#drop1").val()
alert(choice);
}
The output of the alert statement is just blank.
In jQuery, you're better off doing something like:
<select id = "drop1" >
<option value="0">All</option>
<option value="1">Alphabetical</option>
<option value="2">Brewery</option>
<option value="3">Style</option>
</select>
With the following JavaScript:
$(function(){
$('#drop1').change(function() {
var choice = $(this).val();
alert(choice);
}
});
The idea is that jQuery is now attaching the change function automatically to the select with the id of "drop1" By using this pattern, you've decoupled the HTML from the JavaScript that's doing the business logic.
Although what others have selected is a better approach. My answer is just to tell you why your code is not working
Try this
var choice = $('#drop1 option:selected').val()
Instead of
var choice = $("#drop1").val()

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