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.

4
  • 1
    select is not an input, so there is no select type. Input's type property and HTMLElement's nodeType property are 2 different things. Commented Dec 10, 2013 at 12:25
  • possible duplicate of Get element type with jQuery Commented Dec 10, 2013 at 12:26
  • 1
    Sorry, I meant tagName instead of nodeType. Commented Dec 10, 2013 at 12:33
  • And whats your condition ? Commented Dec 10, 2013 at 12:34

5 Answers 5

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'/>"
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

It shows undefied for select tag but it works fine for <input> tag
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
}

Comments

2

Get the element type using jQuery:

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

Get the input type attribute using jQuery:

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

Comments

1

the condicion could be for example:

   if($('#whateverid').attr('type') == "text")

Comments