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条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!