skip to Main Content

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


  1. Chosen as BEST ANSWER

    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)
    

  2. you need to call the custom attribute like this:

    const payvalue = $('option:selected').attr("data-payvalue"))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search