how to set text of option:selected in jquery - javascript

<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());
});

Related

How do get the result from jQuery change method?

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
});

Html element get specific attribute value

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);
}

Remove a dropdown value that has been selected from another dropdown menu

I have searching the web for a while and still I cant find an answer, I have three drop-down menus on my site.
I use them for accepting user preferences so the user can control the output of results.
So I want to know if its possible for the value to be taken out of the other 2 dropdowns if its selected in one.
for example if the user selects movies in the first one it wont be in the others.
here is my dropdowns
<select id="pref1select">
<option value="P">Preference One</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
<select id="pref2select">
<option value="P">Preference Two</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
<select id="pref3select">
<option value="P">Preference Three</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
This will disable it, but not remove it.
Fiddle: http://jsfiddle.net/p2SFA/1/
HTML: (Added .preferenceSelect class) and jQuery:
$(document).ready(function() {
$(".preferenceSelect").change(function() {
// Get the selected value
var selected = $("option:selected", $(this)).val();
// Get the ID of this element
var thisID = $(this).prop("id");
// Reset so all values are showing:
$(".preferenceSelect option").each(function() {
$(this).prop("disabled", false);
});
$(".preferenceSelect").each(function() {
if ($(this).prop("id") != thisID) {
$("option[value='" + selected + "']", $(this)).prop("disabled", true);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<select id="pref1select" class="preferenceSelect">
<option value="P">Preference One</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
<select id="pref2select" class="preferenceSelect">
<option value="P">Preference Two</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
<select id="pref3select" class="preferenceSelect">
<option value="P">Preference Three</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
If you want it removed, you will probably have to make jQuery know what to insert when it has reset because a new choice is made :)
This should work for you:
$(document).ready(function() {
$(".preferenceSelect").change(function() {
// Get the selected value
var selected = $("option:selected", $(this)).val();
// Get the ID of this element
var thisID = $(this).attr("id");
// Reset so all values are showing:
$(".preferenceSelect option").each(function() {
$(this).show();
});
$(".preferenceSelect").each(function() {
if ($(this).attr("id") != thisID) {
$("option[value='" + selected + "']", $(this)).hide();
}
});
});
});`
You should try this:
$(".preferenceSelect").on("change", function () {
$(".preferenceSelect option").prop("disabled", false);
var selectPref = $("option:selected", $(this)).val();
var selectId = $(this).prop("id");
$(".preferenceSelect option").each(function () {
$(this).show();
});
$(".preferenceSelect").each(function () {
if ($(this).prop("id") != selectId) {
$("option[value='" + selectPref + "']", $(this)).prop("disabled", true);
}
});
});
This must be work for you.
I believe something like this would do the trick given the HTML above:
var $selects = $("select");
$selects.on("change", function(){
var value = this.value;
$("option[value='" + value +"']", $selects).prop("disabled", true);
});
var $selects = $("select");
$selects.on("change", function(){
var value = this.value;
$("option[value='" + value +"']", $selects).prop("disabled", true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="pref1select">
<option value="P">Preference One</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
<select id="pref2select">
<option value="P">Preference Two</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
<select id="pref3select">
<option value="P">Preference Three</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
This disables the duplicate options, but it's an easy change to remove them as well. You'll run into a slight issue, though, since the "Preference #" options all have the same value. I would recommend either making these optgroup labels or removing the values entirely and marking them as disabled from the start...since you shouldn't be able to click them in the first place. You can find a bit more on option labels, and separators answered here.
Example
Please try the following which is working fine with no issue. I am also marking the selected option as disable instead of hiding from the other dropdowns.
$( function() {
courC();
});
function courC(){
var previous;
$(".pSel").on('focus', function () {
previous = this.value;
}).change(function() {
var selected = $("option:selected", $(this)).val();
var thisID = $(this).attr("id");
$(".pSel option").each(function() {
$(this).show();
});
$(".pSel").each(function() {
var otid=$(this).attr("id");
if (otid != thisID) {
if( $('#'+otid).val() == selected){ $('#'+otid).val(''); } // this is required when you are viewing data once again after the form submission
$("option[value='" + selected + "']", $(this)).attr("disabled", true);
}
$("option[value='" + previous + "']", $(this) ).attr("disabled", false); // this will help to reset the previously selected option from all dropdown
});
previous = $('#'+thisID).val();
});
}

How to synchronize two SELECT elements

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>

coding onchange event

hello
i need to load page based on the results of dropdown box. for example in my code i have value="userlog". if this selected it will load userlog.php and remove itself so that only userlog.php is being used. thanks
<select onchange="updatePage(this.value)">
<option value="">Select a report</option>
<option value="userlog">User Logs</option>
<option value="actionlog">Action Logs</option>
</select>
<select id="select_page">
<option value="">Select a report</option>
<option value="userlog">User Logs</option>
<option value="actionlog">Action Logs</option>
</select>
$('#select_page').change(function() {
var $el = $(this);
if($el.val() != '') {
$('#page').load($el.val()+'.php');
$el.find('option:selected').remove();
}
});
On change event you will get the selected options value. Using this value you can decide what you want to do.
something like this :
$(document).ready(function() {
$("select option ").each(function() {
if (location.href.indexOf($(this).val()) >= 0) {
$(this).remove();
}
});
$('select').change(function() {
var obj = $(this);
location.href = obj.val() + ".php";
});
});

Categories