0

I want to get element by class and data attribute and add disabled to this element

<button type="button" data-pid="23" class="add " tabindex="0">click me</button>

$(".add").on("click", function(e) {
    e.preventDefault();
    var pid = $(this).attr('data-pid');
    $('.add[data-pid="'+pid+'"]').attr("disabled", "disabled");
    
}); 

this code not work

thanks

1
  • 1
    Side note: e.preventDefault() prevents the default action of the element. There is no default action of a button of type="button". If the button were of type="submit", then e.preventDefault() would prevent the form from submitting. So, e.preventDefault() is not necessary in your example Commented Aug 9, 2024 at 20:05

1 Answer 1

-2

Here it is

$(document).ready(function(){

  $(".add").on("click", function(e) {
      e.preventDefault();
      var pid = $(this).attr('data-pid');
      $('.add[data-pid="'+pid+'"]').attr("disabled", "disabled");

  }); 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<button type="button" data-pid="23" class="add " tabindex="0">click me</button>

Sign up to request clarification or add additional context in comments.

4 Comments

Your answer could be improved if you explained what problem you found in the OP's code and explained how your code resolves that problem. "Here it is" is not very helpful in terms of describing the problem and solution. Also, what purpose does e.preventDefault() serve in your solution?
sure, but it was just a single-line change to include the function in a document.ready, I didn't think it was needed to explain, I am sure the requester would have figured it out by just looking at it, it is very obvious.
It could be helpful to FUTURE visitors who don't understand why wrapping the jQuery in document.ready fixed the problem. Stack Overflow is a Q&A repository -- and while you may have helped the OP, the main goal of answers on this site is to help FUTURE visitors.
if the solution is just to wrap in document.ready, this should just be closed as a duplicate of stackoverflow.com/questions/14028959/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.