dpkt17803 2017-10-06 07:35
浏览 241
已采纳

Html select onchange将自定义属性值设置为其他输入值

onchange I want to get the select option custom attribute and set to the other input's value. Somehow I cannot get the course_price in the input onchange of the select. It only shows the first option value in the input only.

function selectFunction(e) {
  var value1 = $("#test").data('typeid'); //to get value
  document.getElementById("money").value = value1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" onchange="selectFunction(event)">
  <option id="test" data-typeid="<?php echo $row1['course_price']?>" 
  value="<?php echo $row1['course_id']?>"><?php echo $row1['course_name']?>
  </option>
</select>

<input type="number" value="" id="money" class="form-control">

</div>
  • 写回答

3条回答 默认 最新

  • dpafea04148 2017-10-06 07:41
    关注

    The issue is because the data-typeid attribute is on the selected option, not the select, so your jQuery code is looking at the wrong element. You can fix this by using find() and :selected to get the chosen option before reading the data attribute from it.

    Also note that on* attributes are very outdated. You should be using unobtrusive event handlers, something like this:

    $(function() {
      $('select.form-control').change(function() {
        var typeId = $(this).find('option:selected').data('typeid');
        $("#money").val(typeId);
      }).change();
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select class="form-control">
      <option data-typeid="1111" value="courseId1">courseName1</option>
      <option data-typeid="2222" value="courseId2">courseName2</option>
    </select>
    
    <input type="number" value="" id="money" class="form-control">

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度