I'm new to javascript and am trying to populate my textbox to dynamically change its value when I select the dropdownList. My code is able to compile and run successfully with the exception that nothing appears on the textbox.
I would appreciate any kind advice.
Thank you.
*Attached is my code
<body>
<select id="dropdownList" name="dropdownList" onchange="getSelectValue();">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</select>
<input type="text" id="price" value="" disabled> //I'm trying to change this value
<br>
<script>
function getSelectValue() {
var selectedValue = document.getElementById("dropdownList").value;
if(selectedValue.equals("Volvo")) {
document.getElementById("price").value = "4.50";
} else {
document.getElementById("price").value = "3.50";
}
}
</script>
</body>
Try this
selectedValue.equals
is not a function in javascript you use if(selectedValue == 'volvo')
instead of if(selectedValue.equals("Volvo"))
.
And also Value of select box is volvo
not Volvo
.
<script>
function getSelectValue() {
var selectedValue = document.getElementById("dropdownList").value;
if(selectedValue == 'volvo') {
document.getElementById("price").value = "4.50";
} else {
document.getElementById("price").value = "3.50";
}
}
</script>
Please check this.
<script>
function getSelectValue() {
var selectedValue = document.getElementById("dropdownList").value;
console.log(selectedValue);
if(selectedValue==="volvo") {
document.getElementById("price").value = "4.50";
} else {
document.getElementById("price").value = "3.50";
}
}
</script>
Use ===
when comparing, not .equals
.
Casing matters. If the option
value is 'volvo'
, don't test against 'Volvo'
.
Using inline event handlers is bad practice and results in poorly factored, hard-to-manage code. Seriously consider attaching your events with JavaScript, instead, eg: https://developer.mozilla.org/en/DOM/element.addEventListener
const select = document.querySelector('#dropdownList') select.addEventListener('change', getSelectValue); function getSelectValue() { var selectedValue = select.value; if (selectedValue === "volvo") { document.getElementById("price").value = "4.50"; } else { document.getElementById("price").value = "3.50"; } } getSelectValue();
<select id="dropdownList" name="dropdownList"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> </select> <input type="text" id="price" value="" disabled>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.