Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.


1 Answers

You need just to use event delegation .on() instead so it will take in consideration the DOM change made by the button click :

$('body').on("click",'select[readonly]', function(e) {

Hopet his helps.

$('body').on("click",'select[readonly]', 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!');
});
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="true">
        <option>Select an option</option>
        <option>option 2</option>
        <option>option 3</option>
      </select>
    </div>
  </form>
</div>
<br /><br />
<button>
  Remove Disabled Attr
</button>
like image 62
Zakaria Acharki Avatar answered Mar 26 '26 05:03

Zakaria Acharki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!