0

I have created a number of select tags. Every tag is differed by their name. So when I do submit the form, I need to get the name of the select tag using jquery.

<select class="myclass" id="" name="AP">
<option value="">Select Val</option>
   <option value="50">50</option>
   <option value="60">60</option>
</select>

var getSelect = $('.compressor option:selected');
console.log(getSelect.name);

I didn't the same for the input field it is working. When I kept my name in options it is working fine. But I don't want to keep my name attr in options.

SethuNagaKarthik
  • 387
  • 1
  • 3
  • 17
  • You are not selecting the `select` element, but the `option` element. If you select the `select` element, it works like for an `input` element. – trincot Jan 20 '19 at 10:05
  • is it possible to find whether it is dropdown or input using element class? – SethuNagaKarthik Jan 20 '19 at 10:22
  • If you have a jQuery reference to an element, you can know what it is with `.prop("tagName")`. That will return `OPTION`, `SELECT`, or `INPUT`, ... See https://stackoverflow.com/questions/5347357/jquery-get-selected-element-tag-name – trincot Jan 20 '19 at 10:28

1 Answers1

1

If you want to get the attribute name of the select element, remove option:selected from the selector. You can use attr() to get specific attribute:

var getSelect = $('.myclass');
console.log(getSelect.attr('name'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="myclass" id="" name="AP">
<option value="">Select Val</option>
   <option value="50">50</option>
   <option value="60">60</option>
</select>

If you want option:selected as part of the selector then you have to target the parent() element:

$('#submit').click(function(){
  var getSelect = $('.myclass option:selected').parent();
  console.log(getSelect.attr('name'));
  return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="myclass" id="" name="AP">
<option value="">Select Val</option>
   <option value="50">50</option>
   <option value="60">60</option>
</select>

<button type="submit" id="submit">Submit</button>

Update: To get the element's name you can use the property tagName

//using index
console.log(getSelect[0].tagName);
//or: using prop()
console.log(getSelect.prop('tagName'));

var getSelect = $('.myclass');
getSelect.each(function(){
  console.log($(this).prop('tagName'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="myclass" id="" name="AP">
<option value="">Select Val</option>
   <option value="50">50</option>
   <option value="60">60</option>
</select>
<input class="myclass"/>
Mamun
  • 66,969
  • 9
  • 47
  • 59