theplau
theplau

Reputation: 980

on focus only for input type text or tel, not radio or checkboxes

I am using this code to auto-scroll to the selected input type:

$( document ).on( "focus", "input", function() {
            if(document.activeElement.tagName=="INPUT"){
                     window.setTimeout(function(){
                        document.activeElement.scrollIntoView();
                     },0);
                  }
            return false;
});

The problem is, I want to exclude radio buttons and checkboxes ..and only use it for input type tel or text. How do I achieve that?

Upvotes: 0

Views: 390

Answers (1)

Dekel
Dekel

Reputation: 62636

You can select only the relevant inputs, based on their type, instead of select all of the input tags:

$( document ).on( "focus", "input[type='tel'],input[type='text']", function() {
  console.log('relevant element focused');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="radio" value="1" />
<input type="text" value="this is some text" />
<input type="tel" value="123456789" />
<input type="checkbox" value="123456789" />

Another option is to check the type of the focused element, and break the running of the function in case of a selected types:

$( document ).on( "focus", "input", function() {
  if ($(this).attr('type') == 'radio' || $(this).attr('type') == 'checkbox') {
    return;
  }
  console.log('relevant element focused');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="radio" value="1" />
<input type="text" value="this is some text" />
<input type="tel" value="123456789" />
<input type="checkbox" value="123456789" />

Upvotes: 1

Related Questions