Javascript Code Fix

Hello,

I had written code for List - Sub list items selection, but it showing error. Please look into the below code and let me know the issue

`<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>

<body>
<select id="slc1" name="slc1" onChange="populate('this.id', 'slc2')">
    <option value=""></option>
    <option value="Ford">Ford</option>
    <option value="Fiat">Fiat</option>
    <option value="Maruthi">Maruthi</option>
</select>

<select id="slc2" name="slc2"></select>

<script type="text/javascript">
    function populate(s1,s2){
        var s1 = document.getElementById(s1);
        var s2 = document.getElementById(s2);
        s2.innerHTML = "";
        if(s1.value == "Ford"){
            var optionArray = ["|", "Figo|Figo", "Fiesta|Fiesta"];    
        } else if(s1.value == "Fiat"){
            var optionArray = ["|", "Punto|Punto", "Linea|Linea"];    
        } else if(s1.value == "Tata"){
            var optionArray = ["|", "Indica|Indica", "Bolt|Bolt"];    
        } 
        
        for(var option in optionArray){
            var pair = optionArray[option].split("|");
            var newoption = document.createElement("option");
            newoption.value= pair[0];
            newoption.innerHTML = pair[1];
            s2.options.add(newoption);
        }
    }
    
        
</script>
</body>
</html>

Error:
s2 is null value
`

Hi,

The problem is here:

<select id="slc1" name="slc1" onChange="populate('this.id', 'slc2')">

this.id should not be wrapped with quotes:

<select id="slc1" name="slc1" onChange="populate(this.id, 'slc2')">

Otherwise, this line:

var s1 = document.getElementById(s1);

looks for <select id="this.id"> instead of <select id="slc1">

1 Like

Thanks alot megazoid.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.