Simple two button counter html jquery javascript - javascript

I am new to Jquery and Javascript. I've only done the intros for codeacademy and I have what I remembered from my python days.
I saw this tutorial:
http://www.codecademy.com/courses/a-simple-counter/0/1
I completed the tutorial and thought: "I should learn how to do this with Jquery".
So I've been trying to use what I understand to do so. My issue is that I don't know how to pass an argument for a variable from HTML to Jquery(javascript).
Here is my code:
HTML
<body>
<label for="qty">Quantity</label>
<input id="qty" type = "number" value = 0 />
<button class = "botton">-1</button>
<button class = "botton">+1</button>
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="test.js"></script>
</body>
Jquery/Javascript:
//create a function that adds or subtracts based on the button pressed
function modify_qty(x) {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var qty = $('#qty').val();
var new_qty = qty + x;
//i don't want to go below 0
if (new_qty < 0) {
new_qty = 0;
}
//put new value into input box id-'qty'
$('#qty').html(new_qty)
})
};
$(document).ready(modify_qty);
How do I pass an argument of 1 or -1 to the function? I was using onClick() but that seemed redundant because of the $('.botton').click(function(){}).
Thank you

If you use data attributes on your buttons you can get the value you want.
HTML:
<button class = "botton" data-value="-1">-1</button>
<button class = "botton" data-value="1">+1</button>
JS:
function modify_qty() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var qty = parseInt($('#qty').val());
var new_qty = qty + parseInt($(this).data('value'));
//i don't want to go below 0
if (new_qty < 0) {
new_qty = 0;
}
//put new value into input box id-'qty'
$('#qty').val(new_qty)
})
};
$(document).ready(modify_qty);
More compact JS:
$(function() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var $qty = $('#qty'),
currentValue = parseInt($qty.val());
$qty.val(Math.max(0, currentValue + parseInt($(this).data('value'))));
})
});
Update:
Realized you could do this without the data attributes if want to since your button text is the same as your value.
$(function() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var $qty = $('#qty'),
currentValue = parseInt($qty.val()),
newValue = currentValue + parseInt($(this).text());
$qty.val(Math.max(0, newValue));
})
});

Here's a fiddle to help you grasp the what's going on. Basically, the reference to the element that triggered the event is $(this) or event.target. Things get a bit more complicated with self refence depending on the context you are in, however for $('selector').on('event',function(event){ console.log($(this)) //is the reference to $('selector') });. .attr() -> list of the element's attributes.

Related

Put value straight into input textbox form?

I'm grabbing a the last transaction value from https://api.bitcoinaverage.com/ticker/global/CAD/ and want to update it into an input textbox, but no matter what I try it won't show up.
here's a fiddle
https://jsfiddle.net/h9w5tj8m/2/
var xbtc = new XMLHttpRequest();
xbtc.open('GET', 'https://api.bitcoinaverage.com/ticker/global/CAD/', true);
xbtc.onreadystatechange = function() {
if (xbtc.readyState == 4) {
var ticker = JSON.parse(xbtc.responseText);
price = ticker.last;
document.getElementById('btc').innerHTML = price;
document.getElementById('cad').innerHTML = price;
}
};
xbtc.send();
updated fiddle
use
document.getElementById('cad').value
instead of
document.getElementById('cad').innerHTML
Simply understand with user interacted element input,select,textarea all are call with value for get the data from the elements.
All Other element's are call with innerHTML for get the data from the element
also refer different between .value and .innerHTML
var xbtc = new XMLHttpRequest();
xbtc.open('GET', 'https://api.bitcoinaverage.com/ticker/global/CAD/', true);
xbtc.onreadystatechange = function() {
if (xbtc.readyState == 4) {
var ticker = JSON.parse(xbtc.responseText);
price = ticker.last;
document.getElementById('btc').innerHTML = price;
document.getElementById('cad').value = price;
}
};
xbtc.send();
There is no input type of "textbox". You need to change it to "text" or use a <textarea></textarea>. You can set the value of text input with .value and a textarea with .innerHTML or .value.
This fiddle works fine: https://jsfiddle.net/h9w5tj8m/4/
using value attribute will place the value u retrieved into a particular textbox having a specific id .For Example :
<input type ="textbox " id="a">
</input>
<script>
document.getElmentById("a").value=x;
</script>
//x is the variable where the retrieved data is stored.
try this
document.getElementById('cad').value = price;

How to Basically Add the Values of Two <Button> tags

I think I got the logic part right, another problem I have is the NaN output that I keep receiving when I click on the <button> tags. I did use addEventListener('click') method but it seems more complicated, so I tried this simple codes instead. I'm just having trouble on how to add the values of the buttons, any help would be appreciated.
Here's my code :
<html>
<body>
<script type = "text/javascript">
function test(value)
{
var val = parseFloat(value);
var total = parseInt(document.getElementById('totaltext').value);
document.getElementById('totaltext').innerHTML = total + val;
}
</script>
total : <p id = "totaltext" value = "0">0</p>
<button value = "10.11" name = "product" id = "button1" onClick = "test(this.value);">value1</button>
<button value = "20.00" name = "product" id = "button2" onClick = "test(this.value);">value2</button>
</body>
</html>
https://jsfiddle.net/7tm161ob/1/
Because the elements you are accessing button is not an input tag, the value attribute is not the correct one. value is considered an html attribute in this case that is not directly available in the JavaScript object.
You will need to use the method .getAttribute() to get those values. Here is how it works.
<button value="10.11" name="product" id="button1" onclick="test(this);">value1</button>
<button value="20.00" name="product" id="button2" onclick="test(this);">value2</button>
function test(button) {
var val = parseFloat(button.getAttribute("value"));
var total = parseFloat(document.getElementById('totaltext').getAttribute("value"));
document.getElementById('totaltext').innerHTML = total + val;
document.getElementById('totaltext').setAttribute("value",total + val)
}
Working Example

How to calculate the total value of a dynamic number of fields using javascript?

My page shows some forms with content loaded from a database. Every row will get his own <input>. The ID of this input is equal for every row, except for the number that is attached to it, to make it unique. To make it more clear; this is how the form looks like when it loads 3 rows from the database:
<form>
<input id="Amount1" value="<?php echo $databaseValue; ?>" >
<input id="Amount2" value="<?php echo $databaseValue; ?>" >
<input id="Amount3" value="<?php echo $databaseValue; ?>" >
<input type="hidden" name="numberOfRows">
<input id="finalResult">
</form>
This is all done with the mysqli_array function. The value of numberOfRows is based on numRows function.
What I'd like to achieve is that javascript calculates the value of each existing input and put the result in finalResult, regardless the number of forms (because this may vary). If I make some changes to one of the values, the finalResult should update real-time.
What I've tried so far:
formnum contains the number of fields.
var a is created at the beginning, starting at 0. Inside it's function I create an ID, matching the fields on the page. All fields are named "Amount" + number. If this number equals the number of fields, the function will stop. This way the script won't be looking for fields that doesn't excist.
Then it gets the value of this field and adds the value to var b. var b is just created to store the value temporary, untill the function's over.
At the end the total is divided to 15. This is something extra I need. Nothing special on this line.
My code:
<script type='text/javascript'>
$(document).ready(function(){
var formnum = $("#numberOfRows").val();
var a;
var b = 0;
var formname = '#Amount';
for (a = 0; a < formnum; a++) {
var complete = formname.concat(a);
var completeContent = $(complete).val();
b = b + completeContent;
};
b = b.toFixed(2);
});
$(document).mousemove(function(event){
var formula_finalResult = b / 15;
var total_finalResult = Math.floor(formula_finalResult);
$("#finalResult").val(total_finalResult);
});
</script>
This doesn't do anything. It doesn't change the value. What's going wrong?
Make it simple:
$(function(){
var sum = 0;
// Selector to select all input whose id starts with Amount
$("input[id*='Amount']").each(function(){
sum += +$(this).val(); // Parsing as int and adding it to sum
});
$("#finalResult").val(Math.floor(sum/15)); // Storing the values
})
Assuming that all of the fields always have Amount at the beginning of their id attribute, you could use jQuery's ID selector to achieve this, without the need for any of the internal counters, etc.
I'm not entirely sure why you need to hook into the mousemove event, since the data should never change on the page (since it's being generated by PHP when the page is first loaded). The following code should achieve what you're looking for:
$(function() {
var total = 0;
$('input[id*="Amount"]').each(function() { total+= parseFloat( $(this).val() ); });
$('#finalResult').val( Math.floor( total / 15 ) );
});
Your code has an error Uncaught ReferenceError: b is not defined
see it in action here: http://jsfiddle.net/ca9vascj/
There's no reason to bring the mousemove event into this, I'm not even sure what that was needed for.
Like the above answers, here's a much simplified version. But instead of a partial ID selection, let's just give the form an ID, and then give all the needed elements inside that form a class that we can select by. We also no longer need to have the numberOfRows form element.
<form id="theForm">
<input class="formAmmount" value="5" />
<input class="formAmmount" value="10" />
<input class="formAmmount" value="27.5" />
<input class="formAmmount" value="4" />
<input class="formAmmount" value="9" />
<hr />
<input id="finalResult" />
</form>
And then our jQuery code can be reduced to this:
$(function(){
var total = 0;
$("#theForm .formAmmount").each(function(){
total += parseFloat(this.value, 10);
});
var final = Math.floor(total.toFixed(2) / 15);
$("#finalResult").val(final);
});
See it in action here: http://jsfiddle.net/ca9vascj/1/
You dont'need jQuery. The simplest way to do this is document.getElementsByTagName:
var inputs = document.getElementById('my-form').getElementsByTagName('input')
That's it. inputs.length will always get an actual count of inputs in your form. That's because getElementsByTagName() returns a NodeList object, containing a live view of the matching elements. This object is mutable; it will change in response to DOM mutations.
So if you need to get sum from all of the inputs:
function sum() {
var result = 0;
[].slice.call(inputs).forEach(function(input){
result += parseFloat(input.value)
});
return result;
}
If you are able to change the generated Html-Source I would suggest to give a new class to your InputElements.
<input id="Amount1" class="ElementToCount" value="<?php echo $databaseValue; ?>" >
Then you can calculate like that
var getSumOfElements = function() {
var Elements = $('.ElementToCount')
var sum=0
if (Elements && Elements.length>0) {
for (var i=0; i<Elements.length; i++) {
sum += Elements[i].val();
}
}
return sum
}
And to update the field you could register to the 'change'-Event
$('.ElementToCount).on('change', function() {
$('#finalResult').val(getSumOfElements());
})

javascript - get value parameter from input text

I want to get the value of a text input. I would like to do this by using id and getElementById :
here HTML code :
<form>
<fieldset>
<legend>Input ordinate :</legend>
<input type="text" id="ordinateId" name="input"/>
<input type="button" id="startbuttonId" value="Start particle"/>
</fieldset>
</form>
and Javascript :
<script type="text/javascript">
var button = document.getElementById("startbuttonId");
var value = document.getElementById("ordinateId").value;
console.log(value);
button.onclick = function() {
console.log(value);
}
</script>
but into the console, nothing appears for value. Where is the problem ?
Thanks
The problem is that you are checking for the input's value before it is set(on document load). Just move the variable declaration within the click function like so:
var button = document.getElementById("startbuttonId");
button.onclick = function() {
var value = document.getElementById("ordinateId").value;
console.log(value);
}
JSFiddle
You need to get the value again when the event fires. Just move your var value
button.onclick = function() {
var value = document.getElementById("ordinateId").value;
console.log(value);
}
With your current script you are assigning value only once, which I am assuming is an empty string. You need to put the assignment inside the function so it gets the current value of the input when it is clicked.
<script type="text/javascript">
var button = document.getElementById("startbuttonId");
button.onclick = function() {
var value = document.getElementById("ordinateId").value;
console.log(value);
}
</script>

How to change Label Value using javascript

I want to change the label value from '0' to 'thanks' in below label, on checkbox click event.
<input type="hidden" name="label206451" value="0" />
<label for="txt206451" class="swatch_text" >Chestnut Leather</label>
<input type="checkbox" name="field206451" class="swatch_check" id="txt206451" value="SELECTED"/>
The Javascript is as below.
var cb = document.getElementById('field206451');
var label = document.getElementById('label206451');
cb.addEventListener('click',function(evt){
if(cb.checked){
label.value='Thanks';
}else{
label.value='0';
}
},false);
But this is not working. Any idea?
very simple
$('#label-ID').text("label value which you want to set");
This will work in Chrome
// get your input
var input = document.getElementById('txt206451');
// get it's (first) label
var label = input.labels[0];
// change it's content
label.textContent = 'thanks'
But after looking, labels doesn't seem to be widely supported..
You can use querySelector
// get txt206451's (first) label
var label = document.querySelector('label[for="txt206451"]');
// change it's content
label.textContent = 'thanks'
You're taking name in document.getElementById() Your cb should be txt206451
(ID Attribute) not name attribute.
Or
You can have it by document.getElementsByName()
var cb = document.getElementsByName('field206451')[0]; // First one
OR
var cb = document.getElementById('txt206451');
And for setting values into hidden use document.getElementsByName() like following
var cb = document.getElementById('txt206451');
var label = document.getElementsByName('label206451')[0]; // Get the first one of index
console.log(label);
cb.addEventListener('change', function (evt) { // use change here. not neccessarily
if (this.checked) {
label.value = 'Thanks'
} else {
label.value = '0'
}
}, false);
Demo Fiddle
Try
use an id for hidden field and use id of checkbox in javascript.
and change the ClientIDMode="static" too
<input type="hidden" ClientIDMode="static" id="label1" name="label206451" value="0" />
<script type="text/javascript">
var cb = document.getElementById('txt206451');
var label = document.getElementById('label1');
cb.addEventListener('click',function(evt){
if(cb.checked){
label.value='Thanks'
}else{
label.value='0'
}
},false);
</script>
Based off your code, i created this Fiddle
You need to use
var cb = document.getElementsByName('field206451')[0];
var label = document.getElementsByName('label206451')[0];
if you want to use name attributes then you have to take the index since it is a list of items, not just a single one. Everything else worked good.
hope this help someone else :
use innerHTML for using label object.
document.getElementById('lableObject').innerHTML = res.FullName;

Categories