I have a page that builds drop down menus dynamically from the database as follows:
<select name="set_order[]" class="form-control" data-catid="3">
<option value="1" selected="">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="set_order[]" class="form-control" data-catid="2">
<option value="1">1</option>
<option value="2" selected="">2</option>
<option value="3">3</option>
</select>
<select name="set_order[]" class="form-control" data-catid="1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3" selected="">3</option>
</select>
What I want to do is that when one of them is changed, I want to resort the drop downs according to the change that was made with Javascript and update the selected dropdown in each dropdown so as that each drop down has a unique choice made.
I've been trying to sort them but I haven't been successful.
Thank you in advanced!
Edit, as requested, here is my trial JS to sort them:
$(document).on('change', 'select[name="set_order[]"]', function(){
var newOrder = $(this).val();
var change_id = $(this).attr('data-catid');
console.log(newOrder, ' ', change_id);
var order = new Array();
var cat_id = new Array();
var checker = false;
$('select[name="set_order[]"]').each(function(i){
order[i] = parseInt($(this).val());
cat_id[i] = parseInt($(this).attr('data-catid'));
console.log(order[i], ' ', cat_id[i], ' ', i);
if(checker == false){
if(cat_id[i] == change_id){
checker = true;
}else{
order[i] = order[i] + 1 ;
}
}else{
order[i] = order[i] - 1;
}
//console.log(order[i], ' ', cat_id[i], ' ', i);
});
});
You can do that with jQuery
//Sort alphabetically the contact list in the biography page
function sortList() {
//Replace #list by the id of the div who enclose your select
$("#list").html(
$(".form-control").children("option").sort(function (a, b) {
return $(a).text().toUpperCase().localeCompare(
$(b).text().toUpperCase());
})
);
};
Related
I have 2 picklists with the same values. In the 1st picklist, it has more values than the 2nd picklist. So when the user selects some value from the 2nd picklist, it is showing the same value in the 1st one.
But I would like to show if the value Testing 1 is selected in picklist 1 then the same value should show in the 2nd picklist. If the user selects Testing 2 from the 1st picklist then the 2nd picklist should also show the same value.
Not sure how to achieve this. Could someone help me with this?
var sMap = {};
sMap["ABC"] = ["Test2ABC", "Style"];
sMap["CDE"] = ["Test2CDE", "style"];
sMap["EFG"] = ["Test2EFG", "style"];
function onChangeRadio(ele) {
var id = $(ele).attr("id");
var type = $(ele).attr("type");
var tagName = $(ele).prop("tagName");
if (tagName.toLowerCase() == "select") {
var val = $(ele).val();
$('#codes').append($("<option value='" + val + "'>" + val + "</option>"));
setsc(val);
} else {
var Code = Object.keys(sMap).find(key => sMap[key].includes(id));
setsc(Code);
}
}
function setsc(val) {
$('[name="Code"]').val(val);
window.dispatchEvent(new Event('resize'));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td id="TD1">
<input type="hidden" name="Test1" id="hidden-test1" value="">
<input list="codes" name="Code" id="slist" class="Mandatory">
<datalist id="codes">
<option value="">-- Choose one --</option>
<option value="ABC">Testing 1</option>
<option value="CDE">Testing 2</option>
<option value="EFG">Testing 3</option>
<option value="ABC">worker</option>
<option value="NAP">Port</option>
</datalist>
</td>
<select name="T-Test2" id="Test2" onchange="onChangeRadio(this)">
<option value="" selected="">Choose one</option>
<option value="ABC">Testing 1</option>
<option value="CDE">Testing 2</option>
<option value="EFG">Testing 3</option>
</select>
You need to detect the onchange event on the datalist. You do that by checking the input event on the <input>.
You can use the inputType on the InputEvent to filter out any unwanted onInput events. This is "insertReplacementText" on Firefox 81 and null for Chrome/Edge 86. If you need to support IE11 you will need to validate the value is valid.
$("#slist").on("input", (event) => {
// Detect change on the datalist
if (event.inputType == "insertReplacementText" || event.inputType == null) {
console.log(event.target.value);
})
Other explains areinside the below code.
var sMap = {};
sMap["ABC"] = ["Test2ABC", "Style"];
sMap["CDE"] = ["Test2CDE", "style"];
sMap["EFG"] = ["Test2EFG", "style"];
function onChangeRadio(ele) {
var id = $(ele).attr("id");
var type = $(ele).attr("type");
var tagName = $(ele).prop("tagName");
if (tagName.toLowerCase() == "select") {
var val = $(ele).val();
$('#codes').append($("<option value='" + val + "'>" + val + "</option>"));
setsc(val);
} else {
var Code = Object.keys(sMap).find(key => sMap[key].includes(id));
setsc(Code);
}
}
function setsc(val) {
$('[name="Code"]').val(val);
window.dispatchEvent(new Event('resize'));
}
$("#slist").on("input", (event) => {
// Detect change on the datalist
if (event.inputType == "insertReplacementText" || event.inputType == null) {
let selectedValue = event.target.value;
if (!selectedValue) return;
// Get the text of the option associate with the value
let optionData = $(`#codes > option[value="${selectedValue}"]`).text();
console.log(optionData);
// Append in the <select>
// if the otpion is not existed, use a temporary attribute, so we can clear it out later
let selectedOption = $(`#Test2 > option[value="${selectedValue}"]`)[0];
if (selectedOption) {
// selected option exists, show it
selectedOption.selected = 'selected';
} else {
// selected option doesn't exist, add then show
// Clear the temporary options out of the select
$('#Test2 > [temporary="true"]').remove();
$('#Test2').append($('<option>', {
value: selectedValue,
text: optionData,
selected: true,
temporary: true,
}));
}
}
});
// Whenever you change the value on the select, clear out the temporary options
$('#Test2').on('change', (e) => {
$('#Test2 > [temporary="true"]').remove();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td id="TD1">
<input type="hidden" name="Test1" id="hidden-test1" value="">
<input list="codes" name="Code" id="slist" class="Mandatory">
<datalist id="codes">
<option value="">-- Choose one --</option>
<option value="ABC">Testing 1</option>
<option value="CDE">Testing 2</option>
<option value="EFG">Testing 3</option>
<option value="HIJ">worker</option>
<option value="NAP">Port</option>
</datalist>
</td>
<select name="T-Test2" id="Test2" onchange="onChangeRadio(this)">
<option value="" selected="">Choose one</option>
<option value="ABC">Testing 1</option>
<option value="CDE">Testing 2</option>
<option value="EFG">Testing 3</option>
</select>
I have 2 input selects
Country and Cars
This is the structure: [https://jsfiddle.net/CornerStone20/r1eanhwv/6/][1]
JSFIDDLE: [1]: https://jsfiddle.net/CornerStone20/r1eanhwv/6/
When I select Country, How do I only show the selected country's cars?
I have tried:
$(function() {
$('#Country_Select').on('change', function() {
var val = this.value;
$('#Cars_Select option').hide().filter(function() {
return this.value.indexOf( val + '_' ) === 0;
})
.show();
})
.change();
});
You can use each loop to iterate through options and check if the value of car select- box is same as country select-box depending upon this show() or hide() options .
Demo Code :
$(function() {
$('#Country_Select').on('change', function() {
var val = this.value;
$('#Cars_Select option').each(function() {
//checking value of opton in cars selct is same
if ($(this).val() == val) {
$(this).show(); //show it
} else {
$(this).hide(); //hide other
}
})
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
// Country select
<select id="Country_Select" class="form-control">
<option selected="true" disabled="false">Choose Country</option>
<option value="0001">France</option>
<option value="8ebd9ec1-b121-44e9-a530-42f227359913">Germany</option>
<option value="4dda2683-83c6-48c8-af9b-0a96991b7c8b">New Zealand</option>
</select>
// Cars
<select id="Cars_Select" class="form-control">
<option selected="true" disabled="false">Choose Cars</option>
<option value="0001">Renauld</option>
<option value="0001">Mini</option>
<option value="0001">Paris</option>
<option value="8ebd9ec1-b121-44e9-a530-42f227359913">BMW</option>
<option value="8ebd9ec1-b121-44e9-a530-42f227359913">Audi</option>
<option value="8ebd9ec1-b121-44e9-a530-42f227359913">Mercedes</option>
<option value="8ebd9ec1-b121-44e9-a530-42f227359913">Benz</option>
<option value="4dda2683-83c6-48c8-af9b-0a96991b7c8b">Kiwi Auto</option>
</select>
Even though the question has been answered, I am writing a better approach here:
$('#Country_Select').on('change', function(e) {
let cars = $('#Cars_Select').children();
cars.hide();
let country = $(this).val();
cars.filter('[value=' + country + ']').add(cars.eq(0)).show();
});
I have a webpage using 4 search box's in 2 in header & 2 in the body of homepage.
Both Header form & form in body of homepage are the same and query the same search page.
My Question is how could I link dropdowns so that when one changes the others follow.
At the moment I am using php to switch to appropriate categories on arrival to page(s).
eg:
<option value='-1' <?php if ($cat == "-1") {print("selected");}?>>All Categories</option>
<option value='0'<?php if ($cat == "0") {print("selected");}?>>Category One</option>
<option value='1' <?php if ($cat == "1") {print("selected");}?>>Category Two</option>
Which works great when arriving on page(s) after query.
However Because there are 4 forms on my home page I was hoping to somehow dynamically when user changes one of the < select >< options > on page then the other < select >< options > in header and other places all change to same value also?
Any ideas?
Suppose you have 2 'Select' html elements like below:
test.html
<html>
<head>
<script src="connectSelect.js"></script>
</head>
<body onload="connectSelect('first', 'second')">
<select id="first">
<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>
</select>
<select id="second">
<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>
</select>
</body>
</html>
Just use the already made 'connectSelect' function on body load passing the ids of the 'Select' elements you want to connect.
Include the connectSelect.js file in the header. Below is the code for that:
connectSelect.js
function connectSelect(id1, id2) {
var select1 = document.getElementById(id1);
var select2 = document.getElementById(id2);
var i, val1, text1, val2, text2, errText;
//to check whether both the select elements are of same length or not
if (select1.length != select2.length) {
alert("connectSelect Function Error: Both the 'Select' elements should have same number of options!");
return;
}
//after assuring both the select elements to be of same length
//to check whether both the select elements have same value and text
for (i = 0; i < select1.length; i++) {
val1 = select1.options[i].value;
text1 = select1.options[i].innerHTML;
val2 = select2.options[i].value;
text2 = select2.options[i].innerHTML;
if (val1 != val2 || text1 != text2) {
errText = "Both the 'Select' elements should have same options with same value and text!";
errText += "\n";
errText += "\n";
errText += "First mismatch: Option " + (i+1);
alert("connectSelect Function Error: " + errText);
return;
}
}
//after assuring both the select elements to be same
select1.addEventListener("change", function(){
var index = this.selectedIndex;
select2.options[index].selected = true;
});
select2.addEventListener("change", function(){
var index = this.selectedIndex;
select1.options[index].selected = true;
});
}
I have inserted the code snippet also. Try it.
function connectSelect(id1, id2) {
var select1 = document.getElementById(id1);
var select2 = document.getElementById(id2);
var i, val1, text1, val2, text2, errText;
//to check whether both the select elements are of same length or not
if (select1.length != select2.length) {
alert("connectSelect Function Error: Both the 'Select' elements should have same number of options!");
return;
}
//after assuring both the select elements to be of same length
//to check whether both the select elements have same value and text
for (i = 0; i < select1.length; i++) {
val1 = select1.options[i].value;
text1 = select1.options[i].innerHTML;
val2 = select2.options[i].value;
text2 = select2.options[i].innerHTML;
if (val1 != val2 || text1 != text2) {
errText = "Both the 'Select' elements should have same options with same value and text!";
errText += "\n";
errText += "\n";
errText += "First mismatch: Option " + (i+1);
alert("connectSelect Function Error: " + errText);
return;
}
}
//after assuring both the select elements to be same
select1.addEventListener("change", function(){
var index = this.selectedIndex;
select2.options[index].selected = true;
});
select2.addEventListener("change", function(){
var index = this.selectedIndex;
select1.options[index].selected = true;
});
}
<html>
<head>
<script src="test.js"></script>
</head>
<body onload="connectSelect('first', 'second')">
<select id="first">
<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>
</select>
<select id="second">
<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>
</select>
</body>
</html>
Hope it helped.
EDIT: For a better solution, please check this (Source: From comments of this question)
I'm trying to get the value of the option which have the attribute "selected" to compare it to the current option selected.
function onChangeOption(opt) {
var update_value = opt.value;
var selectedValue = '???'; // get selected attribute
if (update_value != selectedValue) {
// Do some things
}
}
<select class="form-control" onchange="onChangeOption(this)">
<!-- I wanna got the content of option selected=selected-->
<option selected="selected" value="1">1</option>
<option value="2">2</option>
</select>
// save initial selected value to a variable
var initSelected = $('.form-control option:selected').val();
$('select').on('change', function() {
// check if the selected value is the same as the initial one was
if(this.value == initSelected) {
console.log('same values');
} else {
console.log('not same values');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
</select>
Just add change event listener.And get the selected value.You can achieve comparision between selected value and changed value by maintaining an array.Like below.
values = []//creates an array
select = document.querySelector('#myselect');
values.unshift(select.value);
//console.log(values);
select.addEventListener('change',function(){
update_value = this.value;
console.log(this.value);
if (update_value != values[0]) {
// alert('Not matched');
console.log('Not matched');
}
else{
//alert('Matched');
console.log('Matched')
}
});
<select class="form-control" id="myselect">
<option selected="selected" value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
I think alexis actually wants something more like this:
function onChangeOption(opt) {
var update_value = opt.value;
var options = document.getElementsByTagName("option");
if (options[0].getAttribute("selected")=="selected") {
var selectedValue = options[0].value;
} else {
var selectedValue = options[1].value;
}
if (update_value != selectedValue) {
// If the selected option's value is not equal to the value of the option with the attribute "selected", then do... (this way, you can change the attribute to any of the options!)
console.log(selectedValue);
}
}
<select class="form-control" onchange="onChangeOption(this)">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
</select>
Comment the result and if you need anything else. Glad to help.
You can always store previously selected values, if you want to access them somehow later on: working example.
HTML:
<select id="mySelect" class="form-control" onchange="onChangeOption(this)">
<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>
</select>
<p>Previous: <span id="prev"></span></p>
<p>Current: <span id="curr"></span></p>
JS:
var selectElem = document.getElementById("mySelect");
var prev = document.getElementById("prev");
var curr = document.getElementById("curr");
var allEverSelected = [ selectElem.value ];
selectElem.addEventListener("change", function(evt){
allEverSelected.push( this.value );
prev.innerHTML = allEverSelected[allEverSelected.length - 2];
curr.innerHTML = allEverSelected[allEverSelected.length - 1];
});
To access default value, just get the <select> value after DOM loads.
selected attribute on <option> tag exist only to make other than first <option> element inside <select> default option, i.e.:
<select>
<option value="1">1</option>
<option selected value="2">2</option>
</select>
Above select's default value is 2.
I think this is the one what you want. Try it.
function onChangeOption(opt) {
var update_value = opt.value;
console.log(update_value);
var selectedValue;// = '???'; // get selected attribute
// I think this is the one you want
//If you want to select the HTML element,
selectedValue=document.querySelector("option[value='"+update_value+"']");
console.log(selectedValue);
//
if (update_value != selectedValue) {
// Do some things
}
}
//onChangeOption(document.querySelector('form'));
function start(){
while(typeof document.querySelector('form')!=typeof {}){}
onChangeOption(document.querySelector('.form-control'));
}
<body onload="start()">
<select class="form-control" onchange="onChangeOption(this)">
<option selected="selected" value="1">1</option>
<!-- I wanna got this -->
<option value="2">2</option>
</select></body>
I am using the SumoSelect dropdown for multiselect options. But i cannot get the selected values array.
Below the sample code :
<script type="text/javascript">
$(document).ready(function () {
window.testSelAll = $('.testSelAll').SumoSelect({okCancelInMulti:true, selectAll:true });
$('.btnOk').on('click', function(){
var obj = [];
$('option:selected').each(function () {
obj.push($(this).index());
alert("Selected Values=="+$(this).val());
});
for (var i = 0; i < obj.length; i++) {
$('.testSelAll')[0].sumo.unSelectItem(obj[i]);
}
});
});
</script>
<select multiple="multiple" placeholder="Share Your Friends" onchange="console.log($(this).children(':selected').length)" class="testSelAll">
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Mercedes</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
<option value="porsche">Porche</option>
<option value="ferrari">Ferrari</option>
<option value="mitsubishi">Mitsubishi</option>
</select>
If you want the selected values instead of the text, just change .text() to .val().
If you want to get the array, see below with working example at the bottom.
jQuery
$(document).ready(function() {
$('.testSelAll').SumoSelect({
okCancelInMulti: true,
selectAll: true
});
$('.btnOk').on('click', function() {
var obj = [],
items = '';
$('.testSelAll option:selected').each(function(i) {
obj.push($(this).val());
$('.testSelAll')[0].sumo.unSelectItem(i);
});
for (var i = 0; i < obj.length; i++) {
items += ' ' + obj[i]
};
alert(items);
});
});
HTML
<select multiple="multiple" class="testSelAll">
<option value="car1">Volvo</option>
<option value="car2">Saab</option>
<option value="car3">Mercedes</option>
<option value="car4">Audi</option>
</select>
Working JSFIDDLE
You can get them from underlying hidden select element.
using jquery eg.
$('.select1 option:selected')
I think the cleanest way to do this. Is to take advantage of html5 select element underlying SumoSelect.
HTML
<select multiple="multiple" class="testSelAll" id="multi-select">
<option value="car1">Volvo</option>
<option value="car2">Saab</option>
<option value="car3">Mercedes</option>
<option value="car4">Audi</option>
</select>
Javascript
var values = $('#multi-select').val();
This line will return a string list of the values selected.