Home > Blockchain >  JQuery to prevent an element from getting focus?
JQuery to prevent an element from getting focus?

Time:05-13

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!

CodePudding user response:

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" > Focus

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

CodePudding user response:

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  value="A"><br/>
<select ><option value="1">A</option></select><br/>
<textarea  col="2" row="10">A</textarea><br/>

<br/><br/>

<input  value="B"><br/>
<select ><option value="1">B</option></select><br/>
<textarea  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" >Disable first only</button><br/>
<button id="second" >Disable second only</button><br/>
<button id="reset">Reset</button>

  • Related