Blawless
Blawless

Reputation: 1279

Get the input type by passing its ID

So I am trying to pass an input ID and get its corresponding type.

Eg.

<input id = "1" type = "date"/>
<input id = "2" type = "text"/>

So passing "1" would return date and passing "2" would return text.

I have looked at a few examples but none that work for my case:

How to use jquery selector having element type and ID

finding the type of an element using jQuery

What I have so far:

$("#my_select").on('click',function(){
        var fieldID = document.querySelector('.selected').id
        console.log("id is " + fieldID);
        var elementType = $(this).prev().prop('.selected');
        console.log("element type " + elementType)
});

Upvotes: 0

Views: 1029

Answers (5)

Osama
Osama

Reputation: 3040

$("#my_select").on('click',function(){
    var fields=$("#your-Form-Id").children();
    for(i=0;i<fields.length;i++){
        var type = field[i].type ||  field[i].tagName.toLowerCase();
        alert(type);
    }
});

Here it give you the type for input like radio text email or the tag name for other tags like textarea

Upvotes: -1

kind user
kind user

Reputation: 41893

Possible solution.

$("#my_select").on('change', function() {
  var fieldID = document.getElementById($(this).val());
  console.log(`id is ${fieldID.id} and type is ${fieldID.type}`);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="1" type="date" />
<input id="2" type="text" />
<select id='my_select'>
  <option value='1'>1</option>
  <option value='2'>2</option>
</select>

Upvotes: 1

Shiladitya
Shiladitya

Reputation: 12181

Here you go with the solution https://jsfiddle.net/bpq58x8m/

getType = function(id){
	console.log($('#' + id).attr('type'));
}

$('input').click(function(){
	getType($(this).attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id = "1" type = "date"/>
<input id = "2" type = "text"/>

Click on the input will give you back the type. I added an extra function just for your reference, you can ignore that and combine two into a single.

Upvotes: 0

Rajesh P
Rajesh P

Reputation: 363

You can do it this way.

$("#my_select").on('click',function(){
            var fieldID = document.querySelector('.selected').id
                console.log("id is " + fieldID);
            var elementType = $('#' + fieldID).prop('type');
            console.log("element type " + elementType)

        });

Upvotes: 1

DavidBittner
DavidBittner

Reputation: 535

var type = $("#id").attr("type");

Should do it.

Upvotes: 5

Related Questions