'JQuery to prevent an element from getting focus?

How to prevent an input element (text, text area, select, radio button, checkbox) from getting focus? I basically want to make them disabled without changing disabled or readonly attribute but denying them focus. Is there a neat way to scan the DOM using certain search criteria and apply that to the search result? Say I want to find all input that are not tagged with a certain css class and make them un-selectable!



Solution 1:[1]

Give the elements that should be allowed focus the focus class. Then use a focus event handler that unfocuses the element.

$(document).on("focus", ":input:not(.focus)", function() {
  $(this).blur();
  console.log("Focus blocked");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox"> No focus<br>
<input type="checkbox" class="focus"> Focus

This uses event delegation so you can add and remove the focus class dynamically.

Solution 2:[2]

I am not sure if I got what you mean but can you please run this:

$('#disabler').change(function() {

  resetFields();
  
  var this_value = $(this).val();
  
  if(this_value != 'none'){
    $('.'+this_value).attr('disabled', true);
  }
  
  
});

$('.disabler').click(function(){

  resetFields();
  
  var this_value = $(this).attr('id');
  
  $('.'+this_value).attr('disabled', true);

});

$('#reset').click(function(){

  resetFields();

});

function resetFields()
{
  $('.first, .second').removeAttr('disabled');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="first" value="A"><br/>
<select class="first"><option value="1">A</option></select><br/>
<textarea class="first" col="2" row="10">A</textarea><br/>

<br/><br/>

<input class="second" value="B"><br/>
<select class="second"><option value="1">B</option></select><br/>
<textarea class="second" col="2" row="10">B</textarea><br/>

<br/><br/>

<select id="disabler">
  <option value="none">-select-</option>
  <option value="first">Disable first</option>
  <option value="second">Disable second</option>
</select><br/>

<button id="first" class="disabler">Disable first only</button><br/>
<button id="second" class="disabler">Disable second only</button><br/>
<button id="reset">Reset</button>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 kapitan