Reputation: 993
Nothing seems to be working on my button element. Here I have more than one function to test if it gives the alert window-- they don't work but it seems like its correctly written. I will provide 2 function codes which either don't work and the html button element being targeted to help inspect the code. I am 1 month into javascript so I apologize in advance if the mistake in here turns out to be a silly mistake.
HTML button element:
<form input='text' action="" method="post" name="entry" class="journalentry" id='form'>
<textarea name='entrybody' rows='12' cols='90' placeholder="Anything you want to write about the day you are thinking of." class="journalentry"></textarea
<button type='submit' onclick= "test()" id='submitid' class='submitbutton'>Submit</button>
</form>
function #1 (creating the element from javascript and adding an event listener. this one doesnt use the html form but function #2 does):
var submitelement = document.createElement('BUTTON');
var submittextnode = document.createTextNode("SUBMIT ME");
submitelement.appendChild(submittextnode);
document.body.appendChild(submitelement);
var submitattr = document.createAttribute("id");
submitAttr.value = "submitbutton";
submitelement.setAttributeNode("submitAttr");
submitelement.addEventListener('click', function() {
alert('88888');
})
function #2 (commented out function #1 and wrote this code out. still doesn't work) :
document.getElementById("submitbutton").addEventListener("click", test();
function test () {
var url = 'http://news.google.com';
var method = "GET";
var httpObj = new XMLHttpRequest();
httpObj.open(method, url, 'true');
httpObj.addEventListener("readystatechange", processRequest, false);
}
function processRequest (e) {
if (httpObj.readyState == 4 && httpObj.status == 200)) {
// time to partay!!!
var response = httpObj.responseText;
alert(response);
}
}
Upvotes: 0
Views: 339
Reputation: 469
Function is not triggering that means you've made some blunders in your coding (syntax error).
Try Correcting Following Issues:-
1.Replace this line document.getElementById("submitbutton").addEventListener("click", test();
with this one document.getElementById("submitbutton").addEventListener("click", test());
2. Shift this line document.getElementById("submitbutton").addEventListener("click", test())
;
before closing your <script> tag
(at the end).
How to debug javascript program?
You can easily debug it by going right clicking on main window screen-> a drop down will appear select inspect element option a window will appear -> click console on tabs. Here you can see your javascript errors red highlighted.
Upvotes: 2