Get all select/option lists start by something - javascript

In an HTML page i have severals list.
<select name="salut-1358937506000-OK">
<option selected="" value="OK">OK</option>
<option value="OK">NOK</option>
</select>
<select name="salut-1358937582000-OK">
<option selected="" value="OK">OK</option>
<option value="OK">NOK</option>
</select>
...
In javascript, I want to get all select/option list which started by "salut-".
For theses list, i want to compare his name and his selected value.
I know it is possible in jQuery but can't use jquery, only javascript (JSNI with GWT exactly).
Have you an idea?
Thanks!

var selects = document.getElementsByTagName('select');
var sel;
var relevantSelects = [];
for(var z=0; z<selects.length; z++){
sel = selects[z];
if(sel.name.indexOf('salut-') === 0){
relevantSelects.push(sel);
}
}
console.log(relevantSelects);

You can use the getElementsByTagName function to get each SELECT name, for example:
var e = document.getElementsByTagName("select");
for (var i = 0; i < e.length; i++){
var name = e[i].getAttribute("name");
}
Then you can use the following code to get each OPTION for the SELECT, to do any necessary comparisons:
var options = e[i].getElementsByTagName("option")

Related

How to use selected option is variable select list

For my code i need 2 selects, the first select is static (4 options that dont change) and the second select is dependant on what is selected in the first select.
Then depending on what is chosen in de the second list a function is executed.
i found some example code one W3schools that allow me to make the whole list thing:
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_select_options3
So this works really well but now i dont know how to attach a function to the selected options in the second select since there is no where in the html to do something like an onchange.
Each option from the second select should have a function (in my code the selected option will display an image corresponding with the chosen option)
<!DOCTYPE html>
<html>
<body>
<select id="car" onchange="ChangeCarList()">
<option value="">-- Car --</option>
<option value="VO">Volvo</option>
<option value="VW">Volkswagen</option>
<option value="BMW">BMW</option>
</select>
<select id="carmodel"></select>
<script>
var carsAndModels = {};
carsAndModels['VO'] = ['V70', 'XC60', 'XC90'];
carsAndModels['VW'] = ['Golf', 'Polo', 'Scirocco', 'Touareg'];
carsAndModels['BMW'] = ['M6', 'X5', 'Z3'];
function ChangeCarList() {
var carList = document.getElementById("car");
var modelList = document.getElementById("carmodel");
var selCar = carList.options[carList.selectedIndex].value;
while (modelList.options.length) {
modelList.remove(0);
}
var cars = carsAndModels[selCar];
if (cars) {
var i;
for (i = 0; i < cars.length; i++) {
var car = new Option(cars[i], i);
modelList.options.add(car);
}
}
}
</script>
</body>
</html>

Javascript get specific values from array list

<select name="List" id="List">
<option value="">-Select-</option>
<option value="">--Product--</option>
<option value="">product1</option>
<option value="">product2</option>
<option value="">product3</option>
<option value="">--Software--</option>
<option value="">software1</option>
<option value="">software2</option>
<option value="">software3</option>
<option value="">--Services--</option>
<option value="">service1</option>
<option value="">service2</option>
<option value="">service3</option>
</select>
I have the above List on my HTML select field.
I want to be able to get only the values --Product--, --Software--, --Services--
So I created an loop to go throw the list of products and used the method startwith to pickup the values starting with "--".
function loadFilter() {
var x = document.getElementById('List');
var i;
var n;
for (i = 0; i < x.length; i++) {
str = x[i].text
var n = str.startsWith('--');
flag = true;
if (n == true) {
alert(x[i].text); // list --Product--, --Software--, --Services--
alert(x[3].text); // prints from the LIST <product1> and not <--Services-->
}
}
}
So when the flag is true, the alert(x[i].text); list correctly the values (--Product--, --Software--, --Services--).
But when I try to get them by their values(index), E.G ..I need to get only (--Services--), so I use x[3].text), but this returns me the whole List values >> and not <--Services-->.
You can use the below code to populate array arr with the list of options having "--".
Then you can use arr[2] to get --Services--.
var arr = [];
[].slice.call(document.querySelectorAll("#List option")).map(function(el){
if (el.text.indexOf("--") === 0) arr.push(el.text);
});
console.log(arr)
console.log(arr[2])
<select name="List" id="List">
<option value="">-Select-</option>
<option value="">--Product--</option>
<option value="">product1</option>
<option value="">product2</option>
<option value="">product3</option>
<option value="">--Software--</option>
<option value="">software1</option>
<option value="">software2</option>
<option value="">software3</option>
<option value="">--Services--</option>
<option value="">service1</option>
<option value="">service2</option>
<option value="">service3</option>
</select>
Here you go:
function loadFilter() {
var element = document.getElementById('List');
var children = element.children;
var filtered = [];
for (var i = 0; i < children.length; i++) {
if (children[i].textContent.startsWith('--')) {
filtered.push(children[i].textContent);
}
}
return filtered;
}
To recap what the function did:
Get the element "List"
Get the children of "List"
Create an array to hold elements that pass the filter
Go through each element and add those with match the specified regex
Return the elements that pass the filter
I'm still not entirely sure what you're trying to do. --Services-- is index 9, not 3. To get --Services-- you need x[9].text
If you want to rearrange the three --xx-- into their own index, you need to push them into a new array, like so:
var output = []
if (n === true) output.push(x[i].text)
console.log(output[2]) // --Services--
You can use simple forEach loop to loop through elements like here, but first you need to create Array from your DOM Node list:
var list = Array.from(x);
list.forEach((value,index)=>{
if (value.text.startsWith('--')){
alert(value.text);
}
});
I've put it up on fiddle so you can check:
https://jsfiddle.net/pegla/qokwarcy/
First of all, you don't seen to be using your flag at all.
If I understood it correctly, you are trying to get --Services-- using x[3].text, but if you count your whole list the element at index [3] is the . You can verify that with the code bellow:
f (n == true) {
alert('index '+ i + ': ' + x[i].text); // list --Product--, --Software--, --Services--
}
You could create a new array containing the filtered options and then access the with the known index:
var filteredArray = [];
f (n == true) {
filteredArray.push(x[i]); //insert the element in the new array.
}
alert(filteredArray[2].text) //print --Service--, the third element of filtered array.
Remember that javascript has zero indexed array, so the first element has index 0, so, in order to acces the third element you'll need the index 2.
May be you want to try using optgroups?
Something like this:
<select name="List" id="List">
<option value="">-Select-</option>
<optgroup label="--Product--">
<option value="">product1</option>
<option value="">product2</option>
<option value="">product3</option>
</optgroup>
<optgroup label="--Software--">
<option value="">software1</option>
<option value="">software2</option>
<option value="">software3</option>
</optgroup>
<optgroup label="--Services--">
<option value="">service1</option>
<option value="">service2</option>
<option value="">service3</option>
</optgroup>
</select>
Then,
var select = document.getElementById('List');
var optgroups = select.getElementsByTagName('optgroup');
console.log(optgroups[2].label);
Will show:
--Services--
try:
function load() {
list = document.getElementById('List');
var data = document.getElementsByTagName('option');
currentCatagory=null;//the current selected catagory
currentvalue=null;
listdata=[];
//for all the options
for(cnt = 0; cnt < data.length; cnt++){
var e = data[cnt].innerHTML;//get option text
if(e.startsWith('-')){//test to make a catagory out of it
if(currentCatagory!=null)//do not concat is listdata is null
listdata=listdata.concat(currentCatagory);
currentCatagory = {"this":e,"listOfItems":[]};//create the catagory
}else if(currentCatagory!=null){//make sure currentCatagory is not null
var l=currentCatagory.listOfItems;//get the Catagory's list
currentCatagory.listOfItems = l.concat(e);//and add e
}
}
listdata=listdata.concat(currentCatagory);//add last catagory
//sets the list to show only catagories
var inner='';
for (i = 0; i < listdata.length; i++) {
inner+=parseOp(listdata[i].this);
}
list.innerHTML=inner;
}
function update(){
//check to make sure everything is loaded
if(typeof list=='undefined'){
load();
}
var inner='';//the new options
var value=list.options[list.selectedIndex].innerHTML;
if(value==currentvalue) return;
if(value.startsWith('-')){//if catagory
if(value.startsWith('--')){//if not -Select-
for (i = 0; i < listdata.length; i++) {//for all catagories
if(value==listdata[i].this){//if it is the current selected catagory then...
currentCatagory=listdata[i];//update the currentCatagory object
inner+=parseOp(listdata[i].this);//parse as option and append
//then append catagory's items
for(item in listdata[i].listOfItems){
inner+=parseOp(listdata[i].listOfItems[item]);
}
}else{//appends the other catagories
inner+=parseOp(listdata[i].this);
}
}
}else{//if it is '-select-' then just append the catagories
for (i = 0; i < listdata.length; i++) {
inner+=parseOp(listdata[i].this);
}
}
//set the new options
list.innerHTML=inner;
}
}
function parseOp(str){
//parse the options
return '<option value="">'+str+'</option>';
}
<select name="List" id="List" onchange="update();">
<option value="">-Select-</option>
<option value="">--Product--</option>
<option value="">product1</option>
<option value="">product2</option>
<option value="">product3</option>
<option value="">--Software--</option>
<option value="">software1</option>
<option value="">software2</option>
<option value="">software3</option>
<option value="">--Services--</option>
<option value="">service1</option>
<option value="">service2</option>
<option value="">service3</option>
</select>
and to set the dropdown box you will have to run load() otherwise load() will only be called after the first change event occurs.

Javascript/jQuery: Set Values (Selection) in a multiple Select

I have a multiple select:
<select name='strings' id="strings" multiple style="width:100px;">
<option value="Test">Test</option>
<option value="Prof">Prof</option>
<option value="Live">Live</option>
<option value="Off">Off</option>
<option value="On">On</option>
</select>
I load data from my database. Then I have a string like this:
var values="Test,Prof,Off";
How can I set this Values in the multiple select? Already tried change the string in an array and put it as value in the multiple, but doesnt work...!
Can someone help me with this? THANKS!!!
Iterate through the loop using the value in a dynamic selector that utilizes the attribute selector.
var values="Test,Prof,Off";
$.each(values.split(","), function(i,e){
$("#strings option[value='" + e + "']").prop("selected", true);
});
Working Example http://jsfiddle.net/McddQ/1/
in jQuery:
$("#strings").val(["Test", "Prof", "Off"]);
or in pure JavaScript:
var element = document.getElementById('strings');
var values = ["Test", "Prof", "Off"];
for (var i = 0; i < element.options.length; i++) {
element.options[i].selected = values.indexOf(element.options[i].value) >= 0;
}
jQuery does significant abstraction here.
Just provide the jQuery val function with an array of values:
var values = "Test,Prof,Off";
$('#strings').val(values.split(','));
And to get the selected values in the same format:
values = $('#strings').val();
Pure JavaScript ES6 solution
Catch every option with a querySelectorAll function and split the values string.
Use Array#forEach to iterate over every element from the values array.
Use Array#find to find the option matching given value.
Set it's selected attribute to true.
Note: Array#from transforms an array-like object into an array and then you are able to use Array.prototype functions on it, like find or map.
var values = "Test,Prof,Off",
options = Array.from(document.querySelectorAll('#strings option'));
values.split(',').forEach(function(v) {
options.find(c => c.value == v).selected = true;
});
<select name='strings' id="strings" multiple style="width:100px;">
<option value="Test">Test</option>
<option value="Prof">Prof</option>
<option value="Live">Live</option>
<option value="Off">Off</option>
<option value="On">On</option>
</select>
var groups = ["Test", "Prof","Off"];
$('#fruits option').filter(function() {
return groups.indexOf($(this).text()) > -1; //Options text exists in array
}).prop('selected', true); //Set selected
Basically do a values.split(',') and then loop through the resulting array and set the Select.
Pure JavaScript ES5 solution
For some reason you don't use jQuery nor ES6? This might help you:
var values = "Test,Prof,Off";
var splitValues = values.split(',');
var multi = document.getElementById('strings');
multi.value = null; // Reset pre-selected options (just in case)
var multiLen = multi.options.length;
for (var i = 0; i < multiLen; i++) {
if (splitValues.indexOf(multi.options[i].value) >= 0) {
multi.options[i].selected = true;
}
}
<select name='strings' id="strings" multiple style="width:100px;">
<option value="Test">Test</option>
<option value="Prof">Prof</option>
<option value="Live">Live</option>
<option value="Off">Off</option>
<option value="On" selected>On</option>
</select>
Use this:
$('#demo').multiselect('select', value);
For multiple values just use a loop
For more properties this page is very good
this is error in some answers for replace |
var mystring = "this|is|a|test";
mystring = mystring.replace(/|/g, "");
alert(mystring);
this correction is correct but the | In the end it should look like this \|
var mystring = "this|is|a|test";
mystring = mystring.replace(/\|/g, "");
alert(mystring);

options is null or not an object

I am trying to select dropdown automatically based on values from another dropdown. Second dropdown will have more values than first one. If I select the first dropdown, then the second should be selected automatically. I tried the below code and getting error: Options is null or not an object. ???
<script type="text/javascript">
function showState(me){
var values = ''; //populate selected options
for (var i=0; i<me.options.length; i++)
if (me.options[i].selected)
values += me.options[i].value + ',';
values = values.substring(0, values.length-1);
var selected=[values];
var del = document.getElementById('data').value;
for(var i=0; i<del.options.length; i++);
{
if(values[i] == del.options[i])
{
del.options[i].selected;
}
}
}
</script>
<select multiple="multiple" onchange="showState(this);">
<option value="1">Test1</option>
<option value="3">Test3</option>
<option value="4">Test4</option>
</select>
<select name="data" id="data" multiple="multiple">
<option value="1">Test1</option>
<option value="2">Test2</option>
<option value="3">Test3</option>
<option value="4">Test4</option>
</select>
I think you should make some correction in your code as below :
<script type="text/javascript">
function showState(me){
var values = ''; //populate selected options
for (var i=0; i<me.length; i++)
if (me.options[i].selected)
values += me.options[i].value + ',';
values = values.substring(0, values.length-1);
var selected=[values];
var del = document.getElementById('data');
for(var i=0; i<del.length; i++)
{
for(var j=0;j<values.length;j++)
{
if(values[j] == del.options[i].value)
{
del.options[i].selected = true;
}
}
}
}
</script>
for more details on Select and Option objects in javascript you may refer this link !
I think your problem is here var del = document.getElementById('data').value;. If you want to access the select options, you should use var del = document.getElementById('data');, without the .value. This way the variable del should have the .options array.

How to change Selected Index when I only have the name?

I'm integrating Postcode anywhere with my web project. I'm using a drop drop for the county/state field. Postcode anywhere returns the name of the County. Can I change the Selected Index when I only have the name? (I'm using a number for the value field which relates to a database field).
I tried the following:
var f = document.getElementById("state_dropdown");
f.options.[f.selectedIndex].text = response[0].County;
I've tried to include the drop down code html here but I can't get it to work properly for some reason.
But of course this just changes the text field for the item in the drop down that is already selected.
I can query the database and find out what ID I have assigned the county but I'd rather not if there is another way.
Loop over the options until you have a match:
for (var i = 0; i < f.options.length; i++) {
if (f.options[i].text == response[0].Country) {
f.options.selectedIndex = i;
break;
}
}
Demo.
I would make a function and loop over the labels:
See: http://jsfiddle.net/Y3kYH/
<select id="country" name="countryselect" size="1">
<option value="1230">A</option>
<option value="1010">B</option>
<option value="1213">C</option>
<option value="1013">D</option>
</select>​
JavaScript
function selectElementByName(id, name) {
f = document.getElementById(id);
for(i=0;i<f.options.length;i++){
if(f.options[i].label == name){
f.options.selectedIndex = i;
break;
}
}
}
selectElementByName("country","B");
Just a variation on other answers:
<script type="text/javascript">
function setValue(el, value) {
var sel = el.form.sel0;
var i = sel.options.length;
while (i--) {
sel.options[i].selected = sel.options[i].text == value;
}
}
</script>
<form>
<select name="sel0">
<option value="0" selected>China
<option value="1">Russia
</select>
<button type="button" onclick="setValue(this, 'Russia');">Set to Russia</button>
<input type="reset">
</form>

Categories

Resources