I have the following HTML:
<button id="ES" class="select" type="button">Select</button>
<h2>Total Units: <span id="totalselected"></span></h2>
and script:
var units=0;
document.getElementById('ES').onclick = function() {
var units=units+2;
document.getElementById("totalselected").innerHTML = units;
};
I want that when the button is clicked, add + 2 to a counter.
It starts off at 0 and is displayed on the webpage.
When the button is clicked, the number jumps to two.
If it is clicked again, the number jumps to four.
Remove the second var on units
var units=0;
document.getElementById('ES').onclick = function() {
units=units+2; // here
document.getElementById("totalselected").innerHTML = units;
};
DEMO
change this:
var units=units+2;
to this:
units=units+2; // remove the keyword var
As per your post:
I want that when the button is clicked, add + 2 to a counter. It starts off at 0 and is displayed on the webpage.
To start your values from 0 you can move your var unit = unit + 2 at the bottom:
var units=0;
document.getElementById('ES').onclick = function() {
document.getElementById("totalselected").innerHTML = units;
units=units+2;
};
<html>
<head>
<script>
var c=0;
function test()
{
c=c+2;
document.getElementById("cnt").innerHTML=c;
}
</script>
</head>
<body>
<input type="button" value="Click" onClick="test()"/>
Count= <p id="cnt""></p>
</body>
</html>
Related
In my Web university course there is this example with local storage and it says it should show in the input area the number of clicks on the button and also store it in localstorage, but all I get is NaN on the input no matter how many times I click on the button.
<head>
<script>
window.onload = function()
{
var el=document.getElementById("bt");
el.onclick= function()
{
var x = parseInt(localStorage.getItem("nrc"));
if (x!==NaN){
localStorage.setItem("nrc", x + 1);
}
else{
localStorage.setItem("nrc", "1");
}
document.getElementById("write").value = localStorage.getItem("nrc");
}
document.getElementById("write").value = localStorage.getItem("nrc");
var buton2=document.getElementById("bt2");
buton2.onlick = function ()
{
localStorage.removeItem("nrc");
}
}
</script>
</head>
<body>
<p> Number of clicks on the button <input type="text" id="write" value="0"> </p>
<button id="bt"> Click</button>
<button id="bt2"> Click2</button>
</body>
Edit: problem was solved, but now if i want to remove an item from local storage or clear the localstorage it doesn't work.
You have a typo, you wrote onlick instead of onclick
buton2.onclick = function() {
console.log('clearing storage!');
localStorage.removeItem("nrc");
// Reset input back to zero
document.getElementById("write").value = '0';
}
Complete working example here
You were checking a non number to a non number which will always true.
Anyways the solution is already posted in the comments
<head>
<script>
window.onload = function() {
var el = document.getElementById("bt");
el.onclick = function() {
var x = parseInt(localStorage.getItem("nrc"));
if (!isNaN(x)) {
localStorage.setItem("nrc", x + 1);
} else {
localStorage.setItem("nrc", "1");
}
document.getElementById("write").value = localStorage.getItem("nrc");
}
document.getElementById("write").value = localStorage.getItem("nrc");
}
</script>
</head>
<body>
<p> Number of clicks on the button <input type="text" id="write" value="0"> </p>
<button id="bt"> Click</button>
</body>
The goal is to type in one text box a certain value (of pixels or centimeters) then to press a button, and the button to do some maths and show the result in a different text box.
What happens is, I'll get a result of 'NaN', implying that the string I inputted hadn't been converted properly. I've gone through hundreds of methods to fix this and it still doesn't work.
Code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Conversion</title>
</head>
<body bgcolor=#FF0000>
<form id="conversions" name="conversions">
Pixel value :
<br>
<input type="text" name="pxvalue" id="pxvalue">
<br>
<input type="submit" name="convertcm" id="convertcm" value="Convert cm to px!">
<input type="submit" name="convertpx" id="convertpx" value="Convert px to cm!">
<br>Centimeter value :
<br>
<input type="text" name="cmvalue" id="cmvalue">
<br>
<br>Output :
<input type="text" name="output" id="output">
</form>
<!-- This is where all the JavaScript code goes -->
<script>
var form = document.getElementById("conversions");
var strcmvalue = form.elements["cmvalue"];
var strpxvalue = form.elements["pxvalue"];
var cmvalue = ToInteger(strcmvalue);
var pxvalue = ToInteger(strpxvalue);
var output = document.getElementById("output");
var ccmbutton = document.getElementById("convertcm").onclick = cm_to_pixel_conversion(cmvalue);
var cpxbutton = document.getElementById("convertpx").onclick = pixel_to_cm_conversion(pxvalue);
var cm_per_pixel = 0.026458333;
var px_per_cm = 37.795275591;
function pixel_to_cm_conversion(pvalue) {
cmconversion = pvalue / px_per_cm;
output.value = cmconversion.toString();
}
function cm_to_pixel_conversion(cvalue) {
pxconversion = cvalue / cm_per_pixel;
output.value = pxconversion.toString();
}
function ToInteger(x) {
x = Number(x);
return x < 0 ? Math.ceil(x) : Math.floor(x);
}
</script>
<!-- End of the JavaScript code-->
</body>
</html>
Because you are not passing a value to the method, you are passing an html element.
var strcmvalue = form.elements["cmvalue"]; //reference element
var strpxvalue = form.elements["pxvalue"];
var cmvalue = ToInteger(strcmvalue); //passing element, not the value
var pxvalue = ToInteger(strpxvalue);
You need strcmvalue.value or form.elements["cmvalue"].value
Next issue is the fact you read the values when the page loads, so you will only ever have the values from the time it loads.
So you should be reading the values and converting them to numbers inside of your methods, not when the page loads.
After that your click event is calling the function, not referencing it.
var ccmbutton = document.getElementById("convertcm").onclick = function () {
var num = parseInt(strcmvalue.value, 10);
cm_to_pixel_conversion(num);
return false;
};
I'm currently adding some input fields to a div. There is also the option to remove the just added input fields.
Now the problem is, if you add 4 input fields and let's say you removed number 2.
You will get something like this
id=1
id=3
id=4
Now when you will add a new one it will add id=5.
So we end up with:
id=1
id=3
id=4
id=5
JS :
var iArtist = 1,
tArtist = 1;
$(document).on('click', '#js-addArtist', function() {
var artist = $('#js-artist');
var liData = '<div class="js-artist"><input id="artiestNaam_' + iArtist + '"><input id="artiestURL_' + iArtist + '"><span class="js-removeArtist">remove</span></div>';
$(liData).appendTo(artist);
iArtist++;
tArtist++;
});
$(document).on('click', '.js-removeArtist', function() {
if (tArtist > 1) {
$(this).parents('.js-artist').slideUp("normal", function() {
$(this).remove();
tArtist--;
});
}
});
$(document).on('click', '#js-print', function() {
var historyVar = [];
historyVar['artiestNaam_0'] = $('#artiestNaam_0').val();
historyVar['artiestURL_0'] = $('#artiestURL_0').val();
console.log(historyVar);
});
HTML :
<span id="js-addArtist">add</span>
<div id="js-artist">
<div class="js-artist">
<input id="artiestNaam_0">
<input id="artiestURL_0">
<span class="js-removeArtist">remove</span>
</div>
</div>
<span id="js-print">print</span>
For now it's okay.
Now for the next part I'm trying to get the data from the input fields:
historyVar['artiestNaam_0'] = $('#artiestNaam_0').val();
historyVar['artiestURL_0'] = $('#artiestURL_0').val();
How can I make sure to get the data of all the input fields?
Working version
You could do with a whole lot less code. For example purposes I'm going to keep it more simple than your question, but the priciple remains the same:
<input name="artiest_naam[]" />
<input name="artiest_naam[]" />
<input name="artiest_naam[]" />
The bracket at the end make it an array. We do not use any numbers in the name.
When you submit, it will get their index because it´s an array, which returns something like:
$_POST['artiestnaam'] = array(
[0] => "whatever you typed in the first",
[1] => "whatever you typed in the second",
[2] => "whatever you typed in the third"
)
If I would add and delete a hundred inputs, kept 3 random inputs and submit that, it will still be that result. The code will do the counting for you.
Nice bonus: If you add some javascript which enables to change the order of the inputs, it will be in the order the user placed them (e.g. if I had changed nuymber 2 and 3, my result would be "one, third, second").
Working fiddle
You could use each() function to go through all the divs with class js-artist:
$('.js-artist').each(function(){
var artiestNaam = $('input:eq(0)',this);
var artiestURL = $('input:eq(1)',this);
historyVar[artiestNaam.attr('id')] = artiestNaam.val();
historyVar[artiestURL.attr('id')] = artiestURL.val();
});
Hope this helps.
var iArtist = 1,
tArtist = 1;
$(document).on('click', '#js-addArtist', function() {
var artist = $('#js-artist');
var liData = '<div class="js-artist"><input id="artiestNaam_' + iArtist + '"><input id="artiestURL_' + iArtist + '"><span class="js-removeArtist">remove</span></div>';
$(liData).appendTo(artist);
iArtist++;
tArtist++;
});
$(document).on('click', '.js-removeArtist', function() {
if (tArtist > 1) {
$(this).parents('.js-artist').slideUp("normal", function() {
$(this).remove();
tArtist--;
});
}
});
$(document).on('click', '#js-print', function() {
var historyVar = [];
$('.js-artist').each(function(){
var artiestNaam = $('input:eq(0)',this);
var artiestURL = $('input:eq(1)',this);
historyVar[artiestNaam.attr('id')] = artiestNaam.val();
historyVar[artiestURL.attr('id')] = artiestURL.val();
});
console.log(historyVar);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="js-addArtist">add</span>
<div id="js-artist">
<div class="js-artist">
<input id="artiestNaam_0">
<input id="artiestURL_0">
<span class="js-removeArtist">remove</span>
</div>
</div>
<span id="js-print">print</span>
Initialize a count variable. This way if an input field is removed, a new id still gets initialized. To get the data for each of them, jQuery has a convenient each function to iterate over all elements.
Hope this helps
count = 0;
$("#add").on("click", function() {
count++;
$("body").append("<input id='" + count + "'</input>");
});
$("#remove").on("click", function() {
var index = prompt("Enter the index of the input you want to remove");
$("input:eq(" + index + ")").remove();
});
$("#log-data").on("click", function() {
$("input").each(function() {
console.log($(this).val());
});
});
#btn-group {
margin-bottom: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="btn-group">
<button id="add">Add Input Fields</button>
<button id="remove">Remove Input Fields</button>
<button id="log-data">Log Data</button>
</div>
There are a few ways this can be asked, I'm trying to go with the easiest. Basically, I have two fields... one is to add a number, the other is to subtract. What I want, is when a number is input into either (let's just stick with the add input for now) and have it update at the bottom once the button "+" is pressed. I want that result to stay at the bottom, so when a new value is put into the add box and the button is pressed, it ADDS to the previous total. For the life of me, I can't figure this one out. Once resolved, I'll take care of the subtraction on my own, just need a push in the right direction. The current code is as follows.
<div id="entire">
<div id="content">
<input type="number" id="addInput" placeholder="0">
<button type="button" id="addBtn" onclick="add()">+</button>
<br>
<br>
<input type="number" id="subInput" placeholder="0">
<button type="button" id="subBtn" onclick="sub()">-</button>
<br>
<br>
<div id="totalAmt"></div>
<br>
<input type="button" id="clear" onclick="clearFields()" value="Clear">
<input type="button" id="reset" onclick="reset()" value="Reset">
</div>
</div>
function add() {
var addInput = document.getElementById("addInput").value;
var emptyValue = "";
var total = emptyValue + addInput;
document.getElementById("totalAmt").innerHTML = total;
}
function clearFields() {
document.getElementById("addInput").value = "";
document.getElementById("subInput").value = "";
}
function reset() {
document.getElementById("totalAmt").innerHTML = "";
}
A link to my codepen is below:
http://codepen.io/0ktane/pen/NNdbOq
Your problem is these two lines
var emptyValue = "";
var total = emptyValue + addInput;
when you are concatenating to a string, you get a string back.
Also, you are not even considering the previous value at first place.
Try this, updated pen
function add() {
var addInput = parseInt(document.getElementById("addInput").value); //parse the value to an integer first
var totalAmt = parseInt(document.getElementById("totalAmt").innerHTML); //parse the value to an integer first
totalAmt = isNaN(totalAmt) ? 0 : totalAmt; //if the value is NaN(not a number) reset it to 0
addInput = isNaN(addInput) ? 0 : addInput;//if the value is NaN(not a number) reset it to 0
document.getElementById("totalAmt").innerHTML = totalAmt + addInput ; //output the correct value
}
var total = 0;
function add() {
var addInput = parseInt(document.getElementById("addInput").value);
total = total + addInput;
document.getElementById("totalAmt").innerHTML = total;
}
How do I change the HTML itself when I press a button? When I press a button in this case, the value is stored as "displayCount". Is there a way in which I can directly see the count on the HTML code? If it was press one time, I could see the number 1 on the HTML itself, not as a variable?
Thank you!
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title> </title>
</head>
<body>
<input type="button" value="Count" id="countButton" />
<p>The button was pressed <span id="displayCount">0</span> times.</p>
<script type="text/javascript">
var count = 0;
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
button.onclick = function() {
count++;
display.innerHTML = count;
}
</script>
</body>
</html>
For example, if button was pressed once, one of the line would change from
<p>The button was pressed <span id="displayCount">1</span> times.</p>
This Fiddle works as you want..
i changed your script into :
var count = 0;
function countIt(){
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
count++;
display.innerHTML = count;
}
and your HTML to :
<input type="button" onclick="countIt()" value="Count" id="countButton" />
<p>The button was pressed <span id="displayCount">0</span> times.</p>
hope this will help you
<script type="text/javascript">
var clicks = 0;
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
</script>
<button type="button" onClick="onClick()">Count</button>
<p>The button was pressed : <a id="clicks">0</a></p>
Here is my jsfiddle to your problem.
I delete the varible count you used, and just use the number on your HTML, it works well.
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
button.onclick = function(){
display.innerHTML = ++display.innerHTML;
}
Thanks,
Edison
I guess you might want to use parseInt() explicitly increment the count as an integer like this:
var count = parseInt(display.textContent,10);
Your code could go like this:
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
var count = parseInt(display.textContent,10);
button.onclick = function(){
count++;
display.innerHTML = count;
}
DEMO : http://jsfiddle.net/naokiota/9dQjv/2/
The document of the parseInt() is here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
Hope this helps.
<script>
var count = 0;
function counts()
{
var result = document.getElementById('txtbxid');
count ++ ;
result.value = count;
}
</script>
<input type="text" id="txtbxid" name="txtbxid">
<input type="button" id="add" name="add" value="add" onClick="counts()">