How to add +1 to a text value every click i do? - javascript

I want to add +1 to a text value but when I click it doesn't add anything...
I think is a updating time but i am not sure...
<input type="text" id="cliccare" value="0">
<img src="http://www.sinalphoto.com/wp-content/uploads/2012/08/no-copyright.png" class="click" onclick="clicca()"/>
punticlick = 1;
punti = document.getElementById("cliccare").value ;
function clicca() {
punti += punticlick;
}
I don't really know if it is correct the onclick on the img...

You cannot add punticlick to punti, it makes no sense: in javascript, punti += punticlick equals to punti = punti + punticlick. Instead, you have to do this:
punticlick = 0;
punti = document.getElementById("cliccare");
function clicca(){
punticlick++;
punti.value = punticlick;
}
Check the fiddle: https://jsfiddle.net/jn9dqfp4/1/

punti = document.getElementById("cliccare").value is outside the function clicca. So on every click it wont get new value
Secondly since you will add one you can directly add with punti. I dont see any use of second variable
Thirdly once you have updated the value of punti you need to update value of the DOM
function clicca(){
punti = parseInt(document.getElementById("cliccare").value,10) ; // Convert to integer
punti += 1;
document.getElementById("cliccare").value=punti
}
JSFIDDLE

A very shortcut (mostly discouraged) way is like this
cliccare.onclick = e => ++e.target.value
<input type="text" id="cliccare" value="0">

you can just set onclick attribute:
onclick="document.getElementById('cliccare').value++"

<input type="text" id="cliccare" value="0">
<img src="http://www.sinalphoto.com/wp-content/uploads/2012/08/no-copyright.png" class="click" onclick="clicca()"/>
<script>
var pun = 1;
punti = document.getElementById("cliccare").value ;
function clicca(){
punti=pun;
document.getElementById("cliccare").value=punti;
pun++;
}
</script>
Try This

You can use onclick attribute for almost any html tag, but the code snippet you've wrote won't work, because after the increment of the value you need to set that value back into input tag, so your java script part would look like this:
<script>
punticlick = 1;
function clicca() {
punti = document.getElementById("cliccare").value;
punti += punticlick;
document.getElementById("cliccare").value = punti;
}
</script>

Related

Uncaught TypeError: Cannot set property 'innerHTML' of null error

I got error of Uncaught TypeError: Cannot set property 'innerHTML' of null for below script.
I added the script tags after the body. But still I get the error.
I want to show the text boxes in the same page within the div with the ID showTextBoxes.
Below is the HTML and JS.
function showArray(){
var numofArr = document.getElementById("numofArr").value;
for (let i = 0; i < numofArr; i++) {
var a = document.writeln('<input type="text" name="Fname"><br/><br/>');
document.getElementById('showTextBoxes').innerHTML = a;
}
document.writeln('<input type="submit" name="submit">');
}
<p>Number of arrays(array within 0-9)</p>
<input type="text" id="numofArr" pattern="[0-9]">
<input type="submit" onclick="showArray()" value="Submit"><br><br>
<div id="showTextBoxes"></div>
Actually document.write()and document.writeln() works in a different ways you think.
It actually clears all the document in your case you you are getting null.
See this
If you wanna add some element to your body you can use document.body.innerHTML += string.appendChild() can also be used but its not for stings
function showArray(){
var numofArr = parseInt(document.getElementById("numofArr").value);
for (let i = 0; i < numofArr; i++) {
var a = '<input type="text" name="Fname" /><br/><br/>'
document.getElementById('showTextBoxes').innerHTML += a;
}
document.body.innerHTML += '<input type="submit" name="submit"/>'
}
<body>
<p>Number of arrays(array within 0-9)</p>
<input type="text" id="numofArr" pattern="[0-9]">
<input type="submit" onclick="showArray()" value="Submit"><br><br>
<div id="showTextBoxes"></div>
I think there are several ways, but I would recommend looking at append. Something like this should work:
function showArray(){
var numofArr = document.getElementById("numofArr").value;
for (let i = 0; i < numofArr; i++) {
var textBox = document.createElement("input");
var enter = document.createElement("br");
document.getElementById('showTextBoxes').append( textBox );
document.getElementById('showTextBoxes').append( enter );
}
}
There are various places in your script which prevent it from running correctly. I'll address them step by step so you can follow along.
First of all, you should avoid inline event handlers in your HTML for the same reasons you should avoid inline style declarations. So don't use onclick=" ... " inside your HTML and instead add eventlisteners in your JS. This also gives you the ability to cancel the default behaviour or stop event propagation and such things.
Next thing is, you try to use the value of your numofArr input as upper bounds for your loop without casting it to a Number. Because <input> elements return their value as a String, this is very likely to fail. Besides, you should use the type="number" attribute instead of type="text" on that element. It's not required to do so, but just good measure.
OK, now for the showArray function:
Instead of using document.writeln (or document.write), create elements with document.createElement and add them to the DOM with appendChild.
You can see a working example below. Don't be confused by the byId and makeEl functions, they are just utilities so you don't have to write document.getElementById and document.createElement all the time.
// ====== UTILITY FUNCTIONS ======
function byId (id, root = document) {
return root.getElementById(id);
}
function makeEl (tag) {
return document.createElement(tag);
}
// ====== PROGRAM STUFF ======
function showArray (e) {
e.preventDefault();
let numofArr = parseInt(byId('numofArr').value, 10);
let output = byId('showTextBoxes');
for (let i = 0; i < numofArr; i++) {
let textIn = makeEl('input');
textIn.type = 'text';
textIn.name = 'Fname';
output.appendChild(textIn);
output.appendChild(makeEl('br'));
output.appendChild(makeEl('br'));
}
let submit2 = makeEl('input');
submit2.type = 'submit';
submit2.value = 'Submit';
document.body.appendChild(submit2);
}
byId('submit1').addEventListener('click', showArray, false);
<p>Number of arrays(array within 0-9)</p>
<input type="number" id="numofArr">
<input id="submit1" type="submit" value="Submit"><br><br>
<div id="showTextBoxes"></div>

Getting the value from an HTML button using JavaScript

I am making a calculator, I have already created the calculator in html and css but I am trying to move forward by making the button clicks register in the display which is what my problem is right now. I am fairly new to JavaScript so if someone could point me in the right direction on how to do it or where to find the answer I would appreciate it.
This is a the portion I am working on, trying to get button '7' to register so I can do the others.
<div class="container-fluid calc" >
<div class="display">
<label type="text" id="screen">0</label>
<div class="buttons">
<button onClick='calculate()' id='myButton'>7</button>
<button>8</button>
<button>9</button>
Here is the JS I put together
function calculate(){
var num = document.getElementById('#myButton').contentValue;
document.getElementById('screen').innerHTML = num;
}
calculate();
You need to update from
var num = document.getElementById('#myButton').contentValue;
to
var num = document.getElementById('myButton').innerHTML;
You should use the .innerHTML function instead of the .contentValue function to do this, also, you shouldn't use a # in document.getElementById this is used in jQuery, so just the ID is enough
function calculate(){
var num = document.getElementById('myButton').innerHTML;
document.getElementById('screen').innerHTML = num;
}
calculate();
Hope this helps!
Update
function calculate(){
var num = document.getElementById('#myButton').contentValue;
document.getElementById('screen').innerHTML = num;
}
to
function calculate(){
var num = document.getElementById('myButton').innerText;
document.getElementById('screen').innerText = num;
}
Another option is you can is data attribute like this :
<button onClick='calculate()' id='myButton' data-value="7">7</button>
and get it like this :
$("#myButton").attr("data-value");

Noob at javascript trying to add +1 to a var with a button

Hey I'm really new to javascript and i just don't understand why it won't print on my document a number increasing every time i click on my button
<script type="text/javascript">
var x = 0;
function clicker(
y = x+1
)
document.write(y)
return clicker();
</script>
<form name="click">
<input type="button" name="derp" onclick="clicker()">
</form>
must be :
var x = 0;
function clicker(){
y = x+1;
document.write(y)
}
but, using document.write(y) will erase your button, to remedy this, you can create another element like <div id='status'></div> and use
//use this instead of document.write(y)
var stat = document.getElementById("status");
stat.innerHTML = y;
There are some problems with the script:
The syntax for the function is wrong, so the code won't run at all.
You can't use document.write once the page is loaded, then it will replace the entire page with what you write.
You are calculating a value that is one higher than a value that never changes, so it will only increase the first time, after that it just returns the same result.
Create an element where you can put the result, and increase the variable in the function so that the value changes each time.
<script type="text/javascript">
var x = 0;
function clicker() {
x = x + 1; // or simply x++;
document.getElementById('value').innerHTML = x;
}
</script>
<form name="click">
<input type="button" name="derp" onclick="clicker()">
</form>
<div id="value"></div>

How to add array items to <li> Jquery

I'm working on something really simple, a short quiz, and I am trying to make the items I have listed in a 2-d array each display as a <li>. I tried using the JS array.join() method but it didn't really do what I wanted. I'd like to place them into a list, and then add a radio button for each one.
I have taken the tiny little leap to Jquery, so alot of this is my unfamiliarity with the "syntax". I skimmed over something on their API, $.each...? I'm sure this works like the for statement, I just can't get it to work without crashing everything I've got.
Here's the HTML pretty interesting stuff.
<div id="main_">
<div class="facts_div">
<ul>
</ul>
</div>
<form>
<input id="x" type="button" class="myBtn" value="Press Me">
</form>
</div>
And, here is some extremely complex code. Hold on to your hats...
$(document).ready (function () {
var array = [["Fee","Fi","Fo"],
["La","Dee","Da"]];
var q = ["<li>Fee-ing?","La-ing?</li>"];
var counter = 0;
$('.myBtn').on('click', function () {
$('#main_ .facts_div').text(q[counter]);
$('.facts_div ul').append('<input type= "radio">'
+ array[counter]);
counter++;
if (counter > q.length) {
$('#main_ .facts_div').text('You are done with the quiz.');
$('.myBtn').hide();
}
});
});
Try
<div id="main_">
<div class="facts_div"> <span class="question"></span>
<ul></ul>
</div>
<form>
<input id="x" type="button" class="myBtn" value="Press Me" />
</form>
</div>
and
jQuery(function ($) {
//
var array = [
["Fee", "Fi", "Fo"],
["La", "Dee", "Da"]
];
var q = ["Fee-ing?", "La-ing?"];
var counter = 0;
//cache all the possible values since they are requested multiple times
var $facts = $('#main_ .facts_div'),
$question = $facts.find('.question'),
$ul = $facts.find('ul'),
$btn = $('.myBtn');
$btn.on('click', function () {
//display the question details only of it is available
if (counter < q.length) {
$question.text(q[counter]);
//create a single string containing all the anwers for the given question - look at the documentation for jQuery.map for details
var ansstring = $.map(array[counter], function (value) {
return '<li><input type="radio" name="ans"/>' + value + '</li>'
}).join('');
$ul.html(ansstring);
counter++;
} else {
$facts.text('You are done with the quiz.');
$(this).hide();
}
});
//
});
Demo: Fiddle
You can use $.each to iterate over array[counter] and create li elements for your options:
var list = $('.facts_div ul');
$.each(array[counter], function() {
$('<li></li>').html('<input type="radio" /> ' + this).appendTo(list);
}
The first parameter is your array and the second one is an anonymous function to do your action, in which this will hold the current element value.
Also, if you do this:
$('#main_ .facts_div').text(q[counter]);
You will be replacing the contents of your element with q[counter], losing your ul tag inside it. In this case, you could use the prepend method instead of text to add this text to the start of your tag, or create a new element just for holding this piece of text.

Javascript Game for Kids

I'm trying to make a game in javascript. I still have many issues in the code. The code is supposed to have 2 buttons; one for shuffling images dice and a button to check if the kid wrote the correct answer or not.
2 buttons
1 textbox
and a place to show the answer if it's correct or not
Here is my code.
I don't know why when I put the source of document.getElementbyID("test") it shows nothing
because I want every time I click on start a random image is selected.
I would appreciate any help as I am still a beginner in javascript.
<head>
<script type="text/javascript">
function startf(){
var images = [];
index = 0;
images[0] = "<img src='1.png' length=70px width=75px>";
images[1] = "<img src='2.png' length=70px width=75px>";
images[2] = "<img src='3.png' length=70px width=75px>";
images[3] = "<img src='4.png' length=70px width=75px>";
index = Math.floor(Math.random() * images.length);
take(index);
function take(ind)
{
return document.getElementbyId("ind")="What should i put here";
}
}
function check(){
var ch=getElementbyId("answer").value;
if (ch=index+1)
{
document.getElementbyId.innerHTML="TRUE";
}
else
{
document.getElementbyId.innerHTML="False";
}
}
</script><br>
</head>
<img id="test" src="" alt="..." length="75px" width="75px" />
<body>
<input type="button" value="start" onclick="startf()">
<input id="answer" type="text" name="checkvalue" value="Enter Value" onclick="check()">
<div id="fa">
</div>
<input type="button" value=chek onclick="check()">
</body>
1- Put and end to each instructions --> ;
2- Do not use document.getElementById directly, there will be at least one occurence with an error into it and you don't want that.
function _e(id) {
return document.getElementById(id);
}
3- Always put brackets and (...) around your IF-ELSE blocks:
if (...) {
//....
} else {
//....
}
4- Every tag attributes should have " " around their values, for example:
<input type="button" value="start" onclick="check()" />
5- You could only put image paths in your array since it seems to be what needs to be updated in #test image.
It is document.getElementById check the casing. Your check function is wrong... you can't assign a value to document.getElementById function. Also your if is wrong. Do you know any JavaScript?
I'm guessing what you want is probably something like this. You seem to be trying to add or replace an element just by using document.getElementById(id) = something but that's not how it works. Instead, to change an image to another file you need to alter its src attribute. (There are other ways but this is maybe the simplest.)
// Declare the variable called number here so it can be accessed
// by all of the following functions.
var number;
// a simple function to save typing document.getElementById all the time
function _e(id) {
return document.getElementById(id);
}
function startf() {
// Pick a number between 1 and 4
number = Math.floor(Math.random() * 4 + 1);
// Set the image with id 'test' to have the source 1.png, 2.png etc.
_e('test').src = number + '.png';
}
function check() {
// note that == is used for comparison, = is used for assignment
if (_e('answer').value == number) {
_e('fa').innerHTML = "TRUE";
}
else {
_e('fa').innerHTML = "False";
}
}​

Categories

Resources