[英]Change input value according which option is selected
我想根据选择的选项更改input field
的值。 我做了这个功能,但没有任何结果:
<script>
function changeFunc() {
var idpn = document.getElementById("idpn").value;
if(idpn.startsWith('v531')) {
if(document.getElementById("price_type_chosen").options.selectedIndex = 2) {
var ltvalue =document.getElementById("ltid").value=30;
} else if (document.getElementById("price_type_chosen").options.selectedIndex = 3) {
var ltvalue =document.getElementById("ltid").value=30;
}
}
alert('ok');
}
</script>
您能告诉我函数中的错误在哪里吗?
您不进行比较,您正在分配价值
if(document.getElementById("price_type_chosen").options.selectedIndex = 2)
您需要在比较中使用==
。
<script>
function changeFunc() {
var idpn = document.getElementById("idpn").value;
if(idpn.startsWith('v531')) {
if(document.getElementById("price_type_chosen").options.selectedIndex == 2) {
var ltvalue =document.getElementById("ltid").value=30;
} else if (document.getElementById("price_type_chosen").options.selectedIndex == 3) {
var ltvalue =document.getElementById("ltid").value=30;
}
}
alert('ok');
}
</script>
在if
语句中更改2个错误的比较( =
到==
)后,代码可以正常工作。
我还组合了if/else
语句,并将document.getElementById("price_type_chosen").options.selectedIndex
放入变量中,以使其更具可读性。
function changeFunc() { var idpn = document.getElementById("idpn").value; if (idpn.startsWith('v531')) { var selectedIndex = document.getElementById("price_type_chosen").options.selectedIndex; //both values are in 1 'if statement' with an or operator if (selectedIndex == 2 || selectedIndex == 3) { var ltvalue = document.getElementById("ltid").value = 30; } } alert('ok'); }
price_type_chosen: <select id="price_type_chosen"> <option>0</option> <option>1</option> <option>2</option> <option>3</option> </select> <br> <label>idpn:</label><input id="idpn" type="text" value="v531" /> <br> <label>ltid:</label><input id="ltid" type="text" value="" /> <br><br> <button onclick="changeFunc()">changeFunc</button>
选择选项2或3将#ltid
值#ltid
30
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.