自定义属性jquery选择选项。

时间:2021-02-15 20:34:52

i have this select option html with custom attribute

我有一个带有自定义属性的select选项html。

<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

现在我要得到dealername的值

 $("#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

我不知道如何获得属性dealername的值

2 个解决方案

#1


4  

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

问题在于dealername属性位于所选选项上,而不是select本身。试试这个:

$("#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.

注意这里的find()和console.log()在alert()中用于调试。

#2


2  

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>

#1


4  

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

问题在于dealername属性位于所选选项上,而不是select本身。试试这个:

$("#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.

注意这里的find()和console.log()在alert()中用于调试。

#2


2  

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>