How to get selected value from dropdown in asp.net using javascript?

I fill out a dropdown list of countries from the database. I need to select a value from a drop down list and assign it to a text box using javascript.

The code:

var textboxId = document.getElementById("txtCountry"); var dropdownListId =document.getElementById("ddlLocation"); var e = document.getElementById("ddlLocation"); var strUser = e.options[e.selectedIndex].value; document.getElementById(textboxId).value = strUser; document.getElementById(textboxId).focus(); 

By doing this, do I get errors .any decisions?

Relationship Ravi

+4
source share
3 answers

Your code is incorrect, look where I made changes to the same code:

 var textboxId = document.getElementById("txtCountry"); var e = document.getElementById("ddlLocation"); var strUser = e.options[e.selectedIndex].value; textboxId.value = strUser; textboxId.focus(); 

What you did, you selected your text field, and JS returned you the DOM element of this text field, and you wanted to fill it by passing the DOM text field inside the getElementById() function.

This is where it broke:

 document.getElementById(textboxId).value = strUser; 

To use the getElementById() method, you pass the string value of the element identifier.

Hope this helps.

+5
source

Try:

 document.getElementById('<%=txtCountry.ClientID%>').value 

or

 var textBox = document.getElementById('<%=txtCountry.ClientID%>'); textBox.value = strUser; 

This is because the identifiers of the html elements in the generated documents do not match the identifier that you assigned in your code. To get the identifier assigned to your control in html, you can use the ClientID property of your drop-down list.

Another problem is that you assign your yourhtml element to a variable and then use the getElementById function, which is not a valid call.

This is a change in ASP.NET 4 that is due to be released.

Hope this helps!

+2
source

These two lines:

 document.getElementById(textboxId).value = strUser; document.getElementById(textboxId).focus(); 

also erroneous. If your previous line really worked:

 var textboxId = document.getElementById("txtCountry"); 

what you called textboxId will actually be a text box control, so you will use getElementById using the control instead of a string identifier.

To keep track of what @anthares said; try the following:

 var textboxId = '<%=txtCountry.ClientID%>'; alert('My textbox id is: ' + textboxId); 

and make sure you get the correct identifier for the text field (remember that it will be launched by ASP.Net, at least make sure that you are not getting anything). Then, when you execute document.getElementById , you need to check the result before using:

 var myTextBox = document.getElementById(textboxId); if (myTextBox !== null) { ...now i can access the properties... } 
0
source

Source: https://habr.com/ru/post/1303548/


All Articles