1
<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-->.

2
  • Try console.log(x.length) and tell me results. Commented Oct 5, 2017 at 1:23
  • x.lenght returns = 13, exatc number of elements value I have on my select. Commented Oct 6, 2017 at 1:58

7 Answers 7

2

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Phani, thanks I checked all the answers and this works perfectly.
@bernlt Glad this helped you. Please upvote/check the answer that helped you.
1

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:

  1. Get the element "List"
  2. Get the children of "List"
  3. Create an array to hold elements that pass the filter
  4. Go through each element and add those with match the specified regex
  5. Return the elements that pass the filter

2 Comments

Aanand the *match(/--(\w+)--/), did not work, so I updated tostartsWith('----')) and it worked.
Oh, that's interesting, when I tried with your code, it worked. Thanks!
0

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

2 Comments

I try something like this, but I'm using firebug on firefox and console giving me undefined, I retry on chrome and worked.
Not sure why that should be the case but glad the other answer worked for you.
0

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/

Comments

0

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.

Comments

0

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

1 Comment

Hi CJ, this is an good approach, I didnt want to update my select list, but you have gave me alternative if was the case. Thanks for the tip.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.