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>
Related
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 have a dynamically generated <select> field with <option>.
<select>
<option value=""></option>
<option value=""></option>
<option value=""> False</option>
<option value=""> True</option>
<option value="">False False</option>
<option value="">False True</option>
<option value="">True</option>
<option value="">True True</option>
</select>
I would like to remove the duplicate occurrences and combinations. The final <select> field with <option> should look like :
<select>
<option value=""></option>
<option value="">False</option>
<option value="">True</option>
</select>
Here is how my fiddle looks like. Been trying to solve this for hours.
var values = [];
$("select").children().each(function() {
if (values.length > 0) {
var notExists = false;
for (var x = 0; x < values.length; x++) {
var _text = this.text.replace(/\s/g, "");
var value = values[x].replace(/\s/g, "");
if (values[x].length > _text.length) {
//console.log('>>+', value, ' || ', _text, value.indexOf(_text))
notExists = value.indexOf(_text) > -1 ? true : false;
} else {
//console.log('>>*', value, ' || ', _text, _text.indexOf(value))
notExists = _text.indexOf(value) > -1 ? true : false;
}
}
if (notExists) {
//this.remove();
values.push(this.text);
}
} else {
values.push(this.text);
}
});
Any help to solve this is appreciated.
You can use map() to return all options text and use split() on white-space. Then to remove duplicates you can use reduce() to return object. Then you can empty select and use Object.keys() to loop each property and append to select.
var opt = $("select option").map(function() {
return $(this).text().split(' ')
}).get();
opt = opt.reduce(function(o, e) {return o[e] = true, o}, {});
$('select').empty();
Object.keys(opt).forEach(function(key) {
$('select').append(' <option value="">'+key+'</option>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value=""></option>
<option value=""></option>
<option value="">False</option>
<option value="">True</option>
<option value="">False False</option>
<option value="">False True</option>
<option value="">True</option>
<option value="">True True</option>
</select>
You can loop through each of this children text , then use substring to get the first text & put it in an array.
Once done empty the select element and append the newly created options
var _textHolder=[]; // NA empty array to hold unique text
var _options="";
$("select").children().each(function(item,value) {
var _textVal = $(this).text().trim(); // Remove white space
//get the first text content
var _getText = _textVal.substr(0, _textVal.indexOf(" "));
// if this text is not present in array then push it
if(_textHolder.indexOf(_getText) ==-1){
_textHolder.push(_getText)
}
});
// Create new options with items from _textHolder
_textHolder.forEach(function(item){
_options+='<option value="">'+item+'</option>'
})
// Empty current select element and append new options
$('select').empty().append(_options);
JSFIDDLE
I would do with pure JS ES6 style. This is producing a words array from the whitespace separated options element's innerText value regardless the words are in the front, middle or the end; and it will create a unique options list from that. Basically we are concatenating these arrays and getting it unified by utilizing the new Set object. The code is as follows;
var opts = document.querySelector("select").children,
list = Array.prototype.reduce.call(opts, function(s,c){
text = c.innerText.trim().split(" ");
return new Set([...s].concat(text)) // adding multiple elements to a set
},new Set());
list = [...list]; // turn set to array
for (var i = opts.length-1; i >= 0; i--){ //reverse iteration not to effect indices when an element is deleted
i in list ? opts[i].innerText = list[i]
: opts[i].parentNode.removeChild(opts[i]);
}
<select>
<option value=""></option>
<option value=""></option>
<option value=""> False</option>
<option value=""> True</option>
<option value="">False False</option>
<option value="">False True</option>
<option value="">True</option>
<option value="">True True</option>
</select>
I have created a page with two drop-down menus containing various values.
Now I would like to add a "randomize" button. When clicked, this button would select any of the values at random in both fields. (the values are also copied on a box above each menu).
Project idea for drop down menus
So far I've coded the menus and the words display in the boxes above them when the user selects them. But now I'm trying to add a randomise button that would put any of the values in the drop down as selected and of course displayed in the above text box. Ideally, more values in the drop-down menus would be added every once in a while without making the script dysfunctional... and ideally it would all be contained in a HTML file (calling for JQuery or javascript is ok).
I've looked at this but it doesn't apply.
I also looked at this but it's not really a feature that the user activates.
Very grateful if anyone can help! Thanks
hope this helps
HTML :
<select id="s1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select id="s2">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Javascript:
var minNumber = 0;
var maxNumber = 3;
function randomNumberFromRange(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
$("#s2")[0].selectedIndex = randomNumberFromRange(minNumber, maxNumber);
$("#s1")[0].selectedIndex = randomNumberFromRange(minNumber, maxNumber);
I create this fiddle for you...
https://jsfiddle.net/s59g8vdp/
The first example you have provided is very close to what you want to do. You just need to:
Get a random value between 0 and options.length - 1.
Get option[random] and set its selected property to true.
Copy that option's .innerHTML or .value to the .innerHTML or .value of the label on top of the dropdowns.
This is all you probably need:
function randomizeSelect(selectId, fieldId) {
var options = document.getElementById(selectId).children;
var random = Math.floor(options.length * (Math.random() % 1));
var option = options[random];
option.selected = true;
document.getElementById(fieldId).value = option.innerHTML; // You can use .value instead in both places
}
var values = {};
window.onload = function(e) {
document.onchange = function(e) { // Event Delegation: http://davidwalsh.name/event-delegate
var t = e.target;
if(t.tagName == "SELECT")
document.getElementById(t.id.replace("Select","Label")).value = t.children[t.selectedIndex].innerHTML;
}
document.oninput = function(e) {
var t = e.target;
if(t.tagName == "INPUT") {
if(values.hasOwnProperty(t.id))
var options = values[t.id];
else
var options = document.getElementById(t.id.replace("Label","Select")).children;
var currentValue = t.value;
for(i in options) {
if(options[i].innerHTML == currentValue) { // Can also use .value
options[i].selected = true;
break;
}
}
}
}
document.getElementById("randomize").onclick = function(e) {
randomizeSelect("leftSelect", "leftLabel");
randomizeSelect("rightSelect", "rightLabel");
}
}
<input type="text" id="leftLabel" value="Left 1">
<select id="leftSelect">
<option value="l1" selected>Left 1</option>
<option value="l2">Left 2</option>
<option value="l3">Left 3</option>
</select>
<input type="text" id="rightLabel" value="Right 1">
<select id="rightSelect">
<option value="r1" selected>Right 1</option>
<option value="r2">Right 2</option>
<option value="r3">Right 3</option>
</select>
<button id="randomize">RANDOMIZE</button>
This will create random number and click on random div menu:
$(function(){
$(".menu").click(function(){
alert("you clicked "+$(this).text());
});
});
function doSomthing(){
var rand=Math.floor((Math.random() * 5));
alert(rand+1);
var ele = $(".menu").get(rand);
$(ele).click();
}
fiddle example: link
Or you can use this example to put value in the menu, or wherever you want: link 2
just a concept how to make that
$('input').on('click',function(){
var randomnum = Math.floor(Math.random()*$('ul li').length);
alert($('ul li').eq(randomnum).text());
});
DEMO FIDDLE
Randomize Button added
see... ;) i hope this solve your problem!
https://jsfiddle.net/s59g8vdp/1/
Html :
<select id="s1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select id="s2">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<a id="randomize" href="#">randomize</a>
Javascript :
var minNumber = 0;
var maxNumber = 3;
$("#randomize").click(function(){
$("#s2")[0].selectedIndex = randomNumberFromRange(minNumber, maxNumber);
$("#s1")[0].selectedIndex = randomNumberFromRange(minNumber, maxNumber);
});
function randomNumberFromRange(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
$("#s2")[0].selectedIndex = randomNumberFromRange(minNumber, maxNumber);
$("#s1")[0].selectedIndex = randomNumberFromRange(minNumber, maxNumber);
I have two drop downs with exactly the same values.
I want the drop down 2 to display the values based on the selection of items of drop down 1.
So the selected index of drop down 2 will be equal to or more than the selected index of drop down 1.
document.getElementById("SELECTB").selectedIndex >= document.getElementById("SELECTA").selectedIndex
So if B is selected in Drop down 1 then selectable options in drop down 2 will be B,C and D. (A will be not selectable item)
http://jsfiddle.net/xxyhm78t/1/
Solution working with pure Javascript:
var select1 = document.getElementById("SELECTA");
var select2 = document.getElementById("SELECTB");
select1.onchange = function () {
while (select2.firstChild) {
select2.removeChild(select2.firstChild);
}
for (var i = select1.selectedIndex; i < select1.options.length; i++) {
var o = document.createElement("option");
o.value = select1.options[i].value;
o.text = select1.options[i].text;
select2.appendChild(o);
}
}
Fiddle
Reference: This is an adjusted solution from javascript Change the Dropdown values based on other dropdown
Update: Like asked in the comment - to disable the options instead of removing them:
var select1 = document.getElementById("SELECTA");
var select2 = document.getElementById("SELECTB");
select1.onchange = function () {
while (select2.firstChild) {
select2.removeChild(select2.firstChild);
}
for (var i = 0; i < select1.options.length; i++) {
var o = document.createElement("option");
o.value = select1.options[i].value;
o.text = select1.options[i].text;
(i <= select1.selectedIndex)
? o.disabled = true
: o.disabled = false ;
select2.appendChild(o);
}
}
Adjusted Fiddle
Update 2: Like asked in the comment if it's possible to adjust this to use class names instead of ids - yes, by using getElementsByClassName(). I've adjusted in this Fiddle both selects to have class="SELECTA" and class="SELECTB" instead of the previously used id. The according adjustment for the Javascript is only the declaration of the variables:
var select1 = document.getElementsByClassName("SELECTA")[0];
var select2 = document.getElementsByClassName("SELECTB")[0];
As you already know, an id is a unique attribute, therefore it's possible to get a single element using getElementById(). getElementsByClassName() returns a collection of HTML elements instead, even if there's only a single element having the class. So it's - in this example - necessary to address the 1st element of this collection. As counting starts by 0, the first (and only) element having the class "SELECTA" is getElementsByClassName("SELECTA")[0].
Reference: https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName#Syntax
You can do this using selectedIndex with the following piece of code:
$("#SELECTA").change(function() {
var selIndex = this.selectedIndex;
$("#SELECTB").find("option").each(function(k,v) {
$(this).attr("disabled", selIndex > k);
});
});
Depending on what it is you are after, you may need to reset #SELECTB if one of the disabled values is selected.
I think this is what you are looking for:
$("select").on("change", function (e) {
var sel = this.selectedIndex;
$("#SELECTB option").each(function (i, e) {
$(this).prop("disabled", sel > i);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="SELECTA">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<select id="SELECTB">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
And this can be even more general:
$("select").on("change", function (e) {
var sel = this.selectedIndex;
var nextSelect = $(this).parent().find("select").not(this);
$(nextSelect).children().each(function (i, e) {
$(this).prop("disabled", sel > i);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="SELECTA">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<select id="SELECTB">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
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;
};