Why isn't my function not working this button element? - javascript

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);
}
}

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.

Related

Javascript not working when 'alert; is removed

I have the following JS on my html and my obervations are:
1) When I removed the line for "alert" display it is not working as expected, the SAVE button is not trigerring when clicked.
2) Even with the "alert", it is not working in CHROME.
function save() {
alert('View Full List triggered!');
var $form = $('.fancybox-inner').find('[data-area="funder-detail"]');
$form.on('click', '[data-action="save-funder"]', function () {
var selected1 = $form.find('input[type="radio"]:checked').val();
if ($('input[type="radio"]:checked').length == 0) {
parent.$.fancybox.close();
} else {
document.getElementById("txtFunder").value = selected1;
parent.$.fancybox.close();
}
});
}
Perhaps the script runs too early, when the form is not yet in the DOM?
This can happen when the script tag is in the header.
Try moving the script tag in front of the closing tag.
I was able to make it work by using onclick="setTimeout(save, 1000)"

listening for click event for an href by classname

there is a page with some basic HTML that I cannot touch that looks like this:
<a class="continue-shopping" href="https://someURL">Continue shopping</a>
what I want to do is send the user to a different link when they click on the someURL text link. the user can come to a page containing this html from many other pages.
i have tried many hours but cannot get my js to recognize a click event for a class associated with hyperlinked text. i could really use some help here. this is the js code i wrote which does not work
window.onload = function() {
prepEventHandler();
}
function prepEventHandler () {
var myClass = document.getElementsByClassName("continue-shopping");
myClass[0].onclick=window.open(document.referrer,"_self");
/* which make my pages go haywire OR THIS -- which also does not work */
myClass[0].addEventListener("click", function() {
window.open(document.referrer,"_self");
}
)
}
It just keeps ignoring the second function, and I am sure I am doing some really basic that is wrong. Again, thanks for any help!
Apart from preventDefault() you could also use return false
window.onload = function () {
var myClass = document.querySelector(".continue-shopping")
.onclick = function () {
window.location.href = "http://elsewere.com";
return false;
}
}
this code should work but it no longer does and i do not know why any hint much appreciated - there seems to be some problem with myClass[0]
window.onload = function() {
var myClass = document.getElementsByClassName('continue-shopping');
myClass[0].addEventListener("click", function(e) {
e.preventDefault();
window.location.href = document.referrer;
});
}

Can't call function with button click (javascript)

I have a very strange issue. I have a button which currently prints a barcode label using the following code:
<button id="printButton">
PRINT BARCODE LABEL
</button>
This button then successfully calls:
printButton.onclick = function()
{ CODE }
The problem is that I wish to be able to print multiple barcode labels with a single button press. So, I changed the javascript function to:
function print()
{ CODE }
And added
printButton.onclick = function()
{
print();
}
With the idea being that I can ultimately call multiple print functions (print1() print2() etc) from the same button press. The problem is, when I rewrite the code as above, nothing happens, even though it seems to me that the exact same thing should happen as happened before? Any idea? I am happy to post the full code if anyone thinks that might help.
i would do:
$('#printButton').on('click',function (){
//call print method
});
var a1 = function (_func) { console.log('print'); if (_func != null) { _func()} }
printButton.onclick = function () {
a1(a1(a1(a1(null))));
}
<button id="printButton"> PRINT BARCODE LABEL</button>
function print(){alert('print func');}
printButton.onclick = print;
<button id="printButton">
PRINT BARCODE LABEL
</button>

JavaScript not allowing input before running

Im having issues with this javascript running prior to the user input, can someone help me fix this.
im just trying to make a little html page with a textbox and a button, that then clicked opens a new windows with a modified URL.
<input type="text" name="enter" class="enter" value="" id="lolz" />
<button type="button" id="the_button">Count</button>
document.getElementById('open').addEventListener('click', myFunction());
function myFunction() {
var button = document.getElementById("the_button");
var siteid = document.getElementById('lolz').value
button.onclick = count();
function count() {
window.location = "http://www.websiteimusing.com/" + siteid;
}
}
You can check the code out here
The Actually generate output from that website's code is this
Updated Code
document.getElementById('the_button').addEventListener('click', myFunction);
function myFunction() {
var button = document.getElementById("the_button");
var siteid = document.getElementById('lolz').value
button.onclick = count();
function count() {
window.location = "http://www.websiteimusing.com/" + siteid;
}
}
There's no element with id open in your code, so you're trying to add an event listener to null. The console will tell you the same:
Uncaught TypeError: Cannot call method 'addEventListener' of null
Also make sure to remove the parens from your event listener function, as the other posters have stated.
Change to:
document.getElementById('open').addEventListener('click', myFunction);
When you put () after a function name, it means to call the function at that time.
On this line
document.getElementById('open').addEventListener('click', myFunction());
you are calling the function by adding the ()
change that to:
document.getElementById('open').addEventListener('click', myFunction);

How do I temporarily disable a submit button for 3 seconds (onsubmit), then re-enable it?

I am fairly new to using javascript and here is what I have so far:
<!-- this is to disable the submit button and then re-enable it after 3 sec -->
<script type="text/javascript">
function enable()
{
var x = document.LAYOUTFORM.getElementById("create_button");
setTimeout(x.removeAttribute("disabled"), 3000);
}
</script>
And for the button I have this:
<INPUT TYPE="SUBMIT" VALUE=" Create PDF " class="FORMBUTTON" ID="create_button" onclick="javascript:this.disabled=true;javascript:enable();">
I have messed with this for hours and most of you will look at it and know what is wrong immediately. My form ID and name is LAYOUTFORM. Can anyone tell me what I am doing wrong here?
For bonus points I would also like the text of the button to temporarily change to "Creating..." while it is disabled, and then back to Create PDF again.
Simplest way:
<input ... onclick="lockoutSubmit(this)">
In your javascript:
function lockoutSubmit(button) {
var oldValue = button.value;
button.setAttribute('disabled', true);
button.value = '...processing...';
setTimeout(function(){
button.value = oldValue;
button.removeAttribute('disabled');
}, 3000)
}
Drop the LAYOUTFORM between document and getElementById.
Just an fyi, using firebug, chrome developer tools, or whatever the equivalent tools are for IE, you can monkey with your javascript on the console. Console.log will also output text and even objects (in CDT) which you can inspect. Very useful for exploring :)
Several problems. First, in the onclick attribute, you use javascript: which is for URLs. Stuff inside the onclick attribute is already evaluated as code. Second, the code in your setTimeout should either be string or a function name. You should do something more like this:
HTML:
<INPUT TYPE="SUBMIT" VALUE=" Create PDF " class="FORMBUTTON" ID="create_button" onclick="disable();">
JavaScript:
<script type="text/javascript">
function disable() {
x=document.getElementById("createbutton");
x.disabled=true;
x.value="Creating...";
setTimeout(enable, 3000);
}
function enable() {
x.disabled=false;
x.value=" Create PDF ";
}
</script>
You can access the button either by id that is globally unique
or by the name unique to the enclosing form
So you have to either
var x = document.getElementById("create_button");
or
var x = document.LAYOUTFORM.elements["create_button_name"];
(Assuming create_button_name is the name of the button:
<input type="submit" value=" Create PDF " id="create_button" name="create_button_name" class="formButton" onclick="javascript:this.disabled=true;javascript:enable();">
)
The first parameter of the setTimeout should be a function:
setTimeout(removeAttr, 3000);
function removeAttr() {
x.removeAttribute("disabled")
}
BTW, HTML need not be (and should not be, for readability etc) all uppercase.
There are two main problems with your JavaScript:
The .getElementById() method belongs to document, not to your form (or any other) element.
setTimeout() expects the first parameter to be a function (or a string, but there's almost never a situation when using a string is appropriate).
Try this:
function enable() {
var x = document.getElementById("create_button");
setTimeout(function() {
x.removeAttribute("disabled");
}, 3000);
}
You may like to combine the disabling and re-enabling into a single function:
<INPUT TYPE="SUBMIT" ... onclick="temporaryDisable(this);">
function temporaryDisable(el) {
el.disabled = true;
setTimeout(function() {
el.disabled = false;
}, 3000);
}
Note that you don't need to use .removeAttribute(), you can just set the .disabled property directly (like you were already doing when you disabled the element).
EDIT: Just saw the "bonus points" part of your question. You just need to set the .value property:
function temporaryDisable(el) {
var oldLabel = el.value;
el.value = "Creating...";
el.disabled = true;
setTimeout(function() {
el.disabled = false;
el.value = oldLabel;
}, 3000);
}
<script type="text/javascript">
function disDelay(obj){
obj.setAttribute('disabled','disabled');
setTimeout(function(){obj.removeAttribute('disabled')},30000)
}
</script>
<input type="submit" value="Submit" onclick="disDelay(this)">
http://www.webdeveloper.com/forum/showthread.php?164239-Temporarily-Disable-Submit-Button

Categories