ajax - Javascript Button OnClick not working, method runs normally -
i trying create button in javascript, when clicked send ajax request php code.
i have setup 3 buttons same thing , working fine.
the bizarre thing if call method directly runs fine.
the code button:
<button id="toggle-button">toggle</button>
the javascript:
var togglebutton = document.getelementbyid('toggle-button'); ... function init() { ... togglebutton.onclick = handletoggleclick; ... } function handletoggleclick(event) { alert("sending request"); var admin_url = "http://localhost/wp-admin/admin-ajax.php"; var data = { action : 'toggle', } $.post(admin_url, data, function(resp) { alert(resp); }); }
i have called following in chrome developer tools console:
handletoggleclick(null); // request sent autoschedulebutton.onclick(); // request sent autoschedulebutton.onclick; //it prints out function autoschedulebutton; //it displays html of button.
as mentioned before there 3 other buttons practically same thing , work fine, can't see why isn't working.
hopefully obvious missed.
edit:
originally made error while anonymising code, code above correct in init method.
previous code: function init() { ... togglebutton.onclick() = handletoggleclick; ... }
in init
function have code togglebutton.onclick() = handletoggleclick;
. means assign result of onclick()
function handletoggleclick
.
you need assign onclick
, not call it. try instead togglebutton.onclick = handletoggleclick;
function init() { ... togglebutton.onclick = handletoggleclick; ... }
Comments
Post a Comment