Can't call function with button click (javascript) - 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>

Related

Clicking 'cancel' in confirm() method has the same result as clicking 'ok'

I am a beginner implementing a confirm method in my HTML code - when the user clicks on "x", they will be redirected to the home page. Otherwise, nothing happens.
My problem is that in confirm(), both "ok" and "cancel" options redirect to home page and I cannot figure out why.
I saw that many people have a similar problem, checked many forums and noticed that writing onclick="return confirmCancel() rather than onclick="confirmCancel()" helped in most of the cases but it did not solve the problem for me.
HTML:
<a onclick="return confirmCancel()"><img src="assets/cancel.svg"></a>
JS:
const confirmCancel = () => {
confirm("All your progress will be lost. Are you sure you want to leave?");
if (confirmCancel) {
window.location.assign("index.html");
} else {
return false;
}
}
You need to test the return value of confirm (rather than the truthiness of the confirmCancel function).
const confirmCancel = () => {
if (confirm("All your progress will be lost. Are you sure you want to leave?");) {
window.location.assign("index.html");
} else {
return false;
}
}
Try something like this.
<a onclick="pleaseConfirm"><img src="assets/cancel.svg"></a>
const pleaseConfirm = () => {
if (confirm("All your progress will be lost. Are you sure you want to leave?")) {
window.location.assign("index.html");
}
}
You're mostly there .. You need to check if confirm() is true .. Change:
confirm("All your progress will be lost. Are you sure you want to leave?");
if (confirmCancel)
To
var test_confirm = confirm("All your progress will be lost. Are you sure you want to leave?");
if (test_confirm === true)
Shorthand can be
if (confirm("All ... ... "){
You can do the functionality inside JavaScript instead of calling out JavaScript function in your HTML tag
<a id="btn-exit"><img src="assets/cancel.svg"></a>
var btnExit = document.querySelector('#btn-exit')
btnExit.addEventListener('click', () => {
if (confirm("are you sure?")) {
window.location.assign("index.html");
}
})

unable to get the value of button inside update panel

Team,
When I click on the first add template button then the download value disappear. .
window.onload = function() {
ddnameChange();
};
function ddnameChange() {
var e = document.getElementById("<%=ddltemplate.ClientID %>");
var ddnamevalue = e.options[e.selectedIndex].value;
if(ddnamevalue==2)
{
<%=btndownload.ClientID %>.value="Download RBH Template";
}
else if(ddnamevalue==3)
{
<%=btndownload.ClientID %>.value="Download VISTA Template";
}
else
{
<%=btndownload.ClientID %>.value="Download OD Template";
}
}
I am not able to get the second button value when i click on edit as well as all template button.I know it should be something reason like update panel that why the function is not calling I don't know how to solve it.
You have to add this in the method that handles the Async PostBack.
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "ddnameChange", "ddnameChange();", true);
When the Async PostBack occurs, everyting inside the UpdatePanel is rebuild and anything that has been altered by jQuery will be lost.

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

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.

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

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

Categories