steve steve - 1 month ago 15
jQuery Question

Remove Readonly attr from SELECT

I have a click event that is triggered when a user clicks on a

select
element that has a
readonly
state. This works fine.

The problem I have is that when the
readonly
state is removed from the
select
element, the click event is still present.

Here is a DEMO.

You will notice that when you click the
select
element, the top function still runs even though the
select
is no longer
readonly


$('select[readonly]').on("click", function(e) {
e.preventDefault();
alert('This is readonly!');
});

$('button').on("click", function(e) {
e.preventDefault();
$('#div form select').attr("readonly", false);
alert('Readonly Attr Removed!');
});


Is there a way around this issue? I know I could accomplish this with some way of adding/removing a class - but i'd rather not have that approach.

Answer

You've got two problems.

First

select[readonly] will target a select that has the attribute readonly, also when it is false. To fix that, use removeAttr('readonly').

Second

The select already got the click event binded on it. So instead, bind the function on the form, with a filter.

All together:

$('form').on("click", 'select[readonly]', function(e) {
  e.preventDefault();
  alert('This is readonly!');
});

$('button').on("click", function(e) {
  e.preventDefault();
  $('#div form select').removeAttr("readonly");

  alert('Readonly Attr Removed!');
});
select[readonly] {
  background-color: red; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div">
  <form>
    <div class="form-group">
      <select readonly>
      <option>Select an option</option>
      <option>option 2</option>
      <option>option 3</option>
      </select>
    </div>
  </form>
</div>
<br /><br />
<button>
Remove Disabled Attr
</button>

Or the updated Fiddle

Comments