3

I have a asp list box in the aspx page.Through the external java script I need to populate the list box manually. How to access the list box in the javascript? Does it requires jquery?I am attaching the java scripting to the aspx page dynamically. I am not using any include/import statements for java script. So I am unable to use "Document" object. How to create the new ListItem() in the java script code to populate it?

Is there any alternate way? Please help me out in this situation. Thanks in advance. Early response is appreciated.

1

3 Answers 3

1

You can do it in a variety of ways. You can get the listbox with:

var myListBox = document.getElementById(<'<%= myListBox.ClientId %>')

Or with Jquery:

$('#<%= myListBox.ClientId %>')

You can also set clientidmode to static which will use the same id as on the aspx page, so you could use:

$('#myListBox')
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for ur response. How to crate a list Item for the list box through java script?
What is the source of the items?
I am hard coding the values of now
1

you can access list box using the listbox id

 var Lbox   document.getElementById(<'<%= ListBox.ClientId %>');
 var option = document.createElement("option");
 option.value = '1';
 option.innerHTML = 'Option 1';
 Lbox.appendChild(option);

1 Comment

In the external Java script I am unable to use document as per my requirement
1
  1. I am attaching the java scripting to the aspx page dynamically. I am not using any include/import statements for java script. So I am unable to use "Document" object.

Binding script dynamically does not refrain you from using document. you can do it like this. For details

Page.RegisterClientScriptBlock("MyScript", _
   "<script language=javascript src='MyJavaScriptFile.js'>");

2 . Through the external java script I need to populate the list box manually. How to access the list box in the javascript

You can get data from server for dropdown using ajax. If you do not need data from server you can omit ajax part. For details follow this article

In HTML section

  <asp:DropDownList ID="ddlCities" runat="server"> </asp:DropDownList>

In Javascript section

 $.getJSON('LoadCities.ashx?StateID=' + StateID, function(cities) {
       $.each(cities, function() {                        
          $("#ddlCities").append($("<option> </option>").val(this['ID']).html(this['City']));

        });
  });
          ​

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.