How to add "selected" to select option using javascript - 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

Related

Change option values of select 2 if select 1 has a value with jquery

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 :)

Update URL with two dropdown list in jquery

I do have two select box like this.
<select class="" id="sender" name="sender">
<option value="">---Select sender ---</option>
<option value="1">Corliss Barrie</option>
<option value="2">Marcie Nava</option>
<option value="3">Weston Bryand</option>
<option value="4">Osvaldo Lasker</option>
<option value="5">Regan Ruckman</option>
</select>
<select class="" id="reciever" name="reciever">
<option value="">---Select sender ---</option>
<option value="1">Araceli Scheff</option>
<option value="2">Assunta Marsch</option>
<option value="3">Yang Wengerd</option>
<option value="4">Branden Purtee</option>
<option value="5">Krystal Fresquez</option>
</select>
My question is I need to update the url with this two select box values, only if both dropdown selected.
I can do it for one dropdown like below, but not sure how to do it with two drop down.
$('#sender').change(function(){
var url = "?sender="+$(this).val();
window.location = url;
});
But my expected url is something similar to this:
?sender=value&reciever=value
Hope somebody may help me out.
Thank you.
you can pretty easy outsource the logic into one function that only changes url if both values are given
$('#sender, #receiver').change(changeUrl);
function changeUrl(){
if($('#receiver').val() != "" && $('#sender').val() != "" ){
url = "?sender="+$('#sender').val()+"&receiver="+$('#receiver').val();
window.location = url;
}
}
Just add another event listener and a conditional:
function changeURL(){
if($('#sender').val()!="" &&$('#receiver').val()!=""){
var url = "?sender="+$(this).val()+'&receiver="+$('#receiver').val();
window.location = url;
}
}
$('#sender').change(changeURL);
$('#receiver').change(changeURL);
Here is a working fiddle. Added a common class url to both select element. And then do functionality on change event.
$('.url').change(function(){
var sender = $('#sender').val();
var receiver = $('#reciever').val();
if(sender !== '' && receiver !== '') {
var url = "?sender=" + sender + "&reciever=" + receiver;
window.location = url;
}
});
Use it like this:
<select class="changeurl" id="sender" name="sender">
<option value="0">---Select sender ---</option>
<option value="1">Corliss Barrie</option>
<option value="2">Marcie Nava</option>
<option value="3">Weston Bryand</option>
<option value="4">Osvaldo Lasker</option>
<option value="5">Regan Ruckman</option>
</select>
<select class="changeurl" id="reciever" name="reciever">
<option value="0">---Select reciever ---</option>
<option value="1">Araceli Scheff</option>
<option value="2">Assunta Marsch</option>
<option value="3">Yang Wengerd</option>
<option value="4">Branden Purtee</option>
<option value="5">Krystal Fresquez</option>
</select>
And your jquery code will like this:
$('.changeurl').on('change', function (e) {
if( $('#sender').val()!="0" && $('#reciever').val()!="0" ){
var newURLString = window.location.href + "?sender=" + $('#sender').val() + "&reciever=" + $('#reciever').val();
window.location.href = newURLString;
}
});

Select value from dropdown list using the text

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.

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

Is there a SelectedIndex for an HTML5 DataList?

You can pick the current option of any select element:
mySelect.options[mySelect.selectedIndex]
Can I do the same with a DataList? Something like this:
<input id = "input" list = "datalist" type = "text" />
<datalist id = "datalist">
<option value = "No. 1"></option>
<option value = "No. 2"></option>
<option value = "No. 3"></option>
</datalist>
<script>
var datalist = document.getElementById ("datalist");
var input = document.getElementById ("input");
input.addEventListener ("keyup", function (event) {
if (event.which === 13) {
alert (datalist.options[datalist.selectedIndex]); // Example
}
}, false);
</script>
No, the datalist element is for providing autocomplete to inputs. It is a source of data, is hidden from the user, and multiple inputs may link to it. Therefore it doesn't make sense to have a selectedIndex.
Instead, you should simply check the .value of the input:
var datalist = document.getElementById ("datalist");
var input = document.getElementById ("input");
input.addEventListener ("keyup", function (event) {
if (event.which === 13) {
alert(input.value);
}
}, false);
Judging by specs, datalist object doesn't have selectedIndex property. But you can find it's default option, which have selected. Or compare input's value to each option value and manually find the index.
for (var i=0;i<datalist_id.options.length;i++)
if (datalist_id.options[i].value == input_id.value)
{alert(datalist_id.options[i].innerText);break;}
Lets say you have data attributes in the above example like this,
<input list="browsers" name="browser" value="Internet Explorer">
<datalist id="browsers">
<option value="Internet Explorer" data-company="Microsoft">
<option value="Firefox" data-company="Mozilla">
<option value="Chrome" data-company="Google/Alphabet">
<option value="Opera" data-company="Opera">
<option value="Safari" data-company="Apple">
</datalist>
and you want to obtain the data-company attribute of the selected item,
using the loop above
for (var i=0;i<datalist_id.options.length;i++) {
if (datalist_id.options[i].value == input_id.value) {
// obtains the data-company attrbute
console.log(datalist_id.options[i].getAttribute("data-company");
alert(datalist_id.options[i].innerText);
break;
}
}
You can just add a value to the input element. This will be shown to the user as the "default" value. If the user decides to change it, i.e. delete this value from the input field, then the list in the datalist will show up:
<input list="browsers" name="browser" value="Internet Explorer">
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
Here is the script for getting index from SelectedIndex of Datalist. Html from #pingle60
let x = document.getElementById("browsers").options;
let input = document.querySelector('input');
input.onchange = getIndex;
function getIndex(e) {
for (var i=0;i<x.length;i++) {
if (x[i].value == e.target.value) {
return i;
// alert('The index of SellectedIndex is : ' + i + ' and the value is : ' +x[i].value);
break;
}
}
}

Categories