Awar Pulldozer
Awar Pulldozer

Reputation: 1101

custom value in custom attribute jquery select option

i have this select option html with custom attribute

<select id='voucher_dealer' name='voucher_dealer' class='form-control'><option value=''>اختر موزع</option>
        @foreach($dealers as $dealer)
            <option dealername='awad' value='{{$dealer->id}}'>{{$dealer->dealer_name}}</option>
        @endforeach
</select>

now i want to get the value of dealername i did this

 $("#voucher_dealer").change(function(){
    var dealer = $(this).val();
    var dealername = $(this).attr("dealername");
    alert(dealername);
});

i get undefined how i can get the value of the attribute dealername

Upvotes: 3

Views: 1931

Answers (2)

Rush.2707
Rush.2707

Reputation: 683

Your selector is wrong.

Try this:

$("#voucher_dealer").change(function(){
  var dealer = $(this).val();
  var dealername = $('#voucher_dealer option:selected').attr("dealername");
  alert(dealername);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='voucher_dealer' name='voucher_dealer' class='form-control'>
  <option dealername='dsf' value=''>اختر موزع</option>    
  <option selected dealername='awad' value='{{$dealer->id}}'>ajhbjkasdb</option>
</select>

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because the dealername attribute is on the selected option, not the select itself. Try this:

$("#voucher_dealer").change(function(){
  var dealer = $(this).val();
  var dealername = $(this).find('option:selected').attr("dealername");
  console.log(dealername);
});

Note the use of find() here, and also console.log() over alert() for debugging purposes.

Upvotes: 5

Related Questions