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>
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'm trying to show/hide the cart button depending on 2 separate select field values.
My logic is this:
Display the cart button if selectId #pa_custom-engraving = 'no' OR if selectId #pa-color != 'custom-print'. Otherwise I want to hide the cart.
This is what I have so far which works unless you continue to toggle the select fields they cancel each other out. How can I combine this into proper 'OR' conditional statement?
JS
document.getElementById('pa_custom-engraving').addEventListener('change', function () {
var style = this.value == 'no' ? 'block' : 'none';
document.getElementsByClassName('woocommerce-variation-add-to-cart')[0].style.display = style;
});
document.getElementById('pa_color').addEventListener('change', function () {
var pstyle = this.value !== 'custom-print' ? 'block' : 'none';
document.getElementsByClassName('woocommerce-variation-add-to-cart')[0].style.display = pstyle;
});
HTML
<select id="pa_custom-engraving">
<option value="">Choose an option</option>
<option value="no">No</option>
<option value="yes">Yes</option>
</select>
<select id="pa_color">
<option value="">Choose an option</option>
<option value="black">Black</option>
<option value="white">White</option>
<option value="custom-print">Custom Print</option>
</select>
Add the same listener to both selects. On change, look at both select values, and apply the conditions separated by ||:
const cartButton = document.querySelector('.woocommerce-variation-add-to-cart');
const selects = ['#pa_custom-engraving', '#pa_color'].map(c => document.querySelector(c));
for (const select of selects) {
select.addEventListener('change', () => {
const displayStyle= selects[0].value === 'no' || selects[1].value !== 'custom-print'
? 'block'
: 'none';
cartButton.style.display = displayStyle;
});
}
You can take the all selected value in an array and check if the array includes/not include the value you want to match:
var sel = Array.from(document.querySelectorAll('#pa_custom-engraving, #pa_color'));
sel.forEach(function(el){
el.addEventListener('change', function () {
var val = sel.map(i => i.value);
var style = val.includes('no') || !val.includes('custom-print') ? 'block' : 'none';
document.getElementsByClassName('woocommerce-variation-add-to-cart')[0].style.display = style;
});
});
<select id="pa_custom-engraving">
<option value="">Choose an option</option>
<option value="no">No</option>
<option value="yes">Yes</option>
</select>
<select id="pa_color">
<option value="">Choose an option</option>
<option value="black">Black</option>
<option value="white">White</option>
<option value="custom-print">Custom Print</option>
</select>
<button class="woocommerce-variation-add-to-cart">woocommerce-variation-add-to-cart</button>
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.
I have a form which has got 45 dropdownlist and I m using the bottom code for its
validation.
how can I use only one function of bottom code to do validation for all of my 45 dropdownlist ??
Here is the Function
function Validate()
{
var e = document.getElementById("dropdownlistone");
var strUser = e.options[e.selectedIndex].value;
var strUser1 = e.options[e.selectedIndex].text;
if(strUser==0)
{
alert("Please select a user");
}
}
----- HTML CODE
<select id="dropdownlistone">
<option value="0">Select</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
<input type="button" onClick="Validate()" value="select"/>
This is a case when you need to use classes. Then use querySelectorAll method:
function Validate() {
var e = document.querySelectorAll(".dropdownlistone");
for (var i = 0; i < e.length; i++) {
var strUser = e[i].options[e[i].selectedIndex].value;
var strUser1 = e[i].options[e[i].selectedIndex].text;
if (strUser == 0) {
alert("Please select a user");
return;
}
}
}
Demo: http://jsfiddle.net/cwNaH/
And here is one more example with more user friendly validation messages: http://jsfiddle.net/cwNaH/1/
You can use DOM Method getElementsByTagName for select box and set an data-attr to "validate" for those whom you want to validate, if you dont want it to be validate simply don't add the above mentioned attribute.
Ex. HTML
<select id="sel1" data-attr="validate">
<option value="0">Select</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
<select id="sel2" data-attr="validate">
<option value="0">Select</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
JavaScript
function validate()
{
var ele = document.getElementsByTagName("select");
for(var i=0;i<ele.length;i++)
{
if(ele.getAttribute("data-attr") && ele.getAttribute("data-attr")=='validate')
{
// you have all 47 select boxes whoose data-attr is validate
// each select box will be in ele[i]
var value= ele[i].options[ele[i].selectedIndex].value;
var text= ele[i].options[ele[i].selectedIndex].text;
alert( value+ " : " + text);
}
}
}