Adding Values in Html - html

I am creating an HTML Invoice. The system we use outputs the data to html in HTML. I put the relevant tag (such as {{order_purchasedate}}) and the values are displayed there instead.
I need the invoice to display the total order weight for all items in the order. The weights will be displayed as numbers in a list for example "60 80 120" with just a space separating them.
How can I add the numbers is html and only display the total?
I know I could use Java but I am not familiar with this. If someone could help that would be great.
Ben
*edit I have made an attempt at the code. I am struggling getting the output. I am sure you guys must think me an idiot!
<!DOCTYPE html>
<html>
<body>
<h1>Invoice</h1>
<p id="order_weight"></p>
<script>
getTotal = function(values){
var total = values.split(" ").reduce(function(a,b){
a = parseInt(a)
b = parseInt(b)
return a+b
});
return total
}
document.getElementById("order_weight").innerHTML = getTotal(a+b);
</script>
</body>
</html>

You can use JavaScript to take your values and calculate total value.
getTotal = function(values){
var total = values.split(" ").reduce(function(a,b){
a = parseInt(a)
b = parseInt(b)
return a+b
});
return total
}
and then just call that function
getTotal(x)
where x is your list
Here is the working example:
http://jsfiddle.net/o89f1mj5/1/

<body>
<h1>Invoice</h1>
<p id="order_weight"></p>
<input id="total" name="total" type="text"></input>
<input id="totalBtn" type="button" value="Get Total" onClick="getTotal();"></input>
</body>
<script>
function getTotal() {
var values = $('#total').val();
alert(values);
var total = values.split(" ").reduce(function(a,b){
var a = parseInt(a);
var b = parseInt(b);
return a+b;
});
document.getElementById('order_weight').innerHTML = "Value: " + total;
}
</script>
Working JS Fiddle: http://jsfiddle.net/o89f1mj5/9/
In the JSFiddle put "5 15 30" into the text box (without the quote of course) and it will make the paragraph be 50
This is what #mgibala did above using a Textbox and a Button. His answer should be accepted I am just giving you it in application with a variable input option.

Related

Validate the sum of three input fields in HTML

I am trying to to validate the sum of three input fields in HTML to be exactly 100. The Code I found on Stackoverflow for two input fields works only for two fields and not for my modification for three (below is my attempt of the modified code). The original code can be found at Validate sum of two input fields
I am most grateful for any help or advice! Here is my code
<html>
<head>
<script> src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<input type="text" class="input" id="value1">
<input type="text" class="input" id="value2">
<input type="text" class="input" id="value3">
<button type="submit" name="submit" id="submit">check sum</button>
<p id="resultMessage"></p>
<script>
$(document).ready(function() {
// on button pressed
$('#submit').on('click', function() {
var val1 = $("#value1").val();
var val2 = $("#value2").val();
var val3 = $("#value3").val();
// numeric validation
if (!isNumeric(val1) || !isNumeric(val2) || !isNumeric(val3)) {
$('#resultMessage').text('Some field does not contain a number');
return;
}
// + operator converts input Strings to Number type
var sum = +val1 + +val2 + +val3;
if (sum > 100) {
// if sum greather than 100
$('#resultMessage').text('Sum is greather than 100 (' + sum + ')');
} else if (sum < 100) {
// some code if sum less than 100 ...
$('#resultMessage').text('Sum is less than 100 (' + sum + ')');
} else {
// sum is 100
$('#resultMessage').text('Sum equals 100');
}
});
// function for numeric validation
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
});
</script>
</body>
</html>
My problem is that the modification does not work and I don't see why..
EDIT Per the comments, I have removed the extra parenthesis around !isNumeric(val2).
The problem still persists though. I see the three text boxes and a check sum button. However, whenever I enter any numbers and hit "check sum", nothing happens, no computation of any sum and no display of any sum.
I would be very grateful for any additional comments.

How to create a matrix table to get and save integer values for future calculation

<head>
<script>
function generate() {
var a = parseInt(document.getElementById("nochapter").value);
var ch = document.getElementById("ch");
for (i = 0; i < a; i++) {
var input = document.createElement("input");
ch.appendChild(input);
}
}
</script>
</head>
<body>
<h1> Prepare new assessment</h1>
<form>
No. of Chapter included
<input type="text" id="nochapter" />
<input type="button" value="set" onclick="generate()" />
<div id="ch"></div>
</form>
</body>
This code is used to get input from users based on the parameters which they have given in textboxes. I have to create an n*n matrix table to get the values for them.
Please help.Thanks in advance.
You almost have it already.
I presume you want to make a n*n matrix table of inputs?
If that is the case then just wrap your current loop in another loop that creates the rows.
Here is a working codepen demo
Id basically adds a new row for every n like
var row = document.createElement("div");
and adds your loop to that row.

Dynamically adding selected scale item values

I am creating a form in which I have added few items of type SCALE and I want the user to select from a scale of 1 to 3.
Now I want to dynamically add all these selected values such as the sum = selected value of scaleA + ..scaleB+ ..ScaleN.
So far I have managed to get all the SCALE items, but I am unable to get the value that use has currently selected.
The API gives only following methods getUpperBound() and getLowerBound() where as I want to get the value the user has currently selected.
Is there a way I can achieve this?
Note: I want to display the user the sum of selected value right away as he is filling in the form.
The piece of code that I have written so far
function myFunction() {
var form = FormApp.getActiveForm();
var items = form.getItems(FormApp.ItemType.SCALE);
for (var i = 0; i < items.length; i++)
Logger.log(items[i].getId() + ':Title ' + items[i].getTitle()+ ':ScaleItem '+items[i].asScaleItem());
}
To make a dynamic form you will have to use google apps scripts to create your own from using HTML service. Like So: https://script.google.com/macros/s/AKfycby5b0Q2cuDSTl8VDIG60-9lnklAgeaZlXwmZq2slRG4h-fx6og/exec
Native form application from google cannot be used for making a dynamic form that updates while the form is live.
Html File: "ScaleForm", code source: http://www.w3schools.com/tags/tag_output.asp
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div id = "formDiv">
<form id = "scaleForm" oninput="x.value=parseInt(a.value)+parseInt(b.value)">
0
<input type="range" id="a" name="a" value="0" min ="0" max ="3">
3 <br>
+ <br> 0
<input type="range" id="b" name="b" value="0" min ="0" max ="3">
3 <br>
=
<output id = "c" name="x" for="a b"></output> <br>
<input type ="button" value ="Submit" onclick ="formSubmit()">
</form>
</div>
<br>
Values Submitted shown Below:
<div id="submittedValue">
</div>
<script>
function formSubmit(){
var formvalues = []
var d = new Date();
formvalues[0] = d.toString();
formvalues[1] = document.getElementById("a").value
formvalues[2] = document.getElementById("b").value
formvalues[3] = document.getElementById("c").value
var sub = document.getElementById("submittedValue")
sub.innerHTML = "Value 1: " +formvalues[1] +"<br>Value 2: "+formvalues[2] +"<br>Total: "+formvalues[3]
google.script.run.recordValues(formvalues)
}
</script>
</body>
</html>
Google Script code:
function doGet() {
return HtmlService.createTemplateFromFile('ScaleForm')
.evaluate()
.setTitle('Scale Form for stack overflow');
}
function recordValues(formvalues){
var scale1 =formvalues[0]
var scale2 = formvalues[1]
var sum = formvalues[2]
// The above assignments are for reference sake only they are not used
var Ss = SpreadsheetApp.openById("Paste your Spreadsheet ID here to record the values")
var Sheet = Ss.getSheetByName("Responses")
Sheet.appendRow(formvalues)
}
How to run this:
In scripts.google.com create a script file and an HTML file named "ScaleForm".
Copy the HTML code the HTML file and script to the script file.
Use publish menu to deploy this as a web app and you should be good to go.
More details on web App can be found here: https://developers.google.com/apps-script/guides/web

how to get left word of the selected word in javascript

As an example that we have
Name : Abdul Naeem
if we select the Naeem from above so to get Abdul From it.......
is it possible to get the left side words of the selected words
i tried but i have not found this..... can any body help me out of this problem.
i found some tips where it only get the selected words but i need the words on its left side
Get the Highlighted/Selected text
for example lets consider if an object weighs 30 N. now i want to select the 30, and get the word weighs from it ?? how can i do it in javascript –
It is nontrivial, mainly because of the hierarchical nature of the document.
A restricted functionality which will get you the previous word as long as it is in the same element, in non-IE browsers:
// get the selection
var sel = window.getSelection();
// get the element in which the selection is made, and the start and end position
var node = sel.anchorNode;
var from = sel.anchorOffset;
// let's see what's before the selection
var textBeforeWord = node.textContent.substring(0, from);
var match = textBeforeWord.match(/(\w+)\s+/);
var previousWord = match[1];
This gets much more complicated when you consider the possibility that a word could be the first thing in its element, or that a selection might be across elements, when you would need to navigate the DOM hierarchy to hunt the previous element. It is also complicated by the fact that you would need to do it twice, completely differently (since IE's API is totally different).
EDIT In case of a <textarea> element, it gets much simpler, as you don't need to worry about the selection spilling over the element. For IE you will have to do some gymnastics, since it does not support selectionStart, as described here.
var node = document.getElementById('mytextarea');
var from = node.selectionStart;
var textBeforeWord = node.textContent.substring(0, from);
// the rest is the same as above
Let assume these first :
all text in textbox = Abdul Naeem
currently selected text = ul Naeem
currently unselected text = Ab
Now, from your question, you only want to get the unselected text right, which is in this case is Ab? Then make three variable like this :
var allText = ... // get it from your textbox value
var selectedText = ... // try to get it using your link location
var unselectedText = allText.replace(selectedText, '');
Then you get the unselectedText. Thanks & Regards.
note just tested it in **CHROME, it will display all words to left to "SELECTED" Word
You need to modify it a little bit according to your need, just try
//console.log(window.getSelection().focusNode.data);
var textSelected = window.getSelection().toString();
var fulltext = window.getSelection().focusNode.data;
console.log(fulltext.substr(0,fulltext.length-textSelected.length));
I found the question quite interesting and thus I tried to do it with the help of Javascript. I wouldnt call it a good code but it does what you require Abdul. Providing you the whole code along with html page. You will have a lot of alert messages to help you debug and understand my code. I have modified an existing code, Please ignore what seems irrelevant to you. Only the name field shall be required to carry out the tests. Do let me know if you need clarifications.
While testing, please select the text so that you dont select a space along with the word, which usually happens when selecting with a double click.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script>
function getPreviousWord()
{
alert("inside getPreviousWord");
var sel = window.getSelection().toString();
alert("selected word is: "+ sel);
var x=document.getElementById("1111");
alert("x= " +x);
var currentTag=x.tagName;
alert("Current tagname is: "+currentTag);
currentTag=currentTag.toLowerCase();
alert("Current tagname (lowered) is: "+currentTag);
var completeList=document.getElementsByTagName(currentTag);
var converted=completeList.toString();
alert("complete List is: "+completeList);
alert ("coneverted = "+converted);
var cur=0;
var next=0;
var i=0;
var word1="";
var word2="";
var j=0;
var found= false;
for(i=0;i<completeList.length;i++)
{
var temp=completeList[i].value.toString()+" ";
alert("temp= "+temp);
for(j=0;j<temp.length;j++)
{
if(temp.substring(j,j+1)==" ")
{
alert("Blank space found");
next=j;
alert("next= "+j);
word1=word2;
word2=temp.substring(cur,next);
alert("word1= "+word1 +" and word2= "+ word2);
cur=j+1;
if(word2==sel)
{
alert("previous word is: "+ word1);
found= true;
break;
}
else
{
alert("sel!=temp");
}
}
}
if(found==true)
{
alert("Breaking outer loop");
break;
}
}
}
</script>
<title>Hello World</title>
</head>
<body bgcolor="beige">
<h1>Employee Details</h1>
<form action="hello" name="frm" onSubmit="return validate()">
<label>Please enter your name</label><br/>
<input type="text" name="name" id="1111" onselect="getPreviousWord()"/><font size="4" color="red"> <div id="error"> </div></font>
<br/>
<label id="abc">Employee ID:</label><br/>
<input type="text" name="empId"/><br/>
<label>Email Id:</label><br/>
<input type="text" name="email">
<br/>
<label>Phone Number:</label><br/>
<input type="text" name="phone">
<br/>
<br/>
<br/>
<input type= "button" value="Check" onclick="return validate()">
<input type="submit" value="Submit"/>
<s:fielderror>
<s:param> name</s:param>
</s:fielderror>
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the array values after the split.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Abdul Naeem";
var res = str.split(" ");
for(i=0;i<res.length;i++)
{
alert(res[i]);
}
//document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
Try This in JS with Jquery :
var a="Name : Abdul Naeem";
var sp="Naeem";
$(function(){
var x=a.split(sp);
z=x[0].split(" ");
alert(z[z.length-2]);
});
Demo in JSFIDDLE

How to get data into html checkbox list, taken from javascript function call

I have a page which assign some values to arrays when a function named 'hndlr' is called.code of the file is given bellow
<html>
<head>
<title>Search Example</title>
</head>
<body>
<script>
var pageName = new Array();
var pageLink = new Array();
var pageDetails = new Array();
function hndlr(response) {
// here I assign values to arrays pageName,pageLink,pageDetails using a for loop
}
// Some codes (I cant change anything in here)
// call the function hndlr here (I cant change anything in here)
</script>
</body>
</html>
I want to take pageName array into a checkbox list and pass the pageLink of selected checkboxes to another file.
I tried using bellow code just before the end of the body tag. but it isn't passing any data to next page(b.php)
<form action="b.php" method="post">
<script>
for (var j = 0; j < 5; j++) {
document.write("<input type='checkbox' name='formDoor[]' id='"+j+"' value= '' />"+pageName[j]+"<br />");
document.getElementById(j).value = pageLink[j];
}
</script>
<input type="submit" name="formSubmit" value="Submit" />
</form>
When I print the output, It displays 'undefined' strings just before the check boxes.
That means pageName[j] doesn't return any value.
problem is, these arrays are not visible to second part(part I tried with check boxes)
Please show me the way to do this..
Weird, your code is working for me (click the code box to show it): http://codepad.viper-7.com/4IVobE
You can't submit the form on this site but you can see that the arrays are accessible within the second script tag. I also tried it on my local server and after submitting the form I was able to access the values in b.php just fine.