possible to change one variable or another inside of a function - javascript

I don't know if this is possible so I figured this would be the place to ask.
I have two inputs and they each hold a unique value. They each have their own respective variable that the value is saved into. I was wondering if there was a way to use just one function to update their values instead of two seperate ones. Below is my code so far.
<form>
<input type="text" id="valueOne" onchange="changeValueOne(this.value)">
<input type="text" id="valueTwo" onchange="changeValueTwo(this.value)">
</form>
var valueOne = parseFloat($('#valueOne'));
var valueTwo = parseFloat($('#valueTwo'));
function changeValueOne(newValueOne) {
valueOne = newValueOne;
}
function changeValueTwo(newValueTwo) {
valueTwo = newValueTwo;
}

Try this:
var valueOne, valueTwo;
$("#valueOne, #valueTwo").change(function(){
if($(this).attr('id') == 'valueOne') {
valueOne = $(this).val();
} else {
valueTwo = $(this).val();
}
});

You could have a second parameter to indicate which variable to store and/or where.
var values;
function changeValue(newValue, pos){
values[pos] = newValue;
}
Change html to:
<input type="text" id="valueOne" onchange="changeValue(this.value, 'first')">
<input type="text" id="valueOne" onchange="changeValue(this.value, 'second')">
Alternatively if you want to store them in separate variables:
function changeValue(newValue, pos){
if(pos == 'first'){
valueOne = newValue;
} else if(pos == 'second'){
valueTwo = newValue;
}
}

the simple expandable way uses a collection instead of vars:
<form>
<input type="text" id="valueOne" onchange="changeValue(value, id)">
<input type="text" id="valueTwo" onchange="changeValue(value, id)">
</form>
<script>
var vals={
valueOne : parseFloat($('#valueOne').val()),
valueTwo : parseFloat($('#valueTwo').val())
};
function changeValue(newValue, slot) {
vals[slot] = newValue;
}
</script>
not only is it incredibly simple and fast, this lets you add many options without reworking the forking code (ifs), all you need to do is modify the vals object and the handler will keep up automatically with all available options, even creating new ones on-the-fly if needed (from new inputs being appended during run-time).

Related

i have code that can be use for subtract the textbox values using javascript?

i have code that can be use for subtract and additional textbox values using javascript and it is working but problem is that javascript again and again executed function whenever onfocus textbox i want only one time javascript should be executed function?
javascript function again and again additional onMouseOver="return B(0);"
javascript function again and again subtraction onfocus="return C();"
javascript function again and again additional onfocus="return D();"
function getObj(objID){
return document.getElementById(objID);
}
function B(){
var advanceBox = document.getElementById('advance');
var originalValue = advanceBox.value;
advanceBox.onfocus = function() {
this.value = parseFloat(originalValue, 10) +
parseFloat(document.getElementById('recamt').value, 10);
return false;
};
}
function C() {
getObj("balance").value=parseFloat(getObj("total").value || 0)-
(parseFloat(getObj("advance").value || 0)) ;
getObj("balance").value=parseFloat(getObj("balance").value || 0)-
(parseFloat(getObj("discount").value)||0) ;
return false;
}
function D() {
getObj("total").value=parseFloat(getObj("total").value || 0)+
(parseFloat(getObj("openbal").value || 0)) ;
return false;
}
Opening Balance:<input class="input_field2"
type="text" name="openbal" id="openbal"><br />
Total:<input class="input_field2" type="text"
readonly name="total" id="total" value="5000"><br />
Advance:<input class="input_field2" type="text"
readonly name="advance" id="advance" value="500"
onMouseOver="return B(0);"><br />
Balance:<input class="input_field2" readonly type="text"
name="balance" id="balance" onfocus="return C();"><br />
Rem Amount:<input class="input_field2" type="text"
name="recamt" id="recamt"><br />
Discount: <input class="input_field2"
style="background-color:#FFF !important;"
type="text" name="discount" id="discount" >
You could have:
var executedAlready = false;
An inside functions B and C have:
if(executedAlready != true){ executedAlready = true; }
else { return; }
Or maybe you could detach the events instead? I guess there are a few different ways to do this.
What the other answers tell you that the "quickest" way to get results is to make your functions only execute once.
You can do that like this:
Make a flag (just a variable that knows if your function has been triggered already).
When executing your functions, first check on this flag.
Here's an example how to do it with function B():
(Note: I didn't change your function, don't wanna get into that now)
// setup fired as false
var hasBFired = false;
function B(){
// if B is true, we do nothing
if (hasBFired) {
return;
// else if it is not true, basically only the first time you call this, flip the flag and execute the rest of the code.
} else {
hasBFired = true;
}
var advanceBox = document.getElementById('advance');
var originalValue = advanceBox.value;
advanceBox.onfocus = function() {
this.value = parseFloat(originalValue, 10) +
parseFloat(document.getElementById('recamt').value, 10);
return false;
};
Now, repeat the same with C and D functions (setup two more flags).
This is not the best way - it's not good to setup global objects and stuff, but since you probably aren't getting any side library in, it will help you solve your issue for now. For long term solution, you should use an Event library (like YUI Event) and have it handle attaching and detaching actions to onfocus events for you.
you can use one or more flag(s) :
in the begenning of the page :
<script>
var flag = false;
</script>
and on your element:
<div .... onMouseOver="if(!flag) { flag = true; return B(0);}" > .... </div>
same for onFocus...

Looking for a speedy way to update array inside a closure

I'm looking for a method to update arrays via closure. Is there anything that would be more efficient than this.
p.s. I'm not actually using inputs in this manner to set values. They are being passed via another function. Just needed an easy way to get my main point across.
<script>
sampleArrayValues=['copy','this','array'];
a="none";
function updateArr(val,index,action) {
var v=value;
var i=index;
var a=action;
var arr=[];
return function(v,i,a) {
if(a=="none"){
}
if(a=="copy"){
arr=sampleArrayValues;
}
if(a=="update"){
arr[index]=val;
}
return arr;
}
}
updateArr.update1 = updateArr(0,0,a);
function scoopValues(){
var val=0 || document.getElementById('one').value;
var index=0 || document.getElementById('two').value;
var action="none" || document.getElementById('three').value;
alert(updateArr.update1(val,index,action))
}
Enter value: <input id="one" style="width:20px;height:20px"/>
<br>
Enetr index: <input id="two"style="width:20px;height:20px"/>
<br>
Enter Action "none" "copy" or "update": <input id="three"style="width:60px;height:20px"/>
<br>
<input type="button" onclick="scoopValues()" value="click to update"style="width:100px;height:25px"/>

Get the value of checked checkbox?

So I've got code that looks like this:
<input class="messageCheckbox" type="checkbox" value="3" name="mailId[]">
<input class="messageCheckbox" type="checkbox" value="1" name="mailId[]">
I just need Javascript to get the value of whatever checkbox is currently checked.
EDIT: To add, there will only be ONE checked box.
None of the above worked for me but simply use this:
document.querySelector('.messageCheckbox').checked;
For modern browsers:
var checkedValue = document.querySelector('.messageCheckbox:checked').value;
By using jQuery:
var checkedValue = $('.messageCheckbox:checked').val();
Pure javascript without jQuery:
var checkedValue = null;
var inputElements = document.getElementsByClassName('messageCheckbox');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue = inputElements[i].value;
break;
}
}
I am using this in my code.Try this
var x=$("#checkbox").is(":checked");
If the checkbox is checked x will be true otherwise it will be false.
in plain javascript:
function test() {
var cboxes = document.getElementsByName('mailId[]');
var len = cboxes.length;
for (var i=0; i<len; i++) {
alert(i + (cboxes[i].checked?' checked ':' unchecked ') + cboxes[i].value);
}
}
function selectOnlyOne(current_clicked) {
var cboxes = document.getElementsByName('mailId[]');
var len = cboxes.length;
for (var i=0; i<len; i++) {
cboxes[i].checked = (cboxes[i] == current);
}
}
This does not directly answer the question, but may help future visitors.
If you want to have a variable always be the current state of the checkbox (rather than having to keep checking its state), you can modify the onchange event to set that variable.
This can be done in the HTML:
<input class='messageCheckbox' type='checkbox' onchange='some_var=this.checked;'>
or with JavaScript:
cb = document.getElementsByClassName('messageCheckbox')[0]
cb.addEventListener('change', function(){some_var = this.checked})
$(document).ready(function() {
var ckbox = $("input[name='ips']");
var chkId = '';
$('input').on('click', function() {
if (ckbox.is(':checked')) {
$("input[name='ips']:checked").each ( function() {
chkId = $(this).val() + ",";
chkId = chkId.slice(0, -1);
});
alert ( $(this).val() ); // return all values of checkboxes checked
alert(chkId); // return value of checkbox checked
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" name="ips" value="12520">
<input type="checkbox" name="ips" value="12521">
<input type="checkbox" name="ips" value="12522">
Use this:
alert($(".messageCheckbox").is(":checked").val())
This assumes the checkboxes to check have the class "messageCheckbox", otherwise you would have to do a check if the input is the checkbox type, etc.
<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="3" name="mailId[]">
<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="1" name="mailId[]">
function getValue(value){
alert(value);
}
None of the above worked for me without throwing errors in the console when the box wasn't checked so I did something along these lines instead (onclick and the checkbox function are only being used for demo purposes, in my use case it's part of a much bigger form submission function):
function checkbox() {
var checked = false;
if (document.querySelector('#opt1:checked')) {
checked = true;
}
document.getElementById('msg').innerText = checked;
}
<input type="checkbox" onclick="checkbox()" id="opt1"> <span id="msg">Click The Box</span>
If you're using Semantic UI React, data is passed as the second parameter to the onChange event.
You can therefore access the checked property as follows:
<Checkbox label="Conference" onChange={(e, d) => console.log(d.checked)} />
Surprised to see no working vanilla JavaScript solutions here (the top voted answer does not work when you follow best practices and use different IDs for each HTML element). However, this did the job for me:
Array.prototype.slice.call(document.querySelectorAll("[name='mailId']:checked"),0).map(function(v,i,a) {
return v.value;
});
If you want to get the values of all checkboxes using jQuery, this might help you. This will parse the list and depending on the desired result, you can execute other code. BTW, for this purpose, one does not need to name the input with brackets []. I left them off.
$(document).on("change", ".messageCheckbox", function(evnt){
var data = $(".messageCheckbox");
data.each(function(){
console.log(this.defaultValue, this.checked);
// Do something...
});
}); /* END LISTENER messageCheckbox */
pure javascript and modern browsers
// for boolean
document.querySelector(`#isDebugMode`).checked
// checked means specific values
document.querySelector(`#size:checked`)?.value ?? defaultSize
Example
<form>
<input type="checkbox" id="isDebugMode"><br>
<input type="checkbox" value="3" id="size"><br>
<input type="submit">
</form>
<script>
document.querySelector(`form`).onsubmit = () => {
const isDebugMode = document.querySelector(`#isDebugMode`).checked
const defaultSize = "10"
const size = document.querySelector(`#size:checked`)?.value ?? defaultSize
// 👇 for defaultSize is undefined or null
// const size = document.querySelector(`#size:checked`)?.value
console.log({isDebugMode, size})
return false
}
</script>
Optional_chaining (?.)
You could use following ways via jQuery or JavaScript to check whether checkbox is clicked.
$('.messageCheckbox').is(":checked"); // jQuery
document.getElementById(".messageCheckbox").checked //JavaScript
To obtain the value checked in jQuery:
$(".messageCheckbox").is(":checked").val();
In my project, I usually use this snippets:
var type[];
$("input[name='messageCheckbox']:checked").each(function (i) {
type[i] = $(this).val();
});
And it works well.

how to add the input values in an array

i just like to ask regarding adding data in a array. But the data which i wanted to put is from a table of input boxes.. Here's the code that i've been practicing to get data:
http://jsfiddle.net/yajeig/4Nr9m/69/
I have an add button that everytime I click that button, it will store data in my_data variable.
i want to produce an output in my variable something like this:
my_data = [ {plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"}]
and if i would add another data again, it will add in that variable and it be something like this:
my_data = [ {plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"},
{plank:"2",thickness:"5",width:"6",length:"2",qty:"1",brdFt:"50"}]
the code that i have right now is really bad, so please help.
Currently my output:
1,4,6,4,1
You should be able to iterate over all of the textboxes using the following:
function add(e) {
var obj = {};
$('#addItem input[type="text"]')
.each(function(){obj[this.name] = this.value;});
myItems.push(obj);
}
Where myItems is a global container for your items and #addItem is your form.
Updated jsfiddle.
If you use a form and a submit button then you should be able to implement a non-JavaScript method to add your information so that the site will be accessible to people without JavaScript enabled.
Try this, sorry for modifying your form, but it works well:
HTML:
<form method="post" action="#" id="add_plank_form">
<p><label for="plank_number">Plank number</label>
<p><input type="text" name="plank_number" id="plank_number"/></p>
<p><label for="plank_width">Width</label>
<p><input type="text" name="plank_width" id="plank_width"/></p>
<p><label for="plank_length">Length</label>
<p><input type="text" name="plank_length" id="plank_length"/></p>
<p><label for="plank_thickness">Thickness</label>
<p><input type="text" name="plank_thickness" id="plank_thickness"/></p>
<p><label for="plank_quantity">Quantity</label>
<p><input type="text" name="plank_quantity" id="plank_quantity"/></p>
<p><input type="submit" value="Add"/>
</form>
<p id="add_plank_result"></p>
Javascript:
$(document).ready(function() {
var plank_data = Array();
$('#add_plank_form').submit(function() {
// Checking data
$('#add_plank_form input[type="text"]').each(function() {
if(isNaN(parseInt($(this).val()))) {
return false;
}
});
var added_data = Array();
added_data.push(parseInt($('#plank_number').val()));
added_data.push(parseInt($('#plank_width').val()));
added_data.push(parseInt($('#plank_length').val()));
added_data.push(parseInt($('#plank_thickness').val()));
added_data.push(parseInt($('#plank_quantity').val()));
$('#add_plank_form input[type="text"]').val('');
plank_data.push(added_data);
// alert(JSON.stringify(plank_data));
// compute L x W x F for each plank data
var computed_values = Array();
$('#add_plank_result').html('');
for(var i=0; i<plank_data.length; i++) {
computed_values.push(plank_data[i][1] * plank_data[i][2] * plank_data[i][3] / 12);
$('#add_plank_result').append('<input type="text" name="plank_add[]" value="' + computed_values[i] + '"/>');
}
return false;
});
});
Iterate through all keys, and add the values.
(code written from mind, not tested)
var added = { };
for (var i = 0; i < my_data.length; i ++) {
var json = my_data[i];
for (var key in json) {
if (json.hasOwnProperty(key)) {
if (key in added) {
added[key] += json[key];
} else {
added[key] = json[key];
}
}
}
}
You can use the javascript array push function :
var data = [{plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"}];
var to_add = [{plank:"2",thickness:"5",width:"6",length:"2",qty:"1",brdFt:"50"}];
data = data.concat(to_add);
Sorry I only glanced at the other solutions.
$(document).ready(function() {
var myData=[];
var myObject = {}
$("input").each(function() {
myObject[this.id]=this.value
});
alert(myObject["plank"])
myData.push(myObject)
});

How do you add the values from input fields and update another field with the result in jQuery?

Preamble: I'm more of a PHP/MySQL guy, just starting to dabble in javascript/jQuery, so please excuse this dumb newbie question. Couldn't figure it out from the Docs.
I have a form without a submit button. The goal is to allow the user to input values into several form fields and use jQuery to total them up on the bottom in a div. The form kinda looks like this but prettier:
<form>
Enter Value: <input class="addme" type="text" name="field1" size="1">
Enter Value: <input class="addme" type="text" name="field2" size="1">
Enter Value: <input class="addme" type="text" name="field3" size="1">
etc.....
<div>Result:<span id="result"></span></div>
</form>
Is it possible to add these up? And if so, can it be done anytime one of the input fields changes?
Thanks.
UPDATE:
Brian posted a cool collaborative sandbox so I edited the code to look more like what I have and it's here:
http://jsbin.com/orequ/
to edit go here:
http://jsbin.com/orequ/edit
Sticking this right after the </form> tag should do it:
<script>
function displayTotal() {
var sum = 0
var values = $('.addme').each(function(){
sum += isNaN(this.value) || $.trim(this.value) === '' ? 0 : parseFloat(this.value);
});
$('#result').text(sum);
}
$('.addme').keyup(displayTotal);
</script>
Here's a demo: http://jsbin.com/iboqo (Editable via http://jsbin.com/iboqo/edit)
Any non numeric or blank values will be disregarded in the calculation (they'll be given a value of zero and hence not affect the sum).
function sumValues() {
var sum = 0;
$("input.addme").each(function(){
var $this = $(this);
var amount = parseInt($this.val(), 10);
sum += amount === "" || isNaN(amount)? 0 : amount;
});
$("#result").text(sum);
}
$(function() {
sumValues();
$("input.addme").keyup(function(){
sumValues();
});
});
Working Demo
(function(){
var context = $("form"), elements = $("input.addme", context);
function getSum(elements) {
var sum = 0;
$(elements, context).each( function() {
var v = parseInt(this.value);
v === parseInt(v,10) ? sum += v : sum = sum;
})
return sum;
}
$(elements).bind("keyup", function() {
$("#result").text( getSum(elements) );
});
})();
isolated scope and context, included dealing with non-integer values, function getSum should rather return a value than do something itself.
Try this:
$(".addme").bind("change",function(){
var _sum = 0;
$(".addme").each(function(i){
_sum += parseInt($(this).val());
});
$("#result").val(_sum);
});

Categories