Anup Anup - 6 months ago 16
Javascript Question

How to get attribute value from options in select box

sI am stuck in one of unique functionality using select box. Html is like:

<select name="hello" id="hello" >
<option selected="selected" value="Please Select">Please Select</option>
<option data-att="one">abc</option>
<option data-att="one">sd</option>
<option data-att="one">wer</option>
<option data-att="two">uio</option>
<option data-att="two">abc</option>
<option data-att="two">sd</option>
<option data-att="three">wer</option>
<option data-att="three">tyu</option>




Now i want to make an array of that data-att values from this select box without selected, LIKE :

var arr = new Array();
arr=['one','two','three'];


it will run on window load state it will use for another dropdown dynamic values after window load. but i want data-att value once which from the same attribute.
Thanks in advance and give effective answer asap.

Answer

var arr=[];
$('#hello option').each(function(){
  if($.inArray($(this).attr('data-att'), arr) == -1) { //check if id value not exits than add it
    arr.push($(this).attr('data-att'))
    
    }


})
console.log(arr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="hello" id="hello">
  <option selected="selected" value="Please Select">Please Select</option>
  <option data-att="one">abc</option>
  <option data-att="one">sd</option>
  <option data-att="one">wer</option>
  <option data-att="two">uio</option>
  <option data-att="two">abc</option>
  <option data-att="two">sd</option>
  <option data-att="three">wer</option>
  <option data-att="three">tyu</option>
</select>

Use $.inArray() to check if value exist in array if not add on arr

will give you [undefined, "one", "two", "three"]

var arr = [];
$('#hello option').each(function() {
  if ($(this).attr('data-att')) {
    if ($.inArray($(this).attr('data-att'), arr) == -1) { //check if id value not exits than add it
      arr.push($(this).attr('data-att'))

    }
  }



})
console.log(arr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="hello" id="hello">
  <option selected="selected" value="Please Select">Please Select</option>
  <option data-att="one">abc</option>
  <option data-att="one">sd</option>
  <option data-att="one">wer</option>
  <option data-att="two">uio</option>
  <option data-att="two">abc</option>
  <option data-att="two">sd</option>
  <option data-att="three">wer</option>
  <option data-att="three">tyu</option>
</select>

You can add additional If statement to make sure only option with attr data-att will be counted

Comments