button click event fires on page load [duplicate] - javascript

This question already has answers here:
What is the difference between a function call and function reference?
(6 answers)
Closed 3 years ago.
I have a js and htlm code in jfiddle.
I have created the button onclick event on the object method and on the page load it firing the event.
Is this some problem with my code.
var user = {
data: [
{name: 'T. Woods', age: 37},
{name: 'P. Mickelson', age: 43}
],
clickHandler: function (event) {
console.log(this);
var randomNum = ((Math.random() * 2 | 0) + 1) - 1; // Random number between 0 and 1
$('input').val(this.data[randomNum].name + ' ' + this.data[randomNum].age);
}
};
console.log(user);
$('button').click(user.clickHandler(this));
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<h1>Homepage Headline</h1>
<div id="div1">
<p>
<button>Get Random Person</button><br>
<input type="text">
</p>
</div>
<script type="text/javascript" src="oops.js"></script>
</body>
</html>

Your click event listener needs to be a function otherwise it will trigger .click() on the button instead of creating a listener
See the documentation for .click()
$("button").click(function () {
user.clickHandler(this)
});
Test it with your code here -
var user = {
data :[
{name: "T. Woods", age:37},
{name: "P. Mickelson", age:43}
],
clickHandler:function (event) {
console.log(this);
var randomNum = ((Math.random () * 2 | 0) + 1) - 1; // random number between 0 and 1
//console.log(this.data[randomNum].name + " " + this.data[randomNum].age);
// This line is adding a random person from the data array to the text field
$ ("input").val (this.data[randomNum].name + " " + this.data[randomNum].age);
}
};
console.log(user);
$("button").click(function() {
user.clickHandler(this)
});
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<h1>Homepage Headline</h1>
<div id="div1">
<p>
<button>Get Random Person</button><br>
<input type="text">
</p>
</div>
<script type="text/javascript" src="oops.js"></script>
</body>
</html>

The issue is because you invoke the user.clickhandler() function when the page loads and set its response as the click handler for the element.
You instead want to provide the reference to the function to the event handler. You will also need to bind() the scope of user to the reference, as that's what clickhandler() expects to run under. Try this:
$("button").click(user.clickHandler.bind(user));
Working example:
var user = {
data: [{
name: "T. Woods",
age: 37
}, {
name: "P. Mickelson",
age: 43
}],
clickHandler: function(event) {
console.log(this);
var randomNum = ((Math.random() * 2 | 0) + 1) - 1;
$("input").val(this.data[randomNum].name + " " + this.data[randomNum].age);
}
};
$("button").click(user.clickHandler.bind(user));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<h1>Homepage Headline</h1>
<div id="div1">
<p>
<button>Get Random Person</button><br>
<input type="text">
</p>
</div>

You need to attach the handler, not call it, and then bind the this object accordingly:
user.clickHandler.bind(user)

This is not a problem, you call
$("button").click(user.clickHandler(this));
at the loading, then it call the click event
Replace it by
$("button").bind("click", user.clickHandler(this));

Related

Javascript: I'd like to have my code show a photo if Points = Ten or More. How would I go about it?

Here is my Html Full File:
Index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Evolution Idle Game</title>
<link rel="stylesheet" href="idlescreen.css">
</head>
<body>
<p id="EvolPoints" class="evol-points">0 EvolutionPoints</p>
<button onclick="Upgrade()">Click to Upgrade</button>
<button onclick="BuyPointsPerClick()" id="perClickUpgrade" >Click to Start Automation</button>
<script src="main.js" charset="utf-8" type="text/javascript"></script>
</body>
</html>
Here is my full Javascript File:
Main.js
var gameData = {
Points: 0,
PointsPerClick: 1,
PointsPerClickCost: 10
}
const perClickUpgrade = document.getElementById("perClickUpgrade");
perClickUpgrade.addEventListener("click", function handleClick() {
perClickUpgrade.textContent = "Upgrade Evolution Level (Currently Level " + gameData.PointsPerClick + ") Cost: " + gameData.PointsPerClickCost + " Points";
});
function Upgrade() {
gameData.Points += gameData.PointsPerClick
document.getElementById("EvolPoints").innerHTML = gameData.Points + " Evolution Points"
}
function BuyPointsPerClick() {
if (gameData.Points >= gameData.PointsPerClickCost) {
gameData.Points-= gameData.PointsPerClickCost
gameData.PointsPerClick += 1
gameData.PointsPerClickCost *= 2
document.getElementById("EvolPoints").innerHTML = gameData.Points + " Evolution Points"
document.getElementById("perClickUpgrade").innerHTML = "Upgrade Evol Level (Currently Level " + gameData.PointsPerClick + ") Cost: " + gameData.PointsPerClickCost + " Points"
}
var mainGameLoop = window.setInterval(function() {
Upgrade()
}, 1000)
I have tried setting Points >= 10 and using various functions, but the functions do not run when the points get to ten or above. I appreciate any help! Re-posted to provide full code and hopefully a better explanation.
One example function that I have done as a test and added on is (which did not activate during program run):
function LevelTen() {
if (gameData.Points >= 10 ) {
alert("This is an alert message box."); // display string message
}
I've also added the variable LevelTen which equals ten (to avoid setting the comparison to an integer incase that was the problem). This is the alternative function, which also did not work.
function LevelTen() {
if (gameData.LevelTen <= gameData.PointsPerClick) {
alert("This is an alert message box."); // display string message
}
}
Thank you again!

How to restrict dynamic input to one digit only and locked for key press except spin buttons using pure Javascript?

I have created a dynamic input and its should accept numbers between 0 to 5 only using spinner (arrow buttons) and should restrict manual input from key board. I have tried [this][1] but its not working in my code. I have two java script files data.js contains object to be read and other file contains a function which read objects and display them dynamically Please help me knowing where I am doing mistake? Thank you
//data.js
var catalogArray = [
{
code: 100,
name: "T Shirt c100",
desc: "Lorem ipsum, or lipsum as it is sometimes known as",
price: 150,
image: "./images/img100.jpg"
},
{
code:101 ,
name: "T Shirt c101",
desc: "Lorem ipsum, or lipsum as it is sometimes known as",
price: 250,
image: "./images/img101.jpg"
}
];
//function.js
function chargerArticles() {
var articles = document.getElementById("content");
var catalog=catalogArray;
for (var i =0; i < catalog.length; i++) {
//Command Input Area
var zoneCmd=document.createElement("div");
zoneCmd.setAttribute("class", "border");
var inputCmd=document.createElement("Input");
inputCmd.setAttribute("class", "qty");
//inputcmd all properties
inputCmd.type="number";
// inputcmd.maxLenght="1";
// inputcmd.onKeydown=false;
inputCmd.value=0;
inputCmd.min=0;
inputCmd.max=5;
zoneCmd.appendChild(inputCmd); //child 1
//zoneCmd child of article element
article.appendChild(zoneCmd);
//finally article as a child of articles
articles.appendChild(article);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Page Title</title>
<link rel="stylesheet" type="text/css" href="css/mystyle.css">
<script src="js/data.js"></script>
<script src="js/codeboutique.js"></script>
</head>
<body onload="chargerArticles()">
<!-- <div class="border"><input class="qty" id="0-qte" type="number" min="0" max="5"
"><button class="cartBtn hvr-underline-btn" id="0-cmd"
"> ADD TO CART</button></div> -->
<div class="mainDivClass">
<section id="content">
</section>
</div>
</body>
</html>
It is unclear what type of thing a "spin button" is, so I can't address that part of your question.
But another of your requirements is an input that does not respond to the keyboard.
This can be accomplished easily.
In order to prevent keyboard events from affecting an input, simply write a listener function that responds to 'keydown' events.
let input = document.createElement('input');
document.body.appendChild(input);
input.addEventListener('keydown', e => {
// console.log('keydown e.key:', e.key);
// prevent default input response
e.preventDefault();
// take action on up or down arrow key
if (e.key === "ArrowUp") {
input.value = 'Up Arrow';
} else if (e.key === 'ArrowDown') {
input.value = 'Down Arrow';
} else {
console.log('key blocked: ', e.key);
}
});

changing the value of a variable when a radio button is clicked [duplicate]

This question already has answers here:
How to use radio on change event?
(11 answers)
Closed 7 years ago.
I know this is probably extremely simple to do but i cant't figure it out.All i need is for the value of the variable "price" to change when the radio button is click and for it to be displayed on the page.Thanks for the help.
This is placed in the head
<script>
var price = 500;
if (document.getElementById('wifi').checked) {
price = price + 200;
}
</script>
This is placed in the body of the html page
<input type="radio" name="wifi_price" id="wifi" value="200">Wifi Price</input>
<script>document.write(price);</script>
You should store your price variable in an object so that it can be easily accessed and updated.
<script>
window.onload = function(){
var obj = {
price: 500
}
var wifi = document.getElementById("wifi");
wifi.addEventListener('click',function(){
obj.price += parseFloat(wifi.value)
// document.writeln(obj.price)
})
}
</script>
<!DOCTYPE html>
<html>
<head>
<title>Checkbox Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<input type="radio" name="wifi_price" id="wifi" value="200">Wifi Price</input>
<p id="priceP"></p>
<script>
var priceP = document.getElementById('priceP');
priceP.innerHTML = "$100";
var wifi = document.getElementById('wifi');
wifi.addEventListener('click', function() {
var price = priceP.innerHTML.slice(1, priceP.innerHTML.length);
price = (price * 1) + 100;
priceP.innerHTML = "$" + price;
});
</script>
</body>
</html>

QUnit tests failing intermittently

Below is my javascript file that shows the sum of two numbers.
var getSum = function (arg1, arg2) {
var intArg1 = parseInt(arg1);
var intArg2 = parseInt(arg2);
return intArg1 + intArg2;
};
var getSumText = function (arg1, arg2) {
var sum = getSum(arg1, arg2);
return 'The sum of ' + arg1 + ' and ' + arg2 + ' is ' + sum + '.';
};
$(document).ready(function () {
$("#button1").click(function (e) {
console.log('button clicked');
var sumText = getSumText($("#arg1").val(), $("#arg2").val());
$("#output1").text(sumText);
e.stopPropagation();
});
});
Here's my QUnit.html file.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Test Suite</title>
<link href="Content/qunit-1.12.0.css" rel="stylesheet" />
<script src="Scripts/jquery-2.0.0.min.js"></script>
<script src="Scripts/qunit-1.12.0.js"></script>
<script src="Scripts/main.js" data-cover></script>
<script src="Scripts/mainTests.js"></script>
<script src="Scripts/blanket.min.js"></script>
</head>
<body>
<h1 id="qunit-header">Test Suite</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
<div id="qunit-fixture">
<input type="text" id="arg1" />
<input type="text" id="arg2" /> <br />
<div id="output1"> </div>
<input type="button" id="button1" value="Show sum" />
</div>
<script type="text/javascript">function blanket_toggleSource(e) {
var t = document.getElementById(e);
t.style.display === "block" ? t.style.display = "none" : t.style.display = "block";
}</script>
</body>
</html>
And here's my js tests file.
module('DOM');
test('should add correctly', 1, function() {
$('#arg1').val('2');
$('#arg2').val('5');
console.log($('#arg1').val());
console.log($('#arg2').val());
$('#button1').trigger('click');
var output = $('#output1').text();
equal(output, 'The sum of 2 and 5 is 7.', 'sum text is correct');
});
module('Sum');
test('should add correctly', 1, function() {
var sum = getSum('2', '1');
deepEqual(sum, 3, 'sum is correct');
});
If I move the 'Sum' module above the 'DOM' one, the test in the DOM module fail intermittently. What am I missing?
Thanks,
Arun
You need to separate the library code, that you can test, from the initialization code, that you don't really need to test in this case. Move the code inside the click handler into another named function and called that from a separate script tag or file. That way you can test all three functions from your tests. Currently you end up with document-ready executing code at a some point in time, while your tests run at another. That causes the seemingly random behaviour you're seeing.

Javascript opener window

I have function that opens up a window, and the values from the newly opened window are listed in the opener window.
The 2nd window - has this function:
function AddOtherRefDoc(name, number) {
var remove = "<a href='javascript:void(0);' onclick='removeRefDoctor(this)'>Remove</a>";
var html = "<li><b> Referral Doctor: </b>"+name+"<b>, Referral No: </b>"+number+ " " +remove+" <input type='text' name='ref_docs' value='"+name+"'></input><input type='text' name='ref_nos' value='"+number+"'></input></li>";
opener.jQuery("#r_docs").append(jQuery(html));
}
The function that calls the one above is:
function addRefDoc(){
var count = 0;
var ref_docarray ;
var ref_noarray ;
<%for(int i1=0; i1<vec.size(); i1++) {
prop = (Properties) vec.get(i1);
String ref_no = prop.getProperty("referral_no","");
String ref_name = (prop.getProperty("last_name", "")+ ","+ prop.getProperty("first_name", ""));
%>
if(document.getElementById("refcheckbox_<%=ref_no%>").checked) {
count++;
if ((ref_doctor!=null)&&(ref_doctor!="")&&(ref_docno!=null)&&(ref_docno!="")) {
ref_docarray = ref_doctor.split(";");
ref_noarray = ref_docno.split(";");
if ((containsElem(ref_docarray,"<%=ref_name%>"))||(containsElem(ref_noarray,<%=ref_no%>))) {
alert("Referral doctor " + "<%=ref_name%>" + " already exists");
} else {
AddOtherRefDoc("<%=ref_name%>", <%=ref_no%>);
}
} else {
AddOtherRefDoc("<%=ref_name%>", <%=ref_no%>);
}
}
<%} %>
self.close();
}
function containsElem(array1,elem) {
for (var i=0;i<array1.length;i++) {
if(array1[i]==elem){
return true;
} else{
return false;
}
}
}
When this function is called, it is supposed to carry the 2 input elements "ref_docs" and "ref_nos" into the page that opened this window. But it is not doing so. It lists the elements alright but when I try to use "ref_docs" and "ref_nos" in another Javascript function in the 1st window, I see that "ref_nos" and "ref_docs" are empty.
What am I doing wrong?
function updateRd(){
var ref_docs = jQuery("#updatedelete").find('input[name="ref_docs"]');
var ref_nos = jQuery("#updatedelete").find('input[name="ref_nos"]'); alert(ref_docs.val() + ref_nos.val());
var rdocs = new Array();
var rnos = new Array();
ref_docs.each(function() { rdocs.push($(this).val()); } );
ref_nos.each(function() { rnos.push($(this).val()); } );
$('#r_doctor').val(rdocs.join(";"));
$('#r_doctor_ohip').val(rnos.join(";")); }
–
This function returns an error saying "ref_docs" and "ref_nos" are undefined.
I think it is trying to use the jQuery on the other page to find "#r_docs" on the current page.
Try:
jQuery(opener.document).find("#r_docs").append(html);
UPDATE:
I created index.html:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.js"></script>
<script type="text/javascript">
window.jQuery = jQuery;
function openChild ()
{
var mychildwin = window.open("child.html");
}
</script>
</head>
<body>
<input type="button" value="click" onclick="openChild();" />
<div id="r_docs">
Redocs here.
</div>
</body>
</html>
and child.html:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.js"></script>
<script type="text/javascript">
function AddOtherRefDoc(name, number) {
var remove = "<a href='javascript:void(0);' onclick='removeRefDoctor(this)'>Remove</a>";
var html = "<li><b> Referral Doctor: </b>"+name+"<b>, Referral No: </b>"+number+ " " +remove+" <input type='text' name='ref_docs' value='"+name+"'></input><input type='text' name='ref_nos' value='"+number+"'></input></li>";
jQuery(opener.document).find("#r_docs").append(html);
}
</script>
</head>
<body>
<input type="button" value="click" onclick="AddOtherRefDoc('name', 42);"/>
</body>
</html>
UPDATE2:
in your update function document.updatedelete has no attributes ref_docs and ref_nos.
try:
jQuery("#updatedelete")
.find('input[name="ref_docs"], input[name="ref_nos"]')
Where your form is
<form id="updatedelete" ... >
Your function that accesses the DOM elements is incorrect. updatedelete is not a property of document, nor will accessing a ref_docs or ref_nos property automatically build a collection of input elements. Since you're using jQuery already, try this:
var ref_docs = $('input[name="ref_docs"]');
var ref_nos = $('input[name="ref_nos"]');
That will give you Array (or at least array-like) objects that will let you access your inputs:
var rdocs = new Array();
var rnos = new Array();
ref_docs.each(function() { rdocs.push($(this).val()); } );
ref_nos.each(function() { rnos.push($(this).val()); } );
$('#r_doctor').val(rdocs.join(";"));
$('#r_doctor_ohip').val(rnos.join(";"));

Categories

Resources