selectlist and javascript in VF page code example

Example 1: selectlist and javascript in VF page

Hi everybody,
I am trying to populate selectlist options through onload javascript function, but some how this is not working. I have pasted the code below that iam working on, could any body please suggest any changes to make it working.
<apex:page >
<script> window.onload = list1;
function list1()
{
var list=document.getElementById('listchosen');
for(var i=0;i<10;i++)
list.add(new Option('xxx','xxx'));
}
</script>
<apex:outputPanel id="result"> <apex:form >
<b>Please select :</b>
<apex:selectList id="listchosen" multiselect="false" size="1"> </apex:selectList>
</apex:form>
</apex:outputPanel>
</apex:page>

Example 2: selectlist and javascript in VF page

<apex:selectList styleclass="Lista" value ="{!type1}" size="1">
    <apex:selectOptions value="{!Types}"/>
</apex:selectList>

var e = document.getElementsByClassName("Lista")[0];
var strUser = e.options[e.selectedIndex].value;

Example 3: selectlist and javascript in VF page

<apex:form >
<apex:outputLabel value="Type" />
<br/>
<apex:selectList id="Lista" value ="{!type1}" size="1">
    <apex:selectOptions value="{!Types}"/>
</apex:selectList>
<br/>
<div class="typesSection"></div>
<apex:outputLabel value="First/Last Name" />
<br/>
<apex:inputText value="{!searchText}" id="searchText"></apex:inputText>
<apex:commandButton value="change" onClick="change()"/>
</apex:form>

<script>
    function change(Lista){

        ss = document.getElementById(Lista).value;
        alert(ss);
    }
</script>

Example 4: selectlist and javascript in VF page

You have to modify your list1 method.

1. SFDC generated ids at run time for the apex tags. Please use correct Id of the apex:selectList.

2. You should add the Option to options list of the html element.

 

Please check the below code -

function list1()

{

var list=document.getElementById('j_id0:j_id2:listchosen');

for(var i=0;i<10;i++)

list.options.add(new Option(i,i));

}