Getting attr value set using option.attr('label', value['labelvalue']);

问题: I have a drop down which displays 'value2'. Its id is "select" like below. <select class="selectOneMenu_Medium_class searchField" id="selectBase"> <option valu...

问题:

I have a drop down which displays 'value2'. Its id is "select" like below.

<select class="selectOneMenu_Medium_class searchField" id="selectBase">
  <option value="Select">Select</option>
</select>
option.attr('value', value['value']);
option.text(value['value2']);
option.attr('label', value['value2']);

Whenever I try to retrieve the value using $('#selectBase').val() it gives me a value, but I want value2 also along with this. Can someone helps me in fetching value2?


回答1:

You can use selected psuedo selector and jquery text method

$('#selectBase').on('change', function() {
  console.log($(this).val());
  console.log($("#selectBase option:selected").text());
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="selectOneMenu_Medium_class searchField" id="selectBase">
  <option value="Select">Value 2</option>
  <option value="Select1">Value 3</option>
</select>


回答2:

JQuery Implementation

$('#selectBase').on('change', function() {

  let myValue = $(this).val(),
    myLabel = $("#selectBase option:selected").attr("label"),
    myText = $("#selectBase option:selected").text();

  console.log(
    "Value is", myValue, "n",
    "ValueOfAttribute is", myLabel, "n",
    "Text is", myText);
    
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id="selectBase">
  
  <option value="Select1" label="myLabel1">Value 1
  </option>
  
  <option value="Select2" label="myLabel2">Value 2
  </option>
  
</select>

Java-Script Implementation

function selectChanged(ref) {

  let index = ref.selectedIndex;
  let myValue = ref.value;
  let myLabel = ref.options[index].getAttribute("label");
  let myText = ref.options[index].text;

  console.log(
    "Value is", myValue, "n",
    "ValueOfAttribute is", myLabel, "n",
    "Text is", myText, "n", );
}
<select id="myselect" onChange="selectChanged(this)">
  <option value="Select1" label="valOfLabel1">Val 1</option>
  <option value="Select2" label="valOfLabel2">Val 2</option>
</select>

  • 发表于 2019-03-18 09:26
  • 阅读 ( 180 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除