jQuery - determine if input element is textbox or select list

后端 未结 3 1705
面向向阳花
面向向阳花 2020-12-24 11:08

How would I determine whether the element returned by an :input filter in jQuery is a textbox or select list?

I want to have a different behavior for each ( textbox

相关标签:
3条回答
  • 2020-12-24 12:00

    alternatively you can retrieve DOM properties with .prop

    here is sample code for select box

    if( ctrl.prop('type') == 'select-one' ) { // for single select }
    
    if( ctrl.prop('type') == 'select-multiple' ) { // for multi select }
    

    for textbox

      if( ctrl.prop('type') == 'text' ) { // for text box }
    
    0 讨论(0)
  • 2020-12-24 12:07

    You could do this:

    if( ctrl[0].nodeName.toLowerCase() === 'input' ) {
        // it was an input
    }
    

    or this, which is slower, but shorter and cleaner:

    if( ctrl.is('input') ) {
        // it was an input
    }
    

    If you want to be more specific, you can test the type:

    if( ctrl.is('input:text') ) {
        // it was an input
    }
    
    0 讨论(0)
  • 2020-12-24 12:07

    If you just want to check the type, you can use jQuery's .is() function,

    Like in my case I used below,

    if($("#id").is("select")) {
     alert('Select'); 
    else if($("#id").is("input")) {
     alert("input");
    }
    
    0 讨论(0)
提交回复
热议问题