Reputation: 2301
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
Reputation: 36609
window.onload
to handle load-event
on the window
document.querySelectorAll
to select list of the elements within the document that match the specified group of selectors.[].forEach.call
to iterate through selected elements.addEventListener
to register the specified listener on the element.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
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