1

I have the following select and using Jquery I manage to get the new value so I can process it further:

 $("select[name=time]").on('change',function(e){
    const target = event.target;
    console.log(target);
    console.log($(target).val());
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="time" class="container-full">
       <option value="12:00" data-payvalue=2300>12:30</option>
       <option value="13:00" data-payvalue=2301>13:00</option>
       <option value="14:00" data-payvalue=2101>14:00</option>
    </select>

But what I want is to also retrieve the data-payvalue of he selected options as well. Do you know how I can do it?

In order words I want to do:

     $("select[name=time]").on('change',function(e){
        const target = event.target;
        console.log(target);
        console.log($(target).val());
        const payvalue=''; //populate with selected option having data-payvalue
        console.log(payvalue)
     });

What I want to do is once I select in the example the value 13:00 to display:

  console.log(payvalue)

How I can do that?

2 Answers 2

2

you need to call the custom attribute like this:

const payvalue = $('option:selected').attr("data-payvalue"))
2
  • 1
    It works as long as value is unique inside the option. If there are 2 option nodes with same value attribute it may not work. Apr 28, 2023 at 14:13
  • understood, I edited it 😁, you didn't mention that Apr 28, 2023 at 14:17
1

One way to do this is:

 $("select[name=time]").on('change',function(e){
    const target = event.target;
    console.log(target);
    console.log($(target).val());

    //populate with selected option having data-payvalue
    const payvalue=$(target).find(":selected").attr('data-payvalue'); 
    console.log(payvalue)
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="time" class="container-full">
       <option value="12:00" data-payvalue=2300>12:30</option>
       <option value="13:00" data-payvalue=2301>13:00</option>
       <option value="14:00" data-payvalue=2101>14:00</option>
    </select>

Pay attention upon:

        //populate with selected option having data-payvalue
        const payvalue=$(target).find(":selected").attr('data-payvalue'); 
        console.log(payvalue)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.