I am populating country dropdownlist from a database. I need to select a value from dropdown list and assign it to textbox by using Javascript.
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 I am getting error. Any solutions?
Your code is wrong, Look at where I've made the 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, is you selected your textbox and JS returned you a DOM element of that text box and you wanted to populate it by passing the DOM
of the textBox inside the getElementById()
function.
Here is where it broke:
document.getElementById(textboxId).value = strUser;
To use getElementById()
method, you pass a string value of the id of an element.
Hope this helps.