9

I have a situation in which i want to convert a <select> tag into a <input type="text"> and <input type="text"> into <select> bu using some condition. So how can i know that this element a type text or type select using id attribute.

Blowsie
  • 40,239
  • 15
  • 88
  • 108

5 Answers5

12

And also a pure javascript solution:

function toggle(a){
    if(a.tagName === 'INPUT'){
        a.outerHTML = '<select id="toggle"></select>';
    }else{
        a.outerHTML = '<input type="text" id="toggle"/>'
    }
}

http://jsfiddle.net/M6qXZ/1/

2018 ES6

e => e.outerHTML = e.tagName === "INPUT" ? "<select id='toggle'></select>" : "<input id='toggle'/>"
php_nub_qq
  • 15,199
  • 21
  • 74
  • 144
8

By using

$("#inputID").attr("type");

If you alert above you will get the type of input element, then you can apply checks accordingly.

Ref here : http://api.jquery.com/attr/

UPDATE

check using

if(!$("#inputID").is("select")) {
    // the input field is not a select
}

got from a link while searching not tested though.

Sunil Verma
  • 2,490
  • 1
  • 14
  • 15
2

You can use .is() to test whether the elements is of type x like

Use :text selector to test for text input element

if($("#inputID").is(":text")){
    //to test for text type
}

Use element selector to test for select element

if($("#inputID").is("select")){
    //to test for select
}
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
2

Get the element type using jQuery:

var elementType = $("#myid").prop('tagName');

Get the input type attribute using jQuery:

var inputType = $("#myid").attr('type');

Blowsie
  • 40,239
  • 15
  • 88
  • 108
1

the condicion could be for example:

   if($('#whateverid').attr('type') == "text")
Sadako
  • 352
  • 3
  • 18