how to pass calculated values using javascript - javascript

the following values are to calculate the user entered values, these are calculated and passed to the text field,
if(computer && monitor && tv && laptop && cell)
{ // getting the text field the values and calculated
var valueCom = document.getElementById("computer").value ;
var valueMon = document.getElementById("monitor").value ;
var valueTv = document.getElementById("tv").value ;
var valueLap = document.getElementById("laptop").value ;
var valueCel = document.getElementById("cell").value;
var finalCom = valueCom * 0.1818937134 ;
var finalMon = valueMon * 0.056842 ;
var finalTv = valueTv * 0.056842 ;
var finalLap = valueLap * 0.090947 ;
var finalCel = valueCel * 0.045473 ;
var totalTonnes = finalCom + finalMon + finalTv + finalLap + finalCel;
var totalCarbon = totalTonnes * 1 ;
var totalTree = totalTonnes * 17.1969 ;
var totalPetrol = totalTonnes * 286.396 ;
var totalPlastic = totalTonnes * 646.421 ;
// pass this above four values to the textfield
}
<input type="text" name="carbon" >
<input type="text" name="tree" >
<input type="text" name="petrol" >
<input type="text" name="plastic" >
// field to pass values here
how to pass this values using java script to the text field. can anyone help me please

you want to add id to text field,
<input type="text" name="carbon" id="carbon">
<input type="text" name="tree" id="tree">
<input type="text" name="petrol" id="petrol">
<input type="text" name="plastic" id="plastic">
then after javascript,
document.getElementById("carbon").value=totalCarbon;
document.getElementById("tree").value=totalTree;
document.getElementById("petrol").value=totalPetrol;
document.getElementById("plastic").value=totalPlastic;
and also you can use to value set by name,
document.getElementsByName("plastic")[0].value = totalPlastic;
......
or,
document.getElementById("plastic").setAttribute('value',totalCarbon);
.....

Assign your resultant text field with id="result" or anything. Then, you can put your result as $(#result).val(yourCalcultedResult);

set the value property
document.getElementById("carbon").value = totalCarbon;
document.getElementById("tree").value = totalTree;
document.getElementById("petrol").value = totalPetrol;
document.getElementById("plastic").value = totalPlastic;
and set the ids to the respective elements
<input type="text" name="carbon" id="carbon" >
<input type="text" name="tree" id="tree" >
<input type="text" name="petrol" id="petrol" >
<input type="text" name="plastic" id="plastic" >
Or if you still want to use names only, then make it
document.getElementsByName("carbon")[0].value = totalCarbon;
document.getElementsByName("tree")[0].value = totalTree;
document.getElementsByName("petrol")[0].value = totalPetrol;
document.getElementsByName("plastic")[0].value = totalPlastic;

document.getElementsByName("carbon")[0].value = totalCarbon;
document.getElementsByName("tree")[0].value = totalTree;
document.getElementsByName("petrol")[0].value = totalPetrol;
document.getElementsByName("plastic")[0].value = totalPlastic;

If your controls are in a form, like:
<form>
<input type="text" name="carbon">
<input type="text" name="tree">
<input type="text" name="petrol">
<input type="text" name="plastic">
...
</form>
then you can get a reference to the form and access them as named properties of the form, e.g.
var form = document.forms[0];
form.carbon.value = totalCarbon;
form.tree.value = totalTree;
...
Just make sure you don't give form controls a name that is the same as a form property, like submit or name, as these will shadow the form's default properties of the same name (so you can't call form.submit() or access the form's name, if it has one).

//globally i declared carbon, tree, petrol, plastic
document.getElementById("carbon").value = carbon ;
document.getElementById("tree").value = tree ;
document.getElementById("petrol").value = petrol ;
document.getElementById("plastic").value = plastic ;

Related

javascript on input field addition

//// JavaScript function to add input values display into another input field
function calculate() {
var x = document.getElementById('fee_selector_holder').value;
var y = document.getElementById('content').value;
var result = document.getElementById('result');
var myResult = x + y;
result.value = myResult;
}
<input type="text" name="hostelfees" id="content" oninput="calculate()">
<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">
<input type="text" id="result" name="totalfee">
I am giving values to input fields its adding concatination but not adding please verify it on input function is correct or wrong once verify then reply me thats it my question.
You have strings, that is why it is concatenating. Make integers with:
http://www.w3schools.com/jsref/jsref_parseint.asp
And it will work well.
First, when you read values from DOM, they are read as string. You will have to use parseInt or parseFloat to convert string to integer.
Second, + operator has a override function for string to act as concatenation operator.
Also notice, I have used .value || 0. Here if value does not exist, performing arithmetic operation over it will return NaN so adding default value (0).
//// JavaScript function to add input values display into another input field
function calculate() {
var x = document.getElementById('fee_selector_holder').value || 0;
var y = document.getElementById('content').value || 0;
var result = document.getElementById('result');
var myResult = parseInt(x) + parseInt(y);
result.value = myResult;
}
<input type="text" name="hostelfees" id="content" oninput="calculate()">
<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">
<input type="text" id="result" name="totalfee">
You have to parse the input values to integer as all input values are string by default:
//// JavaScript function to add input values display into another input field
function calculate() {
var x = document.getElementById('fee_selector_holder').value || 0; // default value 0 if input is blank
var y = document.getElementById('content').value || 0; // default value 0 if input is blank
var result = document.getElementById('result');
var myResult = parseInt(x, 10) + parseInt(y, 10); // parse it here
result.value = myResult;
}
<input type="text" name="hostelfees" id="content" oninput="calculate()">
<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">
<input type="text" id="result" name="totalfee">
You should add attribute to result
result.setAttribute("value", myResult);

JavaScript form same values

How can I make a form so they cannot repeat the same values in the Input?
I tried a way like:
var text1 = document.getElementById('num1').value;
var text2 = document.getElementById('num1').value;
var textform = [text1,text2];
if (
text1 == text2 ||
text2 == text1
) {
alert("repeated numbers");
return false;
}
But this is gets me into two troubles:
- If I put no value, it will say: Repated Numbers
- If I want to make this for 100 form values, it takes a lot of code
You could give all of your text elements the same class, and grab their values by class name to simplify building the array of text values.
<input type="text" class="checkDupe" id="input1" />
<input type="text" class="checkDupe" id="input2" />
Then grab their values in javascript
var checkDupes = document.getElementsByClassName('checkDupe');
var textArray = [];
for(var i = 0; i < checkDupes.length; i++){
textArray.push(checkDupes[i].value);
}
Now that we have an array of values that they entered, check to see if any of them repeat by sorting the array, and seeing if any two elements side-by-side are the same.
textArray.sort();
var dupes = false;
for(var i = 0; i < textArray.length; i++){
if(textArray[i] === textArray[i + 1]) dupes = true;
}
If we find any duplicates, let the user know.
if(dupes) alert('Repeated numbers!');
You could do something like this:
var text1 = document.getElementById('num1').value;
var text2 = document.getElementById('num2').value;
var textform = [text1, text2];
var seen = {};
textform.forEach(function(value) {
if (seen[value]) {
alert('Bad!');
}
seen[value] = true;
});
In the code above, we loop over each value in the array. The first time we encounter it, we push it into a map. Next time (if) we hit that value, it will exist in the map and it will tell us we've seen it before.
If you give all the input's a common class then you quickly loop through them.
The HTML:
<input type="text" name="num1" class="this that number"></input>
<input type="text" name="num2" class="this number"></input>
<input type="text" name="num3" class="that number"></input>
<input type="text" name="num4" class="number"></input>
<input type="text" name="num5" class=""></input> <!-- we don't want to check this one -->
<input type="text" name="num6" class="number that this"></input>
<input type="text" name="num7" class="this that number"></input>
The JavaScript:
// get all the inputs that have the class numbers
var ins = document.querySelectorAll("input.numbers");
// a tracker to track
var tracker = {};
// loop through all the inputs
for(var i = 0, numIns = ins.length; i < numIns; ++i)
{
// get the value of the input
var inValue = ins[i].value.trim();
// skip if there is no value
if(!inValue) continue;
// if the value is already tracked then let the user know they are a bad person
// and stop
if(tracker[inValue])
{
alert("You are a bad person!");
return;
}
// track the value
tracker[inValue] = true;
}
You could also enhance this to let the user know which inputs have duplicate values:
// get all the inputs that have the class numbers
var ins = document.querySelectorAll("input.numbers");
// a tracker to track
var tracker = {};
// loop through all the inputs
for(var i = 0, numIns = ins.length; i < numIns; ++i)
{
// get the value of the input
var inValue = ins[i].value.trim();
// skip if there is no value
if(!inValue) continue;
// if the value is already tracked then error them
if(tracker[inValue])
{
// mark the current input as error
ins[i].className += " error";
// mark the first found instance as an error
ins[tracker[inValue]].className += " error";
}
// save the index so we can get to it later if a duplicate is found
tracker[inValue] = i;
}
Here's a way of doing it that automatically picks up all the text inputs in your document and validates based on what you're looking for. Would be simple enough to expose the valid value and make this the validation handler (or part of one) that handles a form submission.
<meta charset="UTF-8">
<input id="num1" type="text" value="foobar1">
<input id="num2" type="text" value="foobar2">
<input id="num3" type="text" value="foobar3">
<input id="num4" type="text" value="foobar4">
<input id="num5" type="text" value="foobar5">
<button onClick="checkValues();">Validate</button>
<script>
function checkValues() {
var inputs = document.getElementsByTagName('input');
arrInputs = Array.prototype.slice.call(inputs);
var valid = true;
var valueStore = {};
arrInputs.forEach(function(input) {
if (input.type == 'text') {
var value = input.value.toUpperCase();
if (valueStore[value]) {
valid = false;
} else {
valueStore[value] = true;
}
}
});
if (valid) {
alert('Valid: No matching values');
} else {
alert('Invalid: Matching values found!');
}
}
</script>
With jquery you can iterate directly over the inputs.
<form>
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<button>
TEST
</button>
</form>
function checkValues(){
var used = {};
var ok = true;
$('form input[type="text"]').each(function(){
var value = $(this).val();
if(value !== ""){
if(used[value] === true){
ok = false;
return false;
}
used[value] = true;
}
});
return ok;
}
$('button').click(function(event){
event.preventDefault();
if(!checkValues()){
alert("repeated numbers");
};
});
https://jsfiddle.net/8mafLu1c/1/
Presumably the inputs are in a form. You can access all form controls via the form's elements collection. The following will check the value of all controls, not just inputs, but can easily be restricted to certain types.
If you want to include radio buttons and checkboxes, check that they're checked before testing their value.
function noDupeValues(form) {
var values = Object.create(null);
return [].every.call(form.elements, function(control){
if (control.value in values && control.value != '') return false;
else return values[control.value] = true;
});
}
<form id="f0" onsubmit="return noDupeValues(this);">
<input name="inp0">
<input name="inp0">
<input name="inp0">
<button>Submit</button>
</form>
For old browsers like IE 8 you'll need a polyfill for every.
You can simply get all inputs iterate them twice to check if they are equals
var inputs = document.getElementsByTagName('input');
for (i = 0; i < inputs.length; i++) {
for (j = i + 1; j < inputs.length; j++) {
if (inputs[i].value === inputs[j].value) {
console.log('value of input: ' + i + ' equals input: ' + j);
}
}
}
<input value="56" />
<input value="12" />
<input value="54" />
<input value="55" />
<input value="12" />

Count values from <input type="text"

Hello i want to count the ids inside a input type="text"
the values return as this 1,4,6 etc
<input type="hidden" class="selected_ids" value="selected_ids" name="selected_ids[]" multiple="yes" id="selected_ids" />
here the only javascript version :
var testme = function() {
var myInput = document.getElementById('selected_ids');
var myValue = myInput.value;
var myCount = myValue.split(',').length;
document.body.innerHTML += '<br>myValue = ' + myValue + ' | myCount = ' + myCount;
}
<input type="text" class="selected_ids" value="1,4,6" name="selected_ids[]" multiple="yes" id="selected_ids" />
<button onclick='testme()'>test me</button>
You can use split function. for example :
var curval = document.getElementById('selected_ids').value;
var curval_arr = curval.split(',');
var cnt = curval_arr.length;
First, your input type needs to be text and not hidden. It's not possible to enter values in a hidden text box.
So your text box should be :-
<input type="text" class="selected_ids" value="selected_ids" name="selected_ids[]" multiple="yes" id="selected_ids" />
Now suppose the user enters 1,4,6 into the text box(make sure the numbers are separated by a comma). Then on the PHP side you can access as follows.
<?php
$array = explode(',', $_POST['selected_ids']); //this array consists all the elements.
//To get length, do :-
count($array);
?>

Creating Id using javascript

I want to create staffid from three different textboxes values by getting their first letter & adding auto increment number atlast.
eg "staffname", "gender", "designation" result staffid: sgd01 & I want to auto display in the staff id textbox while staffid textbox is disabled. Here is the code below:
<input name="staffname" id="staffname" size="30" type="text" value placeholder=" Staff Name" onkeyup="quick()" class="formTxtInput">
Script
function quick() {
var gender = document.getElementById('gender').value;
var staffname = document.getElementById('staffname');
var desg = document.getElementById('desg').value;
var gen = gender.charAt(0);
var sn = staffname.charAt(0);
var dg = desg.charAt(0);
var val = gen + sn + dg;
document.getElementById('staffid').value = val;
}
You have a missing .value for var staffname. It should be
var staffname = document.getElementById('staffname').value;
Also your function needs to be called on every keyup on each of the 3 input boxes so that updated values can be processed
Here is a working sample: http://jsbin.com/vobikejejo/1/
Hope this helps :)
You can try by updating your function as below:
<script>
var num=01;
function quick() {
num+=1;
var gender = document.getElementById('gender').value;
var staffname = document.getElementById('staffname').value;
var desg = document.getElementById('desg').value;
var gen = gender.charAt(0);
var sn = staffname.charAt(0);
var dg = desg.charAt(0);
var val = gen + sn + dg + num;
document.getElementById('staffid').value = val;
}
By default there is no value, so it is not working. Try by setting the default value.
<input name="staffname" id="staffname" size="30" type="text" value="staffname" placeholder=" Staff Name" onkeyup="quick()" class="formTxtInput">
<input name="gender" id="gender" size="30" type="text" value="gender" placeholder=" Staff Name" class="formTxtInput">
<input name="desg" id="desg" size="30" type="text" value="desg" placeholder=" Staff Name"class="formTxtInput">
<input name="staffid" id="staffid" size="30" disabled="disabled" type="text" value placeholder=" Staff Name" class="formTxtInput">
YOu can view demo here 1

from a html form to javascript

I have a form that requires three inputs as follows:
<form>
<input name="mn"
type="number"
min="1"
value="1">
<input name="mx"
type="number"
min="2"
value="10">
<input name="step"
type="number"
min="1"
value="1">
<input onclick="myfunc()"
type="submit"
value="calculate">
</form>
all i require is to be able to access the three fields directly in javascript. I do not need to pass the information anywhere else.
Could anyone point me in the right direction? I have read examples where there has been one input, but not multiple.
<script type="text/javascript">
function myfunc() {
var mn = document.getElementsByName("mn")
var mx = document.getElementsByName("mx")
var step = document.getElementsByName("step")
alert((mn + mx) / step)
}
</script>
Give your form an id like so
<form id="myForm">
The other thing to watch out for is that the is that the value attribute is a string so adding the two values concatenates them rather than summing them.
Try instead
var frm = document.forms["myForm"];
var _mn = parseInt( frm["mn"].value );
var _mx = parseInt( frm["mx"].value );
var _step = parseInt( frm["step"].value );
var result = ( _mn + _mx ) / _step;
I'd start with giving each input an id then i could use:
var min = document.getElementById('mn')
and so on. To access the value you simply would call
min.value
Also there is no point in removing the i from min and the a from max. That is not optimized just hard to read and understand.
Try this:
<script type="text/javascript">
function myfunc() {
var mn = document.getElementsByName("mn")[0].value;
var mx = document.getElementsByName("mx")[0].value;
var step = document.getElementsByName("step")[0].value;
var top = mn / mx;
alert(top / step);
}
</script>
if u need to access to the values of the inputs change your code to:
function myfunc() {
var mn = document.getElementsByName("mn")[0];
var mx = document.getElementsByName("mx")[0];
var step = document.getElementsByName("step")[0];
// you may need to validate your values here, like step.value != 0
alert((mn.value + mx.value) / step.value)
}

Categories

Resources