How do you select a value from a dropdown list, by using the text, instead of the value or the index?
The HTML:
<select name="category_group" id="category_group" sel_id="" >
<option value="0" selected="selected">Kies de rubriek</option>
<option value='1000' style='background-color:#dcdcc3;font-weight:bold;' disabled="disabled" id='cat1000' >
-- VOERTUIGEN --
</option>
<option value='1020' id='cat1020' >
Auto's
</option>
<option value='1080' id='cat1080' >
Auto's: Onderdelen
</option>
<option value='1040' id='cat1040' >
Motoren
</option>
<option value='1140' id='cat1140' >
Motoren: Onderdelen
</option>
</select>
the script:
this.fillSelectors('form[name="formular"]', {
'select[name="category_group"]': 'Motoren'
}, false);
This does not work, but it works using the value of "Motoren" (which is 1140).
How can I make it work, using fillSelectors, with the text?
CasperJS' fill functions only work by using the value. In your case this doesn't work because you're trying to set the shown value not the assigned option value. Though, this can be easily extended:
casper.selectOptionByText = function(selector, textToMatch){
this.evaluate(function(selector, textToMatch){
var select = document.querySelector(selector),
found = false;
Array.prototype.forEach.call(select.children, function(opt, i){
if (!found && opt.innerHTML.indexOf(textToMatch) !== -1) {
select.selectedIndex = i;
found = true;
}
});
}, selector, textToMatch);
};
casper.start(url, function() {
this.selectOptionByText('form[name="formular"] select[name="category_group"]', "Motoren");
}).run();
See this code for a fully working example on the SO contact page.
Related
Hello is there any way to disable multiple options in a select form if you only choose one option?
For example:
First Select Form
<select name="secondchoice" id="second">
<option value="None">None</option>
<option value="Content Dev">Content Dev</option>
<option value="Web">Web</option>
<option value="Science">Science</option>
<option value="Managing">Managing</option>
</select>
Second Select Form
<select name="day2" id="exam2">
<option value="None">None</option>
<option value="Monday">Monday</option>
<option value="Tuesday">Tuesday</option>
<option value="Wednesday">Wednesday</option>
<option value="Thursday">Thursday</option>
</select>
If I select "None" in the first form then the second form must disable the options "Monday-Thursday" the only option available must be also "None" in the second form. Thank you!
You can do this with javascript by hiding options in the second elements whenever the first select element changes by checking its value and hiding elements accordingly like so:
// Select Elements
const first = document.getElementById('first')
const second = document.getElementById('second')
// Option Elements
const one = document.getElementById('one')
const two = document.getElementById('two')
// Runs whenever first select has changed
first.onchange = () => {
// Checks First Selects Value
if (first.value === '1') {
// If '1' then hide TWO and show ONE
second.value = 'ONE'
one.hidden = false
two.hidden = true
} else if (first.value === '2') {
// Else, if '2' then hide ONE and show TWO
second.value = 'TWO'
one.hidden = true
two.hidden = false
}
}
<select id='first'>
<option>1</option>
<option>2</option>
</select>
<select id='second'>
<option id='one'>ONE</option>
<option id='two'>TWO</option>
</select>
This is a very basic example and can be improved alot.
you can do something like below, so when you do selecting none, other options would be disabled, and other than none it would be enabled again
function disabledEnabled(event) {
var optiosLists = document.getElementById("exam2").options;
for (let i = 0; i < optiosLists.length; i++) {
if(event.target.value === "None"){
optiosLists[i].disabled = true;
optiosLists[0].disabled = false;
} else {
optiosLists[i].disabled = false;
}
}
}
You can either disabled select element itself and each of its options. You can find 2 ways to achieve each of those below.
Disabling Select Element
Disabling Option Element
I have a form that conditionally disables select field options based on the value from a previous select field. In my example, salt is offered for sale at different weights, with weights determined by the type of salt.
My form select looks like this:
<select id="salt_type" class="form-control" name="salt_type">
<option value="null" selected disabled>Select a salt type</option>
<option value="block-salt">Block Salt</option>
<option value="tablet-salt">Tablet Salt</option>
<option value="granular-salt">Granular Salt</option>
</select>
<select id="pack_weight" class="form-control" name="pack_weight">
<option value="null" selected disabled>Select a weight</option>
<option class="hide-if-tablet-salt hide-if-granular-salt" value="8kg">8kg</option>
<option class="hide-if-block-salt" value="10kg">10kg</option>
<option class="hide-if-block-salt hide-if-granular-salt" value="25kg">25kg</option>
</select>
My JS:
$('#salt_type').bind('change', function() {
var bool = ($(this).find(':selected').val() === 'block-salt') ? true : false;
$('.hide-if-block-salt').prop('disabled', bool);
var bool2 = ($(this).find(':selected').val() === 'granular-salt') ? true : false;
$('.hide-if-granular-salt').prop('disabled', bool2);
var bool3 = ($(this).find(':selected').val() === 'tablet-salt') ? true : false;
$('.hide-if-tablet-salt').prop('disabled', bool3);
});
It works if there's only one limiting class, but if there are two, the option isn't always disabled. It doesn't even seem to be consistent in failing to disable the first, or the last class.
I tried using classList.contains:
$('#fw_salt_type').bind('change', function() {
var bool = ($(this).find(':selected').val() === 'block-salt') ? true : false;
$('.pack-weight-option').classList.contains('hide-if-block-salt').prop('disabled', bool);
});
But I get a 'classlist not defined' error. Any help appreciated.
Suggest to use non-negative class name for less confused
<option class="show-if-block-salt" value="8kg">8kg</option>
<option class="show-if-tablet-salt show-if-granular-salt" value="10kg">10kg</option>
<option class="show-if-tablet-salt" value="25kg">25kg</option>
Then on salt option change, enable only weight options with show class.
$('#salt_type').bind('change', function() {
var value = $(this).find(':selected').val();
$('#pack_weight option').each(function() {
$(this).prop('disabled', !$(this).hasClass(`show-if-${ value }`));
});
});
https://codesandbox.io/s/cranky-easley-vpcvh
I would like to iterate through the selected values from a multiple select box and check them against a string, returning false as soon as a match is not found. First I tried:
var exampleString = "example";
var mySelections = $("#mySelect option:selected");
for (selection in mySelections) {
if (exampleString.indexOf(mySelections[selection].text()) === -1) {
return false;
};
};
This code gives me an error, however: "text is not a function". I am given to understand that this is because using the index gets the option object itself, not wrapped in jQuery, and it is jQuery that provides the text() method.
I tried an alternative version using the each function:
var result = $("#mySelect option:selected").each(function () {
if (exampleString.indexOf($( this ).text()) === -1) {
return false;
}
});
However, I do not understand the result I'm getting. I naively assumed that my variable result would be set to false or true, but it seems to just return the objects being iterated over. Is there any way to access the results of those string comparisons short of creating a global variable that gets set to true or false inside the function?
Edited to add: upon request, here's the relevant html:
<select multiple="" class="filterSelect" id="mySelect" style="display: none;">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
This is what I would do (I'm not a jQuery user any more):
let testStr = "dd";
document.getElementById('sel').addEventListener('change', (e) => {
const values = []
for (let i=0; i<e.target.selectedOptions.length; i++) {
values.push(e.target.selectedOptions[i].value);
}
console.log(!values.includes(testStr));
return !values.includes(testStr);
})
<select id="sel" multiple>
<option value="aa">aa</option>
<option value="bb">bb</option>
<option value="cc">cc</option>
<option value="dd">dd</option>
<option value="ee">ee</option>
</select>
I'am trying to select the empty (first) value of a dropdown select option if it does not contains the value from an another dropdown select list:
$('#FirstDropdown').change(function() {
if ( $('#SecondDropdown option').filter(':contains(' + this.value + ')') ){
$('#SecondDropdown option').filter(':contains(' + this.value + ')').prop('selected',true);
}else{
$("#SecondDropdown option[value='']").prop('selected',true);
}
});
This code work well if #SecondDropdown option contains this.value but the else statement doesn't reset the dropdown list if not.
Any suggestion please ?
EDIT : The dropdown lists look like this :
<select id="FirstDropdown">
<option value="" selected="selected"> </option>
<option value="VAL1">First Value</option>
<option value="VAL2">Second Value</option>
<option value="VAL3">Third Value</option>
<option value="VAL4">Fourth Value</option>
</select>
<select id="SecondDropdown">
<option value="-1"> </option>
<option value="12">VAL1 SELECT OPTION</option>
<option value="15">VAL2 SELECT OPTION</option>
<option value="10">VAL3 SELECT OPTION</option>
</select>
EDIT : Added a JsFiddle.
You do not have any option element having value=''. You need to use $("#SecondDropdown option[value='-1']").prop('selected',true); . you would also need to change the condition in if statement to this.value!='':
$('#FirstDropdown').change(function() {
if ( this.value!='' ){
$('#SecondDropdown option').filter(':contains(' + this.value + ')').prop('selected',true);
}else{
$("#SecondDropdown option[value='-1']").prop('selected',true);
}});
Working Demo
Try this :There is problem in your if condition as it is getting always true. You can use .length to check if option exist and select the option else select blank
$('#FirstDropdown').change(function() {
if ($('#SecondDropdown option:contains('+this.value +')').length>0){
$('#SecondDropdown option:contains('+this.value +')').prop('selected',true);
}else{
$("#SecondDropdown option[value='-1']").prop('selected',true);
}
});
JSFiddle Demo
This will work for you.
First, you have to check you this.value, because any string contains ''.
Second, as if works fine, you just need to filter options by [value=-1]
Final JS:
$('#FirstDropdown').change(function() {
var $second = $('#SecondDropdown option').filter(':contains(' + this.value + ')');
if (this.value && $second){
$second.prop('selected',true);
}else{
$("#SecondDropdown option[value=-1]").prop('selected',true);
}
});
In my HTML, I have a <select> with three <option> elements. I want to use jQuery to check each option's value against a Javascript var. If one matches, I want to set the selected attribute of that option. How would I do that?
Vanilla JavaScript
Using plain old JavaScript:
var val = "Fish";
var sel = document.getElementById('sel');
document.getElementById('btn').onclick = function() {
var opts = sel.options;
for (var opt, j = 0; opt = opts[j]; j++) {
if (opt.value == val) {
sel.selectedIndex = j;
break;
}
}
}
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<button id="btn">Select Fish</button>
jQuery
But if you really want to use jQuery:
var val = 'Fish';
$('#btn').on('click', function() {
$('#sel').val(val);
});
var val = 'Fish';
$('#btn').on('click', function() {
$('#sel').val(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<button id="btn">Select Fish</button>
jQuery - Using Value Attributes
In case your options have value attributes which differ from their text content and you want to select via text content:
<select id="sel">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
<script>
var val = 'Fish';
$('#sel option:contains(' + val + ')').prop({selected: true});
</script>
Demo
But if you do have the above set up and want to select by value using jQuery, you can do as before:
var val = 3;
$('#sel').val(val);
Modern DOM
For the browsers that support document.querySelector and the HTMLOptionElement::selected property, this is a more succinct way of accomplishing this task:
var val = 3;
document.querySelector('#sel [value="' + val + '"]').selected = true;
Demo
Knockout.js
<select data-bind="value: val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
<script>
var viewModel = {
val: ko.observable()
};
ko.applyBindings(viewModel);
viewModel.val(3);
</script>
Demo
Polymer
<template id="template" is="dom-bind">
<select value="{{ val }}">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</template>
<script>
template.val = 3;
</script>
Demo
Angular 2
Note: this has not been updated for the final stable release.
<app id="app">
<select [value]="val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</app>
<script>
var App = ng.Component({selector: 'app'})
.View({template: app.innerHTML})
.Class({constructor: function() {}});
ng.bootstrap(App).then(function(app) {
app._hostComponent.instance.val = 3;
});
</script>
Demo
Vue 2
<div id="app">
<select v-model="val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
val: null,
},
mounted: function() {
this.val = 3;
}
});
</script>
Demo
None of the examples using jquery in here are actually correct as they will leave the select displaying the first entry even though value has been changed.
The right way to select Alaska and have the select show the right item as selected using:
<select id="state">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
</select>
With jquery would be:
$('#state').val('AK').change();
You can change the value of the select element, which changes the selected option to the one with that value, using JavaScript:
document.getElementById('sel').value = 'bike';
DEMO
Markup
<select id="my_select">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
jQuery
var my_value = 2;
$('#my_select option').each(function(){
var $this = $(this); // cache this jQuery object to avoid overhead
if ($this.val() == my_value) { // if this option's value is equal to our value
$this.prop('selected', true); // select this option
return false; // break the loop, no need to look further
}
});
Demo
I want to change the select element's selected option's both value & textContent (what we see) to 'Mango'.
Simplest code that worked is below:
var newValue1 = 'Mango'
var selectElement = document.getElementById('myselectid');
selectElement.options[selectElement.selectedIndex].value = newValue1;
selectElement.options[selectElement.selectedIndex].textContent = newValue1;
Hope that helps someone. Best of luck.
Up vote if this helped you.
I used almost all of the answers posted here but not comfortable with that so i dig one step furter and found easy solution that fits my need and feel worth sharing with you guys.
Instead of iteration all over the options or using JQuery you can do using core JS in simple steps:
Example
<select id="org_list">
<option value="23">IBM</option>
<option value="33">DELL</option>
<option value="25">SONY</option>
<option value="29">HP</option>
</select>
So you must know the value of the option to select.
function selectOrganization(id){
org_list=document.getElementById('org_list');
org_list.selectedIndex=org_list.querySelector('option[value="'+id+'"]').index;
}
How to Use?
selectOrganization(25); //this will select SONY from option List
Your comments are welcome. :) AzmatHunzai.
Test this Demo
Selecting Option based on its value
var vals = [2,'c'];
$('option').each(function(){
var $t = $(this);
for (var n=vals.length; n--; )
if ($t.val() == vals[n]){
$t.prop('selected', true);
return;
}
});
Selecting Option based on its text
var vals = ['Two','CCC']; // what we're looking for is different
$('option').each(function(){
var $t = $(this);
for (var n=vals.length; n--; )
if ($t.text() == vals[n]){ // method used is different
$t.prop('selected', true);
return;
}
});
Supporting HTML
<select>
<option value=""></option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select>
<option value=""></option>
<option value="a">AAA</option>
<option value="b">BBB</option>
<option value="c">CCC</option>
</select>
Excellent answers - here's the D3 version for anyone looking:
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<script>
d3.select('#sel').property('value', 'Fish');
</script>
After a lot of searching I tried #kzh on select list where I only know option inner text not value attribute,
this code based on select answer I used it to change select option according to current page urlon this format
http://www.example.com/index.php?u=Steve
<select id="sel">
<option>Joe</option>
<option>Steve</option>
<option>Jack</option>
</select>
<script>
var val = window.location.href.split('u=')[1]; // to filter ?u= query
var sel = document.getElementById('sel');
var opts = sel.options;
for(var opt, j = 0; opt = opts[j]; j++) {
// search are based on text inside option Attr
if(opt.text == val) {
sel.selectedIndex = j;
break;
}
}
</script>
This will keeps url parameters shown as selected to make it more user friendly and the visitor knows what page or profile he is currently viewing .
You just write the code
var theVal = 1;
$('#variable_id').val(theVal).trigger('change');
I used this after updating a register and changed the state of request via ajax, then I do a query with the new state in the same script and put it in the select tag element new state to update the view.
var objSel = document.getElementById("selectObj");
objSel.selectedIndex = elementSelected;
I hope this is useful.
selectElement is a html <select> element.
Increment the value:
selectElement.selectedIndex++
Decrement the value:
selectElement.selectedIndex--
var accHos = document.getElementById("accHos");
function showName(obj) {
accHos.selectedIndex = obj.selectedIndex;
}
div {
color: coral;
}
select {
margin-left: 20px;
margin-bottom: 8px;
min-width: 120px;
}
<div>Select Account Number:</div>
<select id="accNos" name="" onchange="showName(this);">
<option value="">Select Account</option>
<option value="">1052021</option>
<option value="">2052021</option>
<option value="">3052021</option>
<option value="">4052021</option>
<option value="">5052021</option>
</select>
<div>Account Holder Name:</div>
<select id="accHos" name="" disabled>
<option value="">--Name--</option>
<option value="">Suhan</option>
<option value="">Cesur</option>
<option value="">Hopper</option>
<option value="">Rachel</option>
<option value="">Arya</option>
</select>
<!-- Just for my referece -->
Slightly neater Vanilla.JS version. Assuming you've already fixed nodeList missing .forEach():
NodeList.prototype.forEach = Array.prototype.forEach
Just:
var requiredValue = 'i-50332a31',
selectBox = document.querySelector('select')
selectBox.childNodes.forEach(function(element, index){
if ( element.value === requiredValue ) {
selectBox.selectedIndex = index
}
})