How to Call a JS function using OnClick event
Solution 1:
You are attempting to attach an event listener function before the element is loaded. Place fun()
inside an onload
event listener function. Call f1()
within this function, as the onclick
attribute will be ignored.
function f1() {
alert("f1 called");
//form validation that recalls the page showing with supplied inputs.
}
window.onload = function() {
document.getElementById("Save").onclick = function fun() {
alert("hello");
f1();
//validation code to see State field is mandatory.
}
}
JSFiddle
Solution 2:
You could use addEventListener to add as many listeners as you want.
document.getElementById("Save").addEventListener('click',function ()
{
alert("hello");
//validation code to see State field is mandatory.
} );
Also add script
tag after the element to make sure Save
element is loaded at the time when script runs
Rather than moving script tag you could call it when dom is loaded. Then you should place your code inside the
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("Save").addEventListener('click',function ()
{
alert("hello");
//validation code to see State field is mandatory.
} );
});
example