-2
<div id='participant-detail'>
      <select class="form-control quantity" data-short-name="8"> 
      </select>

      <select class="form-control quantity" data-short-name="6"> 
      </select>
</div>

In these given example, how am I supposed to get the value of the first select tag with the data-short-name of '8'?

I tried

$('#participant-detail .quantity').find("select[data-short-name='8']").val()

the '#participant-detail' is the id of the container(div) of those 2 select tags.

How to find or navigate to the specific tag and get its value?

Giving it an id is not advisable because those select tags were created from some conditions.

MDB
  • 339
  • 4
  • 19

3 Answers3

0

$('#participant-detail .quantity').find("select[data-short-name='8']") does not return any element as there is no child of #participant-detail .quantity selector with matching criteria select[data-short-name='8'].

You can try following approach to get the desired result.

console.log($('#participant-detail').find("select[data-short-name='8']").val());
console.log($('#participant-detail select.quantity[data-short-name="8"]').val());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='participant-detail'>
      <select class="form-control quantity" data-short-name="8"> 
      <option value="a">A</option>
      </select>

      <select class="form-control quantity" data-short-name="6"> 
        <option value="b">B</option>
      </select>
</div>
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
0

use document.getElementById to select the div then querySelector to select the first child

let elem = document.getElementById('participant-detail').querySelector('select[data-short-name="8"]');
console.log(elem)
<div id='participant-detail'>
  <select class="form-control quantity" data-short-name="8">
  </select>

  <select class="form-control quantity" data-short-name="6">
  </select>
</div>
brk
  • 48,835
  • 10
  • 56
  • 78
0

find() tries to find the select element inside $('#participant-detail .quantity') which itself is the element. Thus find() fails to target the element.

You do not need to use find(), you can specify the attribute selector as part of the main selector:

var val = $('#participant-detail select.quantity[data-short-name=8]').val();
console.log(val);
var val2 = $('#participant-detail select.quantity[data-short-name=6]').val();
console.log(val2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='participant-detail'>
    <select class="form-control quantity" data-short-name="8"> 
      <option value="1111">1111</option>
      <option value="2222" selected>2222</option>
    </select>

    <select class="form-control quantity" data-short-name="6">
      <option value="1111" selected>1111</option>
      <option value="2222">2222</option>
    </select>
</div>
Mamun
  • 66,969
  • 9
  • 47
  • 59