【问题标题】:display option value in div on change更改时在 div 中显示选项值
【发布时间】:2021-09-12 09:51:48
【问题描述】:

如何使用 jquery 在空 div 中显示选项的选定值?

$(document).ready(function() {
  let from_select = $('#from_select');
  let from_text = $('#from');

  //example#1
  from_select.on('change', function() {
    from_text.append($("option:selected").val());
  })

  //example#2
  from_select.on('change', function() {
    from_text.append($("#test option:selected").val());
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="from_select">
  <option id="test" value="gel" selected data-buy="1" data-sell="1">GEL</option>
  <option id="test" value="usd" data-buy="" data-sell="">USD</option>
  <option id="test" value="eur" data-buy="" data-sell="">EUR</option>
  <option id="test" value="rub" data-buy="" data-sell="">RUB</option>
</select>

<div id="from"></div>

example#1 中它可以工作,但是我无法删除在 #from div 中传递的最后一个值。 但在 example#2 中它不起作用,我不知道为什么但它不是 gettind id #test

【问题讨论】:

  • 第二个示例不起作用,因为您的选择器错误。 select 具有idfrom_select,您的jQuery 使用#tornike。投票结束是一个错字。另请注意,第一个示例应使用$(this).val()
  • 我修复了第二个示例,但它也不起作用。
  • 因为你把它改成了#test而不是#from_select...

标签: javascript html jquery dom


【解决方案1】:

示例#1

  1. 您可以从$(this).val() 中读取选定的值。
  2. 您应该使用.html 而不是.append。它将替换之前从form 添加的值

示例#2

第二个不起作用,因为您的标记中没有#tornike 元素的 id。这没有必要。因为您已经在 onchange 事件中,所以您将从事件中获得价值。所以id 目标是不必要的

$(document).ready(function() {

  let from_select = $('#from_select');
  let from_text = $('#from');

  //example#1
  from_select.on('change', function() {
    from_text.html($(this).val());
  })

   //not necessary 
  //example#2
 // from_select.on('change', function() {
   // from_text.append($("#tornike option:selected").val());
  //})

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="from_select">
  <option id="test" value="gel" selected data-buy="1" data-sell="1">GEL</option>
  <option id="test" value="usd" data-buy="" data-sell="">USD</option>
  <option id="test" value="eur" data-buy="" data-sell="">EUR</option>
  <option id="test" value="rub" data-buy="" data-sell="">RUB</option>
</select>



<div id="from">

</div>

【讨论】:

  • 不,我在#test 上更改了它,但它也不起作用。
  • @Tornike_14 秒不需要。因为您已经在 onchange 事件中,所以您将从事件中获得价值。所以id 目标是不必要的
【解决方案2】:

您可以使用以下任何选项

 $(this).val() 
 from_select.val()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多