Select value using jQuery in same order with select2 - javascript

I have a select2 multiselect dropdown.
<select class="select2" multiselect>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="E">E</option>
</select>
I want to select multiselect on page ready so I tried below code to achieve. But every time I got result in sorted form. But I want selected items in same order.
$('.select2').select2();
$(document).ready(function(){
$('.select2').val(['B','E','A']).trigger('change');
$("select").on("select2:select", function (evt) {
var element = evt.params.data.element;
var $element = $(element);
$element.detach();
$(this).append($element);
$(this).trigger("change");
});
})
Note: when I select manually, it's working fine. But on trigger, it's not working

Related

Display previously selected options in select

Say I've got a HTML setup with some JS behind.
<select id="my-select" onchange="changeFunc()">
<option>A</option>
<option>B</option>
</select>
But I'm trying to make it so that the select HTML keeps track of which options have been clicked and displays those in the select's display rather than just the most recently clicked item. Some pseudo code might look like.
let selectedValues = [];
changeFunc() {
selectedValues.push(mySelect.value);
mySelect.DISPLAY = selectedValues.join(', ');
}
Is there any way to achieve this effect for a select element?
You can do this two ways either store the all previously select value in an array and display them in div as record OR create new option in the same select using and append them in an optgrp.
Solution: If you want display the previously selected option in the same select
Live Demo
let recSel = document.querySelector('#record_select')
function changeFunc(e) {
let opt = document.createElement('OPTION');
opt.textContent = e.options[e.selectedIndex].textContent
opt.value = e.options[e.selectedIndex].value
recSel.appendChild(opt);
}
<select id="my-select" onchange="changeFunc(this)">
<optgroup label="Current Select">
<option selected disabled>Choose</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="E">E</option>
<option value="F">F</option>
<option value="G">G</option>
</optgroup>
<optgroup label="Previous Selected" id="record_select">
</optgroup>
</select>
Solution: If you want display the previously selected records in a div with join(',')
Live Demo:
let selectedValues = [];
let recSel = document.querySelector('#record_select') //get el
//Store value
function changeFunc(e) {
selectedValues.push(e); //store selected value
recSel.textContent = selectedValues.join(', '); //display record of selected values
}
<select id="my-select" onchange="changeFunc(this.value)">
<option selected disabled>Choose</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="E">E</option>
<option value="F">F</option>
<option value="G">G</option>
</select>
<div id="record_select"></div>

How to use getElementByID in JavaScript to connect to my HTML drop down box?

I have a drop-down box in HTML showing three options. I am also using javaScript and want to use the getElementById tool to connect the two. However, I only have one ID for the drop-down box. How does javascript recognize that I have three different options?
There's actually a demo on w3schools.com showing exactly what you're asking. To get the number of options, you could do something like
document.getElementById("mySelect").options.length
Here is an example of how to retrieve the value of a dropdown: https://jsfiddle.net/ykcwgnm8/
You use getElementBy* functions to get the element, however value attribute denotes which item is currently selected.
HTML:
<select id="dropdown">
<option value="1">First option</option>
<option value="2">Second option</option>
<option value="3">Third option</option>
</select>
JS:
function onChangeHandler(e)
{
alert("you have selected item with value "+this.value);
}
document.getElementById("dropdown").addEventListener("change", onChangeHandler);
You can listen for change like this
var list = document.getElementById("mySelect")
list.addEventListener('change', function(e){
console.log(e.target.selectedIndex)
console.log(e.target.options[e.target.selectedIndex].text)
})
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
You can do something like this, here is an example:-
html
<select id="selectBox">
<option value="1">option 1</option>
<option value="2" selected="selected">option 2</option>
<option value="3">option 3</option>
</select>
js
var e = document.getElementById("selectBox");
var selectedValue = e.options[e.selectedIndex].value;
// this will give selectedValue as 2
Hope you find this useful!!

Bind event on select option

I have the following HTML
<select>
<option value="">filter</option>
<option data-behavior="toggle-visibility" data-scope="a" value="a">a</option>
<option data-behavior="toggle-visibility" data-scope="b" value="b">b</option>
</select>
and I need to fire up a Javascript callback when any of the options is selected.
I have the following piece of Javascript:
$(function() {
$(document).on("EVENT", "[data-behavior~=toggle-visibility]", function() {
...
});
});
Is there an event I can use to achieve my goal?
PS - I understand I could move data-behavior="toggle-visibility" to the select tag and then listen for change and get the currently selected value. However, since that piece of Javascript is already used with other elements, I need to keep the data-behavior attribute on the options.
It should work here https://jsfiddle.net/xpvt214o/535895/
You should be using on change event instead:
The example is as follows:
$("select").on("change", function(e) {
var sel = $(this).find(":selected");
var attr = sel.attr("data-behavior");
console.log(attr + "....." + $(this).val())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="">filter</option>
<option data-behavior="toggle-visibility" data-scope="a" value="a">a</option>
<option data-behavior="toggle-visibility" data-scope="b" value="b">b</option>
</select>
Html Code:
<select id="maker-list">
<option value="">filter</option>
<option data-behavior="toggle-visibility" data-scope="a" value="a">a</option>
<option data-behavior="toggle-visibility" data-scope="b" value="b">b</option>
</select>
JavaScript code:
$('#maker-list').off('change').on('change', e => {
selectedValue = $('#maker-list').val();
// Here you can call another function with selectedValue
});
In above JavaScript Code, we bind change even and unbind the same event after selecting value so that it will not fire twice. jquery help
I hope this will work ... happy coding :)
$("select").on("change", (e) => {
console.log(e.target.value)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="">filter</option>
<option data-behavior="toggle-visibility" data-scope="a" value="a">a</option>
<option data-behavior="toggle-visibility" data-scope="b" value="b">b</option>
</select>

Change value of select list with value of another select list jquery

How can I change the value of a select list with the value of another select list
<select class="main-filter" id="Test1" name="Test1"><option value="">Select Option</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
Need to replace #ReplaceThisText# with value selected from above select box
<select id="selectfilter" name="selectfilter" class="form-control main-filter">
<option value="">Sort Products</option>
<option value="/?id=na&selectfilter=hl&Type=#ReplaceThisText#">Chnage Value</option>
</select>
I have tried code from this link Change the Text of a Option with jQuery
and jquery how to find and replace a selected option that has a certain value
but cannot seem to get it to work
My code is
$('#Test1').change(function () {
sessionStorage.setItem("Test1", $(this).val());
$('.main-filter :selected:contains("#ReplaceThisText#")').val($(this).val());
location.href = $(this).val();
});
:contains will look at the .text() value - but your #ReplaceThisText# is not in the .text() value - so you'll need to use .filter() to find it instead:
Adding some console.logs so you can see what's happening and updated the .val(newval) code to make the replacement.
$('#Test1').change(function() {
var newval = $(this).val();
console.log("before", $(".main-filter :contains('Change Value')").val())
var opt = $('.main-filter option').filter(function() {
return $(this).val().indexOf("#ReplaceThisText#") >= 0;
});
console.log("opt length", opt.length);
opt.each(function() {
$(this).val($(this).val().replace(/#ReplaceThisText#/gi, newval));
});
console.log("after", $(".main-filter :contains('Change Value')").val())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="main-filter" id="Test1" name="Test1">
<option value="">Select Option</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
<select id="selectfilter" name="selectfilter" class="form-control main-filter">
<option value="">Sort Products</option>
<option value="/?id=na&selectfilter=hl&Type=#ReplaceThisText#">Change Value</option>
</select>

Get pre-selected value of an HTML select element

Or through example, how can one retrieve "c" via JavaScript or jQuery no matter if the user changed it?
<select id="select-menu">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>
</select>
I tried the following, however, it returns the value of the currently selected menu. I suppose I can take a similar approach which runs upon page load and save the value, but expect there is a more "proper" way to do so.
$('#select-menu > option').each(function(i){
if(this.selected) {
console.log(this.value)
$("#submit").val(this.value);
return false;
}
})
Use jQuery .attr() to get initial value:
function get_initial(){
$('#select-menu > option').each(function(i){
if($(this).attr('selected')) {
console.log('initial: ' + this.value)
}
if(this.selected) {
console.log('current: ' + this.value)
}
})
}
$('.initial').on('click', get_initial);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select-menu">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>
</select>
<button class="initial">check initial</button>
There is no better way. A select is meant to be user-modifiable.
If you want to retain the original value you could save it on load:
$(document).ready(function() {
var initialValue = $("#select-menu").val();
});
You could also write it in a hidden input:
<input type="hidden" name="initial-select-menu" value="c">
This way has the benefit that the value will be submitted along with the rest of the form. Might be preferable in some cases.
Or you could stuff that initial value in a data attribute:
<select id="select-menu" data-initial="c">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>
</select>
You could save the value on an html5 data-* attribute:
<select id="select-menu" data-default="c">
And get it with
$("#select-menu").attr("data-default");
The following code exhibits various examples related to getting of values from select fields using JavaScript.
Working Snippet
const selectMenu = document.getElementById("select-menu");
var selectedIndex = selectMenu.options[selectMenu.selectedIndex].value;
/*Option 1*/
selectMenu.onchange = function() {
selectedIndex = selectMenu.options[selectMenu.selectedIndex].value;
}
/*Option 2*/
/*selectMenu.addEventListener("change", function(){
selectedIndex = selectMenu.options[selectMenu.selectedIndex].value;
})*/
/*Option 3*/
/*function updateSelectedIndex() {
selectedIndex = selectMenu.options[selectMenu.selectedIndex].value;
}*/
document.writeln(selectedIndex);
<!-- Option 3 -->
<!-- <select id="select-menu" onchange="updateSelectedIndex"> -->
<select id="select-menu">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>
</select>
Try this for the appropriate cases:
let preselectedOption = $(targetDropDown).find('option[selected]');
let currentOption = $(targetDropDown).find('option:selected');

Categories

Resources