简体   繁体   English

如何同时从两个输入更新 2 个变量?

[英]How can I update a 2 variables from two inputs at the same time?

I can't get them to output both the selections at the same time.我无法让他们同时选择 output 。 Is this possible?这可能吗? One side is always undefined.一侧总是未定义的。 I have tried so many things, but when I console.log I just cannot get them to log at the same time.我尝试了很多东西,但是当我使用 console.log 时,我无法让它们同时登录。 I would like the default values to be "all", and then either side would update depending on what is clicked.我希望默认值是“全部”,然后任何一方都会根据点击的内容进行更新。

 function combo(a, b) { a = a.value b = b.value console.log(a, b) }
 <label for="food">Please select a food: </label> <select id="food" onchange="combo(this,'all')"> <option value="100">Select</option> <option value="all">All</option> <option value="cheese">cheese</option> <option value="pickle" pickle</option> </select> <label for="sort">Please sort: </label> <select id="sort" onchange="combo('all',this)"> <option value="100">Select</option> <option value="smell">smell</option> <option value="texture">texture</option> </select>

Consider getting the values explicitly instead of trying to go through a onchange attribute handler.考虑显式获取值,而不是尝试通过onchange属性处理程序获取 go。

 const foodSelect = document.getElementById("food"); const sortSelect = document.getElementById("sort"); function selectHandler() { const food = foodSelect.value; const sort = sortSelect.value; console.log(`Food: ${food} | Sort: ${sort}`); } foodSelect.addEventListener("change", selectHandler); sortSelect.addEventListener("change", selectHandler);
 <label for="food">Please select a food: </label> <select id="food"> <option value="100">Select</option> <option value="all">All</option> <option value="cheese">cheese</option> <option value="pickle" pickle</option> </select> <label for="sort">Please sort: </label> <select id="sort"> <option value="100">Select</option> <option value="smell">smell</option> <option value="texture">texture</option> </select>

Another way to do it, less lines.另一种方法是减少行数。

 function combo() { let food = document.getElementById("food"); let sort = document.getElementById("sort"); console.log(food.options[food.selectedIndex].text + ', ' + sort.options[sort.selectedIndex].text); }
 <label for="food">Please select a food: </label> <select id="food" onchange="combo()"> <option value="100">Select</option> <option value="all">All</option> <option value="cheese">cheese</option> <option value="pickle"> pickle</option> </select> <label for="sort">Please sort: </label> <select id="sort" onchange="combo()"> <option value="100">Select</option> <option value="smell">smell</option> <option value="texture">texture</option> </select>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM