Search code examples
javascripthtmlhtml-tablehtml-selectgetelementbyid

Get selected value of select inside table row not working as expected


Hello folks of Stackoverflow, i want to implement a filter for some sort of table in javascript. my text-search does work as expected, but i have some issues with getting an "select" element with js...

Some Code of it:

    function doSomething(){
    	var table, tr, td, i;
    	
    	table = document.getElementById("myTable");
    	tr = table.getElementsByTagName("tr");
    	for(i = 0; i < tr.length-1; i++){
    		td = tr[i].getElementsByTagName("td")[2];
    		
    		var e = td.getElementById("ABC");
    		
    		if(document.getElementById("cb1").checked &&  e.options[0].value == 0){
    			tr[i].style.display = "none";
    			
    		}else{
    			tr[i].style.display = "";
    		}
    	}
    }
<label>click me <INPUT type="checkbox" id="cb1" onclick="doSomething();"></label>
    
    <table id="myTable">
    
    <tr><td>Something</td><td>Some other Thing</td><td><select id="ABC"  name="sel1">
    <option value=0>Default</option>
    <option value=1>Not Default</option>
    </select></td></tr>
    
    </table>

https://jsfiddle.net/tnufmuLu/3/


Solution

  • You could update your code like this

    function doSomething(){
        var table, tr, td, i;
    
        table = document.getElementById("myTable");
        tr = table.getElementsByTagName("tr");
        console.log(tr);
        for(i = 0; i < tr.length; i++){
            td = tr[i].getElementsByTagName("td")[2];
            var e = td.getElementsByTagName("select")[0];
            alert('selected value is:' + e.options[e.selectedIndex].value);
            if(document.getElementById("cb1").checked &&  e.options[0].value == 0){
                tr[i].style.display = "none";
    
            }else{
                tr[i].style.display = "";
            }
        }
    }
    

    Here is updated demo If you want to get the selected value of a dropdown, you could use its selectedIndex attribute.

    By the way, we should not define multiple HTML element with same id (please check here)