Iswar
Iswar

Reputation: 2301

Javascript Equivalent of Jquery

I am having problem in converting jquery to javascript as my application requirement is not to use jquery and only in plain html and javascript. I know how to write the code in Jquery but unable to convert it in javascript. My code is as follows

 $(document).ready(function () {
  $('input[type="button"').click(function () {
     $(this).prop('disabled','disabled');
   });
 });

How to convert this code snippet to javascript.

Upvotes: 2

Views: 295

Answers (2)

Rayon
Rayon

Reputation: 36609

window.onload = function() {
  var elems = document.querySelectorAll('input[type="button"]');
  [].forEach.call(elems, function(el) {
    el.addEventListener('click', function() {
      this.disabled = true;
    });
  });
};

Edit: document.addEventListener('DOMContentLoaded', function () {}); could be used instead of window.onload but consider Browser compatibility as well. Another easier alternate would be to place your <script> as last-child of <body> without wrapping your script in any load handler.

Upvotes: 7

Hulke
Hulke

Reputation: 857

Use the DOMContentLoaded event as follow:

document.addEventListener("DOMContentLoaded", function(event) {
  console.log("DOM fully loaded and parsed");
  var btns = document.querySelectorAll("input[type=button]");
  for (let i = 0; i < btns.length; i++) {
    btns[i].addEventListener("click", function() {
      //Do stuff
      console.log("button" + i +  "clicked");
    });
  }
});

Upvotes: 4

Related Questions