Select2 Select Function Shows Previous Value - javascript

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.

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>

How to get all the selected option from multipal selectbox value using jQuery

I have a long dynamic form which has several Select Option like
<select class="common_dt_select" id="select_15" data-col-index="15">
<option value="">All CC Status</option>
<option value="0">Dead</option>
<option value="1">Active</option>
<option value="2">Frozen</option>
</select>
<select class="common_dt_select" id="select_23" data-col-index="23">
<option value="">All</option>
<option value="0">No</option>
<option value="1">Yes</option>
</select>
I want to get all the selected option value and data-col-index value using jQuery.
I know I have to loop it by a common class so I have given common_dt_select but I cannot able to get the data.
How i want is
some loop that will run
if (sel_val != '') //I only want that value which is not blank
console.log(sel_val);
console.log(data_tag_id);
end of if
end of loop
Codepen
$('.common_dt_select').each(function() {
var value = $(this).val();
var colindex = $(this).data('col-index');
if(value.length) {
console.log(colindex);
console.log(value);
}
});
You can simply use below code
$('.common_dt_select :selected').each(function(i, sel){
alert( $(sel).val());
});

Change selected item from inside onchange event

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.

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.

Javascript: Get array value when I select the option in the drop down list

I hope that someone would be able to help me to solve this simple problem.
My goal is to get the value in the array from selection drop down list.
Basically, I create an Array in Javascript and a selection drop down list in the body.
<script type="text/javascript">
var even = new Array(2, 4, 6);
</script>
.
.
.
<select id="evenNumbers">
<option value="1">two</option>
<option value="2">four</option>
<option value="3">six</option>
</select>
My question is how can I get the value in the Array if I select the option from the drop down list? e.g. when I select "two" from the drop down list, but I can get the value of "2" in the array in order to do some calculation.
your select box will look like this
<select >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
if you want to populate values putting a for loop.
for getting selected option value
this.options[this.selectedIndex].value
http://awesomerails.wordpress.com/2007/12/04/get-the-value-of-a-selected-option-with-javascript/
document.getElementById('evenNumbers').onchange = function() {
var index = this.value - 1; // array indices start at 0
alert(even[index]);
}

Categories

Resources