I want to increase a value when some checkboxes are checked - javascript

I want to increase the price if one or more check boxes are checked. Here is the code i have but it does not work
HTML
<input type="checkbox" value="15" />Checkbox
<br/>
<br/>
<span id="result"></span>
JAVASCRIPT
var a=0;
window.onload = function () {
var input = document.querySelector('input[type=checkbox]');
function check() {
var a = a+value;
document.getElementById('result').innerHTML = 'result ' + a;
}
input.onchange = check;
check();
}

You've scoped your a variable away in the check function, and you're calling the function check without the proper "this".
This should work
var a = 0;
window.onload = function() {
var input = document.querySelector('input[type=checkbox]');
function check() {
a = a + parseInt(this.value, 10);
document.getElementById('result').innerHTML = 'result ' + a;
}
input.onchange = check;
input.onchange();
}

your variable "a" is in global scope when you have initialized it on the top var a = 0; If you want to use it, you can directly do a = a + 1.
When you declare it again as a var inside check function, it is now a new variable "a" bound to the check function scope as a new variable and its not referring to the variable declared at the top.
So the solution is remove declaration var and directly use it as a = a + 1 inside check function.
Also you need to check if checkbox is checked :
here is a working fiddle : https://jsfiddle.net/1m09z0cg/

There are a couple of things wrong.
First, querySelector will only return the first element that matches the selector, if you want to get all checkboxes you'll have to use querySelectorAll.
Second, you're using var a = a+value; if you want to add value to the previous value of the global variable a you should use a = a+value;, by using var a = ... you're declaring a new variable a in the current context.
Third, there is no variable value, if you're trying to get the value of the clicked element use event.currentTarget.value.
var checkboxes = Array.from(document.querySelectorAll("input[type='checkbox']"));
var result = document.querySelector("#result");
checkboxes.forEach(function(checkbox){
checkbox.onchange = function(){
var total = checkboxes.reduce(function(a, c){
return a + (c.checked ? parseInt(c.value):0);
}, 0);
result.textContent = "Result " + total;
}
});
<input type="checkbox" value="15" />Checkbox
<br/>
<input type="checkbox" value="15" />Checkbox 2
<br/>
<input type="checkbox" value="15" />Checkbox 3
<br/>
<br/>
<span id="result">Result 0</span>

Related

Increment input field value with jQuery

I want every time when user enter number ,print the new one + old one in console
here is html script
<input type="number"value=""/>
<button>click</button>
my jquery code
$("button").click(function (){
var x = $("input").val();
x+=x;
console.log(x);
});
You have to initialize the value outside somewhere to keep its state.
html
<input type="number" id="inp" value=""/>
<button>click</button>
js
var x = 0;
$("button").click(function (){
var y = parseInt($("#inp").val());
x+=y;
console.log(x);
});
hope this will help to you. refer the working demo.
var thevalue = 0;
$("#click").click(function(){
$("#display").text("The Value is :");
var theinput_value = parseInt($("#num").val());
thevalue += theinput_value;
$("#display").append(thevalue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Enter the nubmer : <input type="number" id="num"><button id="click">Click on me !</button>
<br>
<p id="display">The Value is :</p>
You just need to make sure x is a global variable so you can save it's value and used each time the click handler is triggered.
I added input casting to avoid string concatenation when using the addition assignment operator.
var x = 0;
$("button").click(function (){
// Get the input
var current_input = parseInt($("input").val());
// If input is not a number set it to 0
if (isNaN(current_input)) current_input = 0;
// Add the input to x
x+=current_input;
// Display it
console.log(x);
});

Tricky Javascript logic with Objects, Array and Booleans

I am having a lot of issue trying to figure out this logic. Let me set the stage here:
In the HTML there are some form/input elements type radio. Each of them have an ID assigned to it.
<form>
<input type="radio" name="oneAllowed" id="yesterday" />
<input type="radio" name="oneAllowed" id="today" />
<input type="radio" name="oneAllowed" id="tomorrow" />
</form>
Using Javascript essentially what I am trying to do is loop through the 3 objects, since they all have same name assigned within HTML only a single one can be selected, whichever one is returning true I want grab hold of that result then access the second key:value pair, for example for 'commitYesterday' it would be 'commitYesterday.hasValue();' and dispatch that to a different function for other calculation.
var urgentOrderSelector = function(){
var commitYesterday = {
isChecked: document.getElementById("yesterday").checked,
hasValue: function(){
if (this.isChecked == true) {
return 3;
};
};
};
var commitToday = {
isChecked: document.getElementById("today").checked,
hasValue: function(){
if (this.isChecked == true) {
return 2;
};
};
};
var commitTomorrow = {
isChecked: document.getElementById("tomorrow").checked,
hasValue: function(){
if (this.isChecked == true) {
return 1;
};
};
};
var urgentArray = [commitYesterday.isChecked, commitToday.isChecked, commitTomorrow.isChecked];
for(var i = 0; i <= urgentArray.length-1; i++){
if (urgentArray[i].isChecked == true) {
//This is where I am stuck. I was thinking of doing perhaps the following:
return urgentArray[i].hasValue();
};
}
};
Why don't you change your HTML to this:
<form>
<input type="radio" name="oneAllowed" id="yesterday" value="3" />
<input type="radio" name="oneAllowed" id="today" value="2" />
<input type="radio" name="oneAllowed" id="tomorrow" value="1" />
</form>
And use document.querySelector to get the selected elements:
document.querySelector('[type="radio"][name="oneAllowed"]:checked').value
If you actually need to run specific functions dependend on which radio box is checked you could add an attribute data-fn="fnName" to each input and then create an object with the keys as functions:
var fns = {'fnName1': function () {}, 'fnName2': function() {} …};
And then call the function defined by the Attribute:
fns[document.querySelector('[type="radio"][name="oneAllowed"]:checked').getAttribute('data-fn')]();
Not exactly sure what your end goal is.
But here's a more minified version of your logic. Hope it helps.
var urgentOrderSelector = function(){
var radioDict = {'yesterday':3, 'today':2, 'tomorrow':1};
return radioDict[$('input[name=oneAllowed]:checked').attr('id')];
};
Alternatively, if you wanted to execute some function based on the selection, you could store the function pointers and execute them accordingly, ie:
var funcYesterday = function(){alert('yesterday');};
var funcToday = function(){alert('today');};
var funcTomorrow = function(){alert('tomorrow');};
var funcUrgentOrder = function(){
var radioDict = {
'yesterday' : funcYesterday,
'today' : funcToday,
'tomorrow' : funcTomorrow
};
return radioDict[$('input[name=oneAllowed]:checked').attr('id')]();
};
Or, much simpler, since you are using the 'value' property on your radios:
function urgentOrderSelector = function() {
return $('input[name=oneAllowed]:checked').val();
};

Jquery only registers one id

I have three checkboxes that looks like this:
<input id="image_tagging" class="1" type="checkbox" value="1" checked="checked" name="data[image_tagging]">
now i wanted to create some ajax (which is working fine) however only the first checkbox has the event:
here is my Jquery function:
$('#image_tagging').click(function(){
var value = 0;
var websiteID = $(this).attr('class');
if($(this).attr('checked')){
value = 4;
}else{
value = -4;
}
alert('works! '+'id = '+websiteID+" value = "+value );
});
So my question is. why is this click function only happening for one of my checkboxes? (if it matters it is only the first checkbox that is working)
ids must be unique on an html page. Instead use a class in the markup and a class selector in jQuery.
HTML
<input class="image_tagging 1" type="checkbox" value="1" checked="checked" name="data[image_tagging]">
Javascript
$('.image_tagging').click(function(){
var value = 0;
var websiteID = $(this).attr('class');
if($(this).attr('checked')){
value = 4;
}else{
value = -4;
}
alert('works! '+'id = '+websiteID+" value = "+value );
});
IDs have to be unique change the id to class instead
id="image_tagging"
to
class="image_tagging"
then
$('.image_tagging').click(function(){
in html
<input class="image_tagging" type="checkbox" value="1" checked="checked" name="data[image_tagging]">
in js
$('.image_tagging').click(function(){
// your code
});
id must be unique, use class instead or try this...
$('input[type="checkbox"]').click(function(){
var value = 0;
var websiteID = $(this).attr('class');
if($(this).attr('checked')){
value = 4;
}else{
value = -4;
}
alert('works! '+'id = '+websiteID+" value = "+value );
});
no need to change any HTML code you wrote already...
ID should be unique in your DOM structure. Use class instead of ID for such things.
<input id="image_tagging" class="img_tagging 1" type="checkbox" value="1" checked="checked" name="data[image_tagging]">
And then instead of #image_tagging use .image_tagging for binding click event
$('.image_tagging').click(function(){

i have code it can be sum two textbox values using javascript

i have code it can be sum two textbox values using javascript but problem is that when i entered amount into recamt textbox value and javascript count again and again recamt textbox values it should be count only one time recamt textbox value not again and again?
<script type="text/javascript">
function B(){
document.getElementById('advance').value
=(parseFloat(document.getElementById('advance').value))+
(parseFloat(document.getElementById('recamt').value));
return false;
}
</script>
<input class="input_field2" type="text" readonly name="advance"
id="advance" value="50" onfocus="return B(0);" /><br />
<input class="input_field2" type="text" name="recamt" id="recamt">
You could keep a property on the read-only text field to keep the old value:
function B()
{
var adv = document.getElementById('advance'),
rec = document.getElementById('recamt');
if (typeof adv.oldvalue === 'undefined') {
adv.oldvalue = parseFloat(adv.value); // keep old value
}
adv.value = adv.oldvalue + parseFloat(rec.value));
rec.value = '';
return false;
}
You're calling the sum function every time the readonly input is focused using the new value. If you only want it to add to the original value, you need to store it somewhere.
HTML:
<input type="text" id="advance" readonly="readonly" value="50" /><br />
<input type="text" id="recamt">
JS:
var advanceBox = document.getElementById('advance');
var originalValue = advanceBox.value;
advanceBox.onclick = function() {
this.value = parseFloat(originalValue) +
parseFloat(document.getElementById('recamt').value);
return false;
};
http://jsfiddle.net/hQbhq/
Notes:
You should bind your handlers in javascript, not HTML.
The javascript would need to exist after the HTML on the page, or inside of a window.load handler, otherwise it will not be able to find advanceBox.

not changing textbox value from ui and unable to display

taking value in 1st textbox and want to display it in 2nd..
1st <input type="text" value=" " id = "marks1" name = "marks1" onblur = "myFunction('marks1')" />
2nd <input type="text" value=" " id = "marks2" name = "marks1" disabled = "disabled" />
and on oblur I am calling a function. Whenever I change the value from UI, on function call I am getting the old value i.e. ' ' instead of changed value.
in the variable "value" the old value which i am getting, i am unable to display it on 2nd textbox.
function myFunction( txtname )
{
alert("call");
var txtobj = document.getElementsByName(txtname);
var value = txtobj[0].value;
alert("my value : "+value);
txtobj[1].value = value;
}
I know the code is okay, but it is not working at me. Is there any other way?
Works for me:
function myFunction(element)
{
var txtobj = document.getElementsByName(element);
var value = txtobj[0].value;
txtobj[1].value = value;
}​
http://jsfiddle.net/pwTwB/1/
Are you getting an error?
Try it this way:
function myFunction( txtname )
{
var txtobj = document.getElementById(txtname);
var target = document.getElementById("marks2");
target.value = txtobj.value;
}
Here is a simple way to set the next textbox's value.
function moveText(ele){
document.getElementById("marks2").value = ele.value;
}
Then use the following in your html markup
<input type="text" id="marks1" onblur="moveText(this)" />
<input type="text" id="marks2" disabled="disabled" />

Categories

Resources