I am trying to get year from selection but getting undefined in jquery

Viewed 37

I am trying to get a year from the selection option when I select any year and then I am getting undefined on alert please help me thanks.

html view

  <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 script

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

this in your change handler is the radio button, not the <label> element.

Try this instead

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

or even this

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

I can't see any reason to use a data-attribute when you could just use the radio button's value

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

I think you need to pass the data through the input tag, not through the label. Then it will look like the following code structure-

<input class="selectopt" name="test1" type="radio" id="opt{{$year->year}}" data-year="{{$year->year}}">

And, I hope it will work fine. thanks

Related