This shouldn't be so difficult... A little rusty with Javascript and jQuery and I think I'm missing something obvious.
Code sample. Abbreviated DOM
<select data-drupal-selector="edit-country-code-country" id="edit-country-code-country" name="country_code[country]"
class="form-select is-empty">
<option value="" selected="selected">- None -</option>
<option value="AF">Afghanistan</option>
<option value="AL">Albania</option>
<option value="ZW">Zimbabwe</option>
<option value="AX">Åland Islands</option>
</select>
Code from script (doesn't work)
$('select[id^="edit-country-code-country"]').on('change', () => {
const $target = $('#opt-in-wrapper');
const countryNames = drupalSettings.r1;
const $countrySelected = $('#select2-edit-country-code-country-container').attr('title');
const countryCode = this.value;
const test1 = $(this).value;
const this2 = $(this).change;
const this3 = $(this).data();
const elem = $(this);
const test5 = elem.value;
const test6 = elem.value();
What I don't understand is why this.value returns undefined in the script but works as I would expect in the debug console
Debug results screenshot.
As you used arrow function in the scope of checkCountryChange, I think this belong to upper scope inside it so Replace arrow function with regular function to fix the issue.
$('#edit-country-code-country').on('change', function(){
alert(this.value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select data-drupal-selector="edit-country-code-country" id="edit-country-code-country" name="country_code[country]"
class="form-select is-empty">
<option value="" selected="selected">- None -</option>
<option value="AF">Afghanistan</option>
<option value="AL">Albania</option>
<option value="ZW">Zimbabwe</option>
<option value="AX">Åland Islands</option>
</select>
If the element has id, you can just use the id for the query selector. Then, you can find the selected option.
$('#edit-country-code-country').change(function() {
var $option = $(this).find('option:selected');
var code = $option.val(); // to get selected country code
var name = $option.text(); // to get selected country name
});
Related
I would like to get the "data-price" attribute from the option element onChange. getting the value does work, but i can not get the data-price attribute. I have the following code, which doesnt work.
function getComboA(selectObject) {
var printit = selectObject.getAttribute("data-price");
console.log(printit);
}
/*with this it gets the value tho, but i need the data-price attribute
function getComboA(selectObject) {
var printit = selectObject.value;
console.log(printit);
}
*/
<select id="comboA" onchange="getComboA(this)">
<option value="">Select combo</option>
<option data-price=100 value="Value1">Text1</option>
<option data-price=200 value="Value2">Text2</option>
<option data-price=2003 value="Value3">Text3</option>
</select>
By JavaScript :
var selection = document.getElementById("comboA");
selection.onchange = function(event){
var printit = event.target.options[event.target.selectedIndex].dataset.price;
console.log(printit);
};
Or JQuery :
$('#comboA').change(function(){
var printit =$(this).find(':selected').attr('data-price')
console.log(printit);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="comboA" >
<option value="">Select combo</option>
<option data-price=100 value="Value1">Text1</option>
<option data-price=200 value="Value2">Text2</option>
<option data-price=2003 value="Value3">Text3</option>
</select>
This should make it work:
const comboA = document.querySelector('#comboA');
comboA.addEventListener('change', function(event) {
console.log(event.target.options[event.target.selectedIndex].dataset.price);
});
With this you can also omit the function call in html.
You can use the selectedIndex of the selectObject to get the index which you can use to get the selected option and then you can get the data-price attribute of that option.
Code:
function getComboA(selectObject) {
var selectedIndex = selectObject.selectedIndex;
var selectedPrice = selectObject[selectedIndex].getAttribute("data-price");
console.log(selectedPrice);
}
I require a bit of jQuery to do the following:
A user can currently select Program and/or a region.
If a user selects Program AND a Region I require the option values of the region dropdown to change to "?region=1" and "?region=2"
<select class="program" id="program">
<option value="program1.html">Program 1</option>
<option value="program2.html">Program 2</option>
</select>
<select class="region" id="region">
<option value="region1.html">Region 1</option>
<option value="region2.html">Region2</option>
</select>
Greatly appreciate the assist.
My attempt at JQuery:
$('#program').on('change', function () { if($(this).val() !="0") { } else { // no option is selected } })
You need to further extend the change event for #program and include a similar one for #region.
var programSelected = null;
var regionSelected = null;
$('#program').on('change', function(element) {
programSelected = $('#program option:selected').text();
updateRegionOptions();
});
$('#region').on('change', function(element) {
regionSelected = $('#region option:selected').text();
updateRegionOptions();
});
function updateRegionOptions() {
if(programSelected != null && regionSelected != null) {
$('#region option').each(function() {
var modifiedString = '?';
modifiedString += $(this).val().replace(/\d+/,'');
modifiedString = modifiedString.replace('.html','');
modifiedString += '=';
modifiedString += $(this).val().match(/\d+/);
$(this).val(modifiedString);
});
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="program" id="program">
<option value="" selected disabled>Select Program</option>
<option value="program1.html">Program 1</option>
<option value="program2.html">Program 2</option>
</select>
<select class="region" id="region">
<option value="" selected disabled>Select Region</option>
<option value="region1.html">Region 1</option>
<option value="region2.html">Region2</option>
</select>
Explanation of the logic above:
on('change' event for both #region and #program
Set the relevant variable programSelected or regionSelected depending on the change event
Run function updateRegionOptions();
If the variables programSelected and regionSelected both have a value
For each of the options in #region
Mutate the existing value to be of the form "?region=1" and "?region=2"
Update the value section of each of the option elements to have this value
The relevant JSFiddle for review.
If this solved your issue, please accept this answer :)
I would like to put multiple values in tag within select, so I could adress precisely one or few items.
Example:
<select id="select1">
<option value="pf, nn">NN</option>
<option value="pf, x2, jj">JJ</option>
<option value="pf, uu">UU</option>
<option value="pf, x2, oo">OO</option>
<option value="tt">TT</option>
<option value="rr">RR</option>
</select>
In my js I got that one function that depend on one value that is common for many items:
if (document.getElementById("select1").value = "pf";) {
// do something;
}
if (document.getElementById("select1").value = "x2";) {
// do some-other-thing;
}
But I don't want to use (cos' and with more options gonna get messy)
var sel1 = document.getElementById("select1").value
if (sel1="nn" || sel1="jj" || sel1="uu" || sel1="oo") {
// do something;
}
if (sel1="jj" || sel1="oo") {
// do some-other-thing;
}
Neverthelesst I need to be able to set item by precise one value
if (document.somethingelse = true) {
document.getElementById("select1").value = "oo";)
}
Is there a nice way to achieve this? Maybe use some other "value-like" attribute of option (but which?)?
Only JS.
I think you can do what you want with selectedOpt.value.split(",").includes("sth") code:
$(document).ready(function(e){
selectedChange($("#select1")[0])
});
function selectedChange(val) {
var selectedOpt = val.options[val.selectedIndex];
var status1 = selectedOpt.value.split(",").includes("x2");
var status2 = selectedOpt.value.split(",").includes("pf");
console.log(status1);
console.log(status2);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select1" onchange="selectedChange(this)">
<option value="pf,nn">NN</option>
<option value="pf,x2,jj">JJ</option>
<option value="pf,uu">UU</option>
<option value="pf,x2,oo">OO</option>
<option value="tt">TT</option>
<option value="rr">RR</option>
</select>
<select id="myselect">
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Dr</option>
<option value="5">Prof</option>
</select>
<select id="youSelect">
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Dr</option>
<option value="5">Prof</option>
</select>
Now on click of a button I want to set mySelect option:selected value in youSelect So for this I had done this
$('#youSelect option:selected').text($('#myselect option:selected').text())
but its not working.Please guide how to solve this.
Simply do:
$('#youSelect').val($('#myselect').val());
You are matching the values, not the text.
Edit: Based on your edited question, you're probably looking at the same situation as this question
var _mySelectText = $("#myselect option:selected").text();
$("#youSelect option").filter(function () {
return this.text === _mySelectText;
}).attr("selected", "selected");
$("#youSelect").val("thevalue");
just make sure the value in the options tags matches the value in the val method.
var myValue = $("#myselect option:selected").text();
var secondoption = $("#youSelect")[0];
for (var i = 0, sL = secondoption.length; i < sL; i++) {
if (secondoption.options[i].text == myValue) {
secondoption.selectedIndex = i;
break;
}
}
http://plnkr.co/edit/GVt8rZswjzZTC13vw98N?p=preview
Use this.
$(selector_to_your_button).on('click',function(){
$('#youSelect).val($("#myselect").val());
});
I was wondering how to synchronize the values and text of two elements. For instance,
<select id="box1" onchange="sync();">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="box2">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
and then sync(); would look something like....
function sync()
{
box2.selected = box1.selected;
}
Any idea how I would do this?
Thanks,
Matthew
One possible approach:
function sync(el1, el2) {
// if there is no el1 argument we quit here:
if (!el1) {
return false;
}
else {
// caching the value of el1:
var val = el1.value;
// caching a reference to the element with
// with which we should be synchronising values:
var syncWith = document.getElementById(el2);
// caching the <option> elements of that <select>:
var options = syncWith.getElementsByTagName('option');
// iterating over those <option> elements:
for (var i = 0, len = options.length; i < len; i++) {
// if the value of the current <option> is equal
// to the value of the changed <select> element's
// selected value:
if (options[i].value == val) {
// we set the current <option> as
// as selected:
options[i].selected = true;
}
}
}
}
// caching the <select> element whose change event should
// be reacted-to:
var selectToSync = document.getElementById('box1');
// binding the onchange event using an anonymous function:
selectToSync.onchange = function(){
// calling the function:
sync(this,'box2');
};
function sync(el1, el2) {
if (!el1) {
return false;
} else {
var val = el1.value;
var syncWith = document.getElementById(el2);
var options = syncWith.getElementsByTagName('option');
for (var i = 0, len = options.length; i < len; i++) {
if (options[i].value == val) {
options[i].selected = true;
}
}
}
}
var selectToSync = document.getElementById('box1');
selectToSync.onchange = function() {
sync(this, 'box2');
};
<select id="box1">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="box2">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
JS Fiddle demo.
Or, revised and updated somewhat:
function sync() {
// caching the changed element:
let el = this;
// retrieving the id of the element we should synchronise with
// from the changed-element's data-syncwith custom attribute,
// using document.getElementById() to retrieve that that element.
document.getElementById( el.dataset.syncwith )
// retrieving the <options of that element
// and finding the <option> at the same index
// as changed-element's selectedIndex (the index
// of the selected <option> amongst the options
// collection) and setting that <option> element's
// selected property to true:
.options[ el.selectedIndex ].selected = true;
}
// retrieving the element whose changes should be
// synchronised with another element:
var selectToSync = document.getElementById('box1');
// binding the snyc() function as the change event-handler:
selectToSync.addEventListener('change', sync);
function sync() {
let el = this;
document.getElementById(el.dataset.syncwith).options[el.selectedIndex].selected = true;
}
var selectToSync = document.getElementById('box1');
selectToSync.addEventListener('change', sync);
<select id="box1" data-syncwith="box2">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="box2">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
JS Fiddle demo.
Note that this approach does assume – and requires – that the <option> elements are in the same order.
To update the original approach, where the order is irrelevant, using ES6 approaches (and the same data-syncwith custom attribute approach):
function sync() {
// caching the changed element (since
// we're using it twice):
let el = this;
// retrieving the id of the element to synchronise 'to' from
// the 'data-syncwith' custom attribute of the changed element,
// and retrieving its <option> elements. Converting that
// Array-like collection into an Array using Array.from():
Array.from(document.getElementById(el.dataset.syncwith).options)
// Iterating over the array of options using
// Array.prototype.forEach(), and using an Arrow function to
// pass the current <otpion> (as 'opt') setting that current
// <option> element's selected property according to Boolean
// returned by assessing whether the current option's value
// is (exactly) equal to the value of the changed element:
.forEach(opt => opt.selected = opt.value === el.value);
}
var selectToSync = document.getElementById('box1');
selectToSync.addEventListener('change', sync);
function sync() {
let el = this;
Array.from(document.getElementById(el.dataset.syncwith).options).forEach(opt => opt.selected = opt.value === el.value);
}
let selectToSync = document.getElementById('box1');
selectToSync.addEventListener('change', sync);
<select id="box1" data-syncwith="box2">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="box2">
<option value="1">One</option>
<option value="3">Three</option>
<option value="2">Two</option>
</select>
JS Fiddle demo.
If you look at the HTML in the Snippet you'll see that I switched the positions of <option> elements in the second <select> element to demonstrate that the <option> position doesn't matter in this latter approach.
References:
Array.from().
Array.prototype.forEach().
Arrow functions.
document.getElementById().
EventTarget.addEventListener().
for loop.
HTMLElement.dataset.
HTMLSelectElement.
let statement.
var.
In the Actual browsers you dont have to do to much...
<select id="box1" onchange="box2.value=this.value;">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="box2">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Jsfiddle DEMO
Without jQuery:
for (var i=0; i<document.getElementById('box1').options.length; i++)
if (document.getElementById('box1').options[i].selected)
for (var j=0; j<document.getElementById('box2').options.length; j++)
if (document.getElementById('box1').options[i].value == document.getElementById('box2').options[j].value)
document.getElementById('box2').options[j].selected = true;
With jQuery:
Note: on method requires jQuery > 1.7
jQuery(function($) {
$('#first').on('change', function() {
var sel = $('option:selected', this).val();
$('#second option').filter(function(index, el) {
return el.value == sel;
}).prop('selected', true);
});
});
<select name="first" id="first" autocomplete="off">
<option value="0">-- Select one option --</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
<option value="5">Fifth</option>
<option value="6">Sixth</option>
</select>
<select name="second" id="second" autocomplete="off">
<option value="0">-- Select one option --</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
<option value="5">Fifth</option>
<option value="6">Sixth</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>