首页 > 解决方案 > 我正在尝试从选择中获取年份,但在 jquery 中未定义

问题描述

当我选择任何一年时,我试图从选择选项中获得一年,然后我在警报中变得不确定,请帮助我,谢谢。

html视图

  <label for="opt11" class="option">Select Year</label>
          @foreach($years as $year)
          <input class="selectopt" name="test1" type="radio" id="opt{{$year->year}}">
          <label for="opt{{$year->year}}" data-year="{{$year->year}}" class="option text-box year"  data-maxlength=28>
          <p>{{$year->year}}</p>
          </label>

jQuery脚本

  $('.selectopt').on('change', function() {
    
      let year = $(this).data('year');
    
        alert(year); getting unfined
   
    });

标签: jquery

解决方案


this在您的更改处理程序中是单选按钮,而不是<label>元素。

试试这个

let year = $(`label[for="${this.id}"]`).data("year")

甚至这个

$(this).next("label.option").data("year")

当您可以使用单选按钮时,我看不出有任何理由使用数据属性value

<input
  class="selectopt" 
  name="test1" 
  type="radio" 
  id="opt{{ $year->year }}"
  value="{{ $year->year }}"
>
$(".selectopt").on("change", function(e) {
  const year = this.value
})

推荐阅读