如何根据另一个字段的值设置输入字段的值?

How to set an input field value based on the value of another field?

字段 1 [attribute_size]
下拉式菜单 值:小、中、大、特大

字段 2 [计数]
输入文本 值:根据以下映射根据字段 1 输入设置值

小 = 1
中 = 2
大 = 3
特大 = 4

<select id="size" class="" name="attribute_size" data- 
attribute_name="attribute_size" data-show_option_none="yes">
<option value="">Choose an option</option>
<option value="Small" class="attached enabled">Small</option>
<option value="Medium" class="attached enabled">Medium</option>
<option value="Large" class="attached enabled">Large</option>
<option value="Extra Large" class="attached enabled">Extra 
Large</option></select>

<input id="count" name="count" value="5" class="thwepo-input-field ">

如何使用 JQuery 实现此目的?每次更改字段 1 时,我都需要更新字段 2 的值。

const input = document.getElementById('count');
document.getElementById('attribute_size').addEventListener('change', function(){
var sizsel = document.getElementById('attribute.size').value;
if (sizsel = 'Small') {
    input.value = '5';
} else if (sizsel = 'Medium') {
    input.value = '10';
} else {
    input.value = "15";
}
});

您可以在 select 上设置一个 change 事件处理程序来设置 inputvalue:

const $input = $("#size");
$input.change(function(){
  $("#count").val($(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="size" class="" name="attribute_size" data-attribute_name="attribute_size" data-show_option_none="yes">
  <option value="">Choose an option</option>
  <option value="1" class="attached enabled">Small</option>
  <option value="2" class="attached enabled">Medium</option>
  <option value="3" class="attached enabled">Large</option>
  <option value="4" class="attached enabled">Extra Large</option>
</select>

<input id="count" name="count" value="5" class="thwepo-input-field ">

但是,关于此的一些事情:

  • input 字段就是用户输入的元素。如果你只是 需要显示信息,你不应该使用 input 元素,而是你应该设置一个正常的 textContent 元素(如 spandiv)。

  • 如果您希望 optionvalue
    相同 option 的文本,不需要指定 value 属性 option 的全部 - - 文本将成为值。 但是,在您的情况下,您说过您希望数字是不同 option 的值,因此 value 属性应该反映这一点。

  • 你问的场景非常简单,JQuery是 可能矫枉过正来完成它。这是代码的内容 香草 JavaScript:

const input = document.getElementById("count");
document.getElementById("size").addEventListener("change", function(){
  input.value = this.value;
});
<select id="size" class="" name="attribute_size" data-attribute_name="attribute_size" data-show_option_none="yes">
  <option value="">Choose an option</option>
  <option value="1" class="attached enabled">Small</option>
  <option value="2" class="attached enabled">Medium</option>
  <option value="3" class="attached enabled">Large</option>
  <option value="4" class="attached enabled">Extra Large</option>
</select>

<input id="count" name="count" value="5" class="thwepo-input-field ">