Select value from dropdown list using the text - javascript

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

When one option is selected all others should be disabled

I have a dropdown menu that allows multiple selections. Now I want to make it when one particular option has selected all others to be disabled and enabled for selection. If that one particular is de-selected all others should be enabled again.
This is my select dropdown:
<select class="input-fields selectpicker" id="select_heigh" name="search[]" multiple>
<option value="all" selected>Search all</option>
<option value="tag">Tags</option>
<option value="username">Username</option>
<option value="email">Email</option>
<option value="full_name">Full Name</option>
</select>
And here is what I have tried for the js
$(document).ready(function() {
$('.selectpicker').selectpicker();
$('.selectpicker').on('change', function() {
if ($('option[value="all"]', this).is(':selected') && $(this).val().length > 1) {
$('option[value="all"]', this).prop('selected', false);
$('.selectpicker').selectpicker('refresh');
}
var selected = $(this).val();
if (selected.includes("tag")) {
$('option[value!="tag"]', this).prop('disabled', true);
} else {
$('option[value!="tag"]', this).prop('disabled', false);
}
if (selected.length > 3) {
$(this).selectpicker('setStyle', 'selected-count', 'btn-danger');
$(this).selectpicker('setTitle', selected.length + ' select(s)');
} else {
$(this).selectpicker('setStyle', 'selected-count', 'btn-default');
$(this).selectpicker('setTitle', 'Select');
}
});
});
I want when "Tag" is selected the other options to be disabled. When "Tag" is de-selected the others are enabled. When any other option is selected to no effect on others.
Also, the counting of selected choices doesn't work as expected. It should start showing Selected(3), Selected(4) ... after the third selection. Currently, it shows all of them not count of them.
I'm not that familiar with JS and not sure if I'm on the right path here
What the OP wants to achieve is a rather unexpected behavior of a native form control.
And in case one changes the behavior it should be based on using what form elements or elements in particular do support natively like the disabled- and the dataset-property.
An implementation then could be as simple as querying the correct select element and subscribing an event listener to any click event which occurres on the very select element. The change event can not be used since any further changes are impossible once a single option is selected but all other option are disabled. An option element's dataset gets used as lookup in order to detect whether the very element already has been selected before the current click handling.
function handleOptionClickBehavior({ target }) {
const optionNode = target.closest('option');
const nodeValue = optionNode?.value;
if (nodeValue === 'tag') {
const optionNodeList = [...optionNode.parentNode.children]
.filter(node => node !== optionNode);
const { dataset } = optionNode;
if (dataset.hasOwnProperty('selectedBefore')) {
Reflect.deleteProperty(dataset, 'selectedBefore');
optionNode.selected = false;
optionNodeList
.forEach(node => node.disabled = false);
} else {
dataset.selectedBefore = '';
optionNodeList
.forEach(node => node.disabled = true);
}
}
}
document
.querySelector('.selectpicker')
.addEventListener('click', handleOptionClickBehavior)
body { zoom: 1.2 }
<select class="input-fields selectpicker" id="select_heigh" name="search[]" size="5" multiple>
<option value="all" selected>Search all</option>
<option value="tag">Tags</option>
<option value="username">Username</option>
<option value="email">Email</option>
<option value="full_name">Full Name</option>
</select>

How to add "selected" to select option using javascript

I have the following code and I am trying to add "selected" to the option dynamically, when the user select an option. How can i do it using Javascript ?
Example when the user select "Candy" I want to add <option value="candy" selected>Candy</option>
function urlDirect() {
var businessTypeSelected = document.getElementById("BusinessType").value;
//alert("x " +x);
if (businessTypeSelected != "") {
window.location.href = location.host + businessTypeSelected;
document.getElementById("BusinessType").selectedIndex = document.getElementById("BusinessType").selectedIndex;
} else {
}
}
<span class="custom-dropdown custom-dropdown--blue custom-dropdown--large">
<select id="BusinessType" class="custom-dropdown__select custom-dropdown__select--blue" onChange="urlDirect()">
<option value="default">Select your business type</option>
<option value="auto">Auto </option>
<option value="aero">Aeroplane</option>
<option value="film">Film</option>
<option value="candy">Candy</option>
</select>
</span>
This should do:
var select = document.getElementById('BusinessType');
select.addEventListener('change', function() {
select.options[select.selectedIndex].setAttribute('selected');
});
Also I'd suggest you change the name of the id to business-type since CSS isn't written in camelCase.
var select = document.getElementById('BusinessType');
select.options[indexOfoption].selected = true;
You can do it by this method too. it's easy to understand

How to establish relationship between option tag of different select tags in html

I have three select tags in HTML with option tag.I want to establish relationship between option tags of different select tag.
EDIT-1
When I choose Reference-1 from select name="reference" then 2014-10-10 07:17:00 and 2014-10-10 08:46:00 from select name="from" and select name="to" should only be present in the dropdown list.When I choose Reference-2 then 2014-09-01 10:00:00 and 2014-09-01 11:00:00 should only be present in dropdown list of from and to select tag. My html code for is-
<form method="post">
Select Reference:
<select name="reference">
<option value="Select">Select</option>
<option value="Reference-1">Reference-1;</option>
<option value="Reference-2">Reference-2</option>
<option value="Reference-3">Reference-3</option>
<option value="Reference-4">Reference-4</option>
</select>
From Date:
<select name="from">
<option value="Select">Select</option>
<option value="2014-10-10 07:17:00">2014-10-10 07:17:00</option>
<option value="2014-09-01 10:00:00">2014-09-01 10:00:00</option>
<option value="2014-09-08 10:00:00">2014-09-08 10:00:00</option>
</select>
To Date:
<select name="to">
<option value="Select">Select</option>
<option value="2014-10-10 08:46:00">2014-10-10 08:46:00</option>
<option value="2014-09-01 11:00:00">2014-09-01 11:00:00</option>
<option value="2014-09-08 10:00:00">2014-09-08 11:00:00</option>
</select><br>
<b>Select Date to be compared</b>
<p>Date: <input type="text" id="datepicker"></p>
<input type="submit" value="Submit"><br>
</form>
Get the index of the selected option from reference select element and then disable all the options of from and to select elements except the option with index of the previous index you got from reference select option.
javaScript Solution :
var reference = document.getElementsByName("reference")[0];
var fromSelect = document.getElementsByName("from")[0];
var toSelect = document.getElementsByName("to")[0];
reference.onchange = function(){
var selectedIndex = this.selectedIndex;
for(var i = 1; i <= fromSelect.length; i++){
if(i != selectedIndex){
fromSelect.getElementsByTagName("option")[i].disabled = true;
toSelect.getElementsByTagName("option")[i].disabled = true;
} else{
fromSelect.getElementsByTagName("option")[i].disabled = false;
toSelect.getElementsByTagName("option")[i].disabled = false;
}
}
};
jsFiddle
jQuery Solution :
$("select[name='reference']").on("change", function(){
var $fromSelect = $("select[name='from']");
var $toSelect = $("select[name='to']");
var selectedIndex = $(this).children("option:selected").index();
$fromSelect.children("option").removeAttr("disabled");
$toSelect.children("option").removeAttr("disabled");
$fromSelect.children("option").not(":eq(" + selectedIndex +")").prop("disabled", "disabled");
$toSelect.children("option").not(":eq(" + selectedIndex +")").prop("disabled", "disabled");
});
jsFiddle
If second selection values are dependent on the first selection option, then you should disable the whole second selection until the first one is selected.
When the first one is selected then disable all the unrelated options in second selection and make it enabled to the user. Let me know if it helped.
$("select[name='reference']").on('change', function() {
var value = $(this).val(); // first selection value
if ("Reference-1" == value ) {
var $selection2 = $("select[name='from']");
$selection2.find("option[value*='2014-09-01 10:00:00']").prop('disabled',true);
$selection2.find("option[value*='2014-09-08 10:00:00']").prop('disabled',true);
}
...
});
Here is DEMO

How to run a piece of javascript when you select a dropdown option?

I have a select with loads of options. (Code below shortened for sake of example).
I want it to set the value of the input textfield "hoh" to "10" when you click/select all dropdown options, except one, that should set it to 50.
I imagined something like this would work, but its not. What am I doing wrong here?
<select>
<option onselect="document.getElementById('hoh').value = '50'">Hey</option>
<option onselect="document.getElementById('hoh').value = '10'">Ho</option>
<option onselect="document.getElementById('hoh').value = '10'">Lo</option>
....
</select>
<input type="text" id="hoh" value="10">
Something like this should work:
<script>
function myFunc(val) {
if (val == '50') {
document.getElementById('hoh').value = val;
} else {
document.getElementById('hoh').value = '10';
}
}
</script>
<select onchange="myFunc(this.value)">
<option value="1">one</option>
<option value="2">two</option>
<option value="50">fifty</option>
</select>
http://jsfiddle.net/isherwood/LH57d/3
The onselect event refers to selecting (or highlighting) text. To trigger an action when a dropbox selection changes, use the onchange event trigger for the <select> element.
E.g. Since you didn't already set the value attribute of your option tags.
<select id="myselect" onchange="myFunction()">
<option value="50">Hey</option>
<option value="10">Ho</option>
<option value="10">Lo</option>
....
</select>
and somewhere inside of a <script> tag (presumably in your HTML header) you define your javascript function.
<script type="text/javascript>
function myFunction() {
var dropbox = document.getElementById('myselect');
document.getElementById('hoh').value = dropbox[dropbox.selectedIndex].value;
}
</script>
I'm not sure it's wise to repeat the same value among different options in a droplist, but you could expand on this to implement the result other ways, such as if the sole option which will have value 50 is in a certain position, you could compare the selectedIndex to that position.
you could add an onchange event trigger to the select, and use the value of an option to show in the textbox
see http://jsfiddle.net/Icepickle/5g5pg/ here
<select onchange="setValue(this, 'hoh')">
<option>-- select --</option>
<option value="10">Test</option>
<option value="50">Test 2</option>
</select>
<input type="text" id="hoh" />
with function setValue as
function setValue(source, target) {
var tg = document.getElementById(target);
if (!tg) {
alert('No target element found');
return;
}
if (source.selectedIndex <= 0) {
tg.value = '';
return;
}
var opt = source.options[source.selectedIndex];
tg.value = opt.value;
}
Try this code
var inp = document.getElementById('hoh');
sel.onchange = function(){
var v = this.value;
if( v !== '50'){
v = '10';
}
inp.value = v;
};

javascript validation in a form

I am having trouble getting this validation to work. I am validating that a selectbox has been chosen and not left on the default option within my form.
Form:
<label for="reason">How can we help?</label>
<select name="reas">
<option value="Please Select">Please Select</option>
<option value="Web Design">Web Design</option>
<option value="branding">Branding</option>
<option value="rwd">Responsive Web Design</option><span id="dropdown_error"></span>
</select>
Onclick event:
$(document).ready(function(){
$('#contactForm').submit(function(){
return checkSelect();
});
});
Function:
function checkSelect() {
var chosen = "";
var len = document.conform.reas.length;
var i;
for (i = 0; i < len; i++){
if (document.conform.reas[i].selected){
chosen = document.conform.reas[i].value;
}
}
if (chosen == "Please Select") {
document.getElementById("dropdown_error").innerHTML = "No Option Chosen";
return false;
}
else{
document.getElementById("dropdown_error").innerHTML = "";
return true;
}
}
I also get this error in the console:
Uncaught TypeError: Cannot set property 'innerHTML' of null
I am really new to javascript, so, I am learning and trying some simple examples at the moment, but I cannot see what is causing this not to validate.
Any help appreciated
First, you can't have your error span inside the <select>. Move it outside of the <select> HTML, and that will make the JS error go away.
<label for="reason">How can we help?</label>
<select name="reas">
<option value="select">Please Select</option>
<option vlaue="Web Design">Web Design</option>
<option vlaue="branding">Branding</option>
<option vlaue="rwd">Responsive Web Design</option>
</select>
<span id="dropdown_error"></span>
Then, since you are already using jQuery, you could shorten your whole validation function to just this:
function checkSelect() {
var chosen = $('select[name="reas"]').val();
if (chosen == "select") {
$("dropdown_error").text("No Option Chosen");
return false;
} else {
$("dropdown_error").text("");
return true;
}
}
Change your default selection to an optgroup:
<optgroup>Please Select</optgroup>
Then it won't be selectable
https://developer.mozilla.org/en-US/docs/HTML/Element/optgroup
Your default value is "select" and you are checking "Please Select". Use the same value.
Change this
<option value="select">Please Select</option>
to
<option value="Please Select">Please Select</option>
EDIT: I would use the following code. To fix javascript issue, make sure you put the script just before closing body tag. Your script is executing before the document is parsed
<label for="reason">How can we help?</label>
<select id="reas" name="reas">
<option value="">Please Select</option>
<option vlaue="Web Design">Web Design</option>
<option vlaue="branding">Branding</option>
<option vlaue="rwd">Responsive Web Design</option><span id="dropdown_error"> </span> </option>
function checkSelect() {
var chosen = document.getElementById["reas"].value;
if (chosen == "") {
document.getElementById("dropdown_error").innerHTML = "No Option Chosen";
return false;
}
else{
document.getElementById("dropdown_error").innerHTML = "";
return true;
}
}

Categories