What is wrong with my code? - javascript

I'm having trouble with my code but can't seem to find what the problem is. I keep getting the same errors in browser but I don't see what the problem is?
FVOM.js:16 Uncaught SyntaxError: Unexpected number
FVOM.html:15 Uncaught ReferenceError: CheckSelection is not defined
HTML code:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Future Value Demo</title>
<link rel="stylesheet" type="text/css" href="css/index.css"/>
<script type="text/javascript" src="JScripts/FVOM.js"></script>
</head>
<body>
<table>
<tr>
<td colspan="2">
<input type="radio" id="futVal" name="Money" checked onClick="FVOM:CheckSelection(1)"/>Future Value
<input type="radio" id="preVal" name="Money" onClick="FVOM:CheckSelection(2)"/>Present Value
<input type="radio" id="rate" name="Money" onClick="FVOM:CheckSelection(3)"/>Rate of Interest
<input type="radio" id="time" name="Money" onClick="FVOM:CheckSelection(4)"/>Years
</td>
</tr>
</table>
<br/>
<table>
<tr>
<td>Future Value (FV)</td>
<td><input type="text" id="FV" disabled/></td>
</tr>
<tr>
<td>Present Value (PV)</td>
<td><input type="text" id="PV" value = "1500" /></td>
</tr>
<tr>
<td>Interest Rate [pa] (r)</td>
<td><input type="text" id="R" value = "4.5"/></td>
</tr>
<tr>
<td>Years (n)</td>
<td><input type="text" id="N" value = "1"/></td>
</tr>
<tr>
<td>Compounded</td>
<td>
<select id="compounded">
<option value="year">Yearly</option>
<option value="quarter">Quarterly</option>
<option value="month">Monthly</option>
</select>
</td>
</tr>
<tr>
<td><input type="button" id="reset" value="RESET"/></td>
<td><input type="button" id="calculate" value="Calculate"/></td>
</tr>
</table>
<br/>
<hr/>
<br/>
<div id="results">
</div>
</body>
JavaScript:
var $ = function(id){
return document.getElementById(id);
};
var futureValue = function(){
var pv = parseFloat($("PV").value);
var r = parseFloat($("R").value);
var n = parseFloat($("N").value);
if(isNaN(pv) || isNaN(r) || isNaN(n)){
alert("Please enter a valid number");
}
else{
r = r/100/Compounded();
n = n*Compounded();
$("FV").value=(pv*Math.pow((1+r), n)).toFixed(2);
var res = "<table border="1"><tr><th>Period</th><th>Investment</th><th>Year End</th></tr>";
for(var i=1; i<=n; i++){
res+="<tr><td>"+i+"</td><td>€"+(pv).toFixed(2)+"</td><td>€"+(pv*Math.pow((1+r), 1)).toFixed(2)+"</td></tr>";
pv = pv*Math.pow((1+r), 1);
}
res+="</table>";
$("results").innerHTML = res;
}
};
var presentValue = function(){
var fv = parseFloat($("FV").value);
var r = parseFloat($("R").value);
var n = parseFloat($("N").value);
if(isNaN(fv) || isNaN(r) || isNaN(n))
alert("Please enter numbers");
else{
r = r/100/Compounded();
n = n*Compounded();
$("PV").value=(fv/Math.pow((1+r), n)).toFixed(2);
}
};
var rateOfInterest = function(){
var fv = parseFloat($("FV").value);
var pv = parseFloat($("PV").value);
var n = parseFloat($("N").value);
if(isNaN(fv) || isNaN(pv) || isNaN(n))
alert("Please enter numbers");
else{
n = n*Compounded();
$("R").value=((Math.pow((fv/pv),(1/n))-1)*100*Compounded()).toFixed(2)+"%";
}
};
var numberOfYears = function(){
var fv = parseFloat($("FV").value);
var pv = parseFloat($("PV").value);
var r = parseFloat($("R").value);
if(isNaN(fv) || isNaN(pv) || isNaN(r))
alert("Please enter numbers");
else{
r = r/100/Compounded;
$("N").value=(((Math.log(fv)-Math.log(pv))/Math.log(1 + r)))n/Compounded()).toFixed(2);
}
};
var Compounded = function(){
var com = $("compounded").value;
if(com=="year")
return 1;
if(com=="quarter")
return 4;
if(com=="month")
return 12;
};
var calculate = function(){
if($("futVal").checked)
futureValue();
if($("preVal").checked)
presentValue();
if($("rate").checked)
rateOfInterest();
if($("time").checked()
numberOfYears();
};
var CheckSelection = function(id){
if(id==1){
$("FV").disabled = true;
$("PV").disabled = false;
$("R").disabled = false;
$("N").disabled = false;
}
else if(id==2){
$("FV").disabled = false;
$("PV").disabled = true;
$("R").disabled = false;
$("N").disabled = false;
}
else if(id==3){
$("FV").disabled = false;
$("PV").disabled = false;
$("R").disabled = true;
$("N").disabled = false;
}
else{
$("FV").disabled = false;
$("PV").disabled = false;
$("R").disabled = false;
$("N").disabled = true;
}
RESET();
};
var RESET = function(){
$("FV").value = "";
$("PV").value = "";
$("R").value = "";
$("N").value = "";
$("results").innerHTML = "";
};
window.onload = function(){
$("calculate").onClick = calculate;
$("reset").onClick = RESET;
};
I'm fairly new to JavaScript so any help would be greatly appreciated.

var res = "<table border="1"><tr><th>Period</th><th>Investment</th><th>Year End</th></tr>";
is where the problem lies. You need to escape the " (double quotes) that exist in border="1" by either using a \" or by using single quotes '
For this reason some people use single quotes in javascript to assign a string, that way you do not need to escape the double quotes. If you would like to read more about strings in javascript there is a decent introduction at http://www.w3schools.com/js/js_strings.asp

Related

AppsScript -> WebApp -> Event listeners don't work if element added after DOMContentLoaded?

I have a webapp that retrieves from a Google sheet an array of values to dynamically create a table so if the array retrieved has four items, then the table has four rows, and so on.Each row has as first column item a toggle to disables the other columns' input fields for that row.
It looks like this:
I initially created everything statically, just to get it working first, with five sample rows, and got every thing working, the toggle worked and disabled and cleared content, etc. However, as I wrote in the part to dynamically create the table rows and the event listeners for each toggle, the toggle stopped responding, even though the function for each is named correctly according to the dynamically created event listeners.
These rows are done in the javascript for the page, using this statement:
document.addEventListener('DOMContentLoaded', setup_ui);
After creating the table rows and before the end of the setup_ui function, I create the event listeners for each toggle.
// Next we need to create event listeners to make the toggles usables
for(var i = 0; i < domains_count; i++){
let number = i+1;
let domain_toggle = `domain${number}`;
let function_name = `switch_for_dom${number}`;
document.getElementById(domain_toggle).addEventListener("click",function_name);
}
You see, at this point, I do have the rows created, they show up, all appears well. And yet, if I do
alert(document.getElementById("domain1"))
It doesn't find it... even though its in front of me and I can right click on the page, go into dev tools and see it there.
The code for the function handling the toggle is there below in the file, here's the first function for the first toggle.
function switch_for_dom1(){
let check = document.getElementById("domain1");
if(check.checked == true){
document.getElementById("first_name_domain1").disabled = false;
document.getElementById("last_name_domain1").disabled = false;
document.getElementById("email_domain1").disabled = false;
document.getElementById("phone_domain1").disabled = false;
document.getElementById("position_domain1").disabled = false;
document.getElementById("role_domain1").disabled = false;
}else{
document.getElementById("first_name_domain1").disabled = true;
document.getElementById("last_name_domain1").disabled = true;
document.getElementById("email_domain1").disabled = true;
document.getElementById("phone_domain1").disabled = true;
document.getElementById("position_domain1").disabled = true;
document.getElementById("role_domain1").disabled = true;
document.getElementById("first_name_domain1").value = "";
document.getElementById("last_name_domain1").value = "";
document.getElementById("email_domain1").value = "";
document.getElementById("phone_domain1").value = "";
document.getElementById("position_domain1").value = "";
document.getElementById("role_domain1").value = "Role";
}
}
How can I not only create those table rows dynamically, as I have done here, but also have the event listeners I create dynamically actually work with the functions that are later down in that js file?
I will have to eventually have the functions to handle the toggles created dynamically as well and I have no clue at this point.
To replicate this you'd need yourself a new AppScript project webapp.
Here's the code for my html and js.
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?!= include('menu-css'); ?>
<?!= include('users-css'); ?>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
</head>
<body class="body">
<?!= include('menu'); ?>
<div class="user-create-form">
<h5 id="title"> Create User</h5> </br>
<div class="row g-3">
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="first name" aria-label="first name" id="first_name">
</div>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="last name" aria-label="last name" id="last_name">
</div>
<div class="col-sm">
<input type="text" class="form-control" placeholder="email" aria-label="email" id="email">
</div>
</div>
</br>
<div class="row g-3">
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="Phone number" aria-label="Phone number" id="phone">
</div>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="Company Position" aria-label="Company Position" id="position">
</div>
<div class="col-sm">
<select class="form-select" aria-label="Default select example" id="role">
<option selected>Role</option>
<option value="1">Superuser</option>
<option value="2">Requester</option>
<option value="3">Reporter</option>
<option value="4">Receiver</option>
<option value="5">Purchaser</option>
<option value="6">Finance</option>
<option value="7">Approver</option>
<option value="8">Peasant</option>
</select>
</div>
</div>
</br>
<div class="toggles">
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="alldomains">
<label class="form-check-label" for="flexSwitchCheckDefault">All Domains</label>
</div>
<table class="table w-auto">
<thead>
<tr>
<th scope="col" class="col col-auto">
Domains
</th>
<th scope="col">
First name
</th>
<th scope="col">
Last name
</th>
<th scope="col">
Email
</th>
<th scope="col">
Phone number
</th>
<th scope="col">
company position
</th>
<th scope="col">
Role
</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
<?!= include('menu-js'); ?>
<?!= include('users-js'); ?>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
</body>
</html>
And now the Javascript:
<script>
document.addEventListener('DOMContentLoaded', setup_ui);
function setup_ui(){
var count = 4;
document.getElementById("title").innerHTML = `Create a User across any number of your ${count} domains`;
create_table();
document.getElementById("alldomains").click();
document.getElementById("alldomains").click();
}
google.script.run.withSuccessHandler(create_table).get_domains_names();
function create_table(domains_names){
var domains_count = domains_names.length;
var row_html;
if(domains_count > 0){
var table = document.getElementById("tbody");
var table_body = table.innerHTML;
for(var i = 0; i < domains_count; i++){
let domain = domains_names[i];
let number = i+1;
row_html = `
<tr>
<td>
<div class="form-check form-switch form-check-inline">
<input class="form-check-input" type="checkbox" id="domain${number}">
<label class="form-check-label" for="flexSwitchCheckDefault">${domain}</label>
</div>
<td>
<input type="text" class="form-control" placeholder="first name" aria-label="first name" id="first_name_domain${number}">
</td>
<td>
<input type="text" class="form-control" placeholder="last name" aria-label="last name" id="last_name_domain${number}">
</td>
<td>
<input type="text" class="form-control" placeholder="email" aria-label="email" id="email_domain${number}">
</td>
<td>
<input type="text" class="form-control" placeholder="Phone number" aria-label="Phone number" id="phone_domain${number}">
</td>
<td>
<input type="text" class="form-control" placeholder="Company Position" aria-label="Company Position" id="position_domain${number}">
</td>
<td>
<select class="form-select" aria-label="Default select example" id="role_domain${number}">
<option selected>Role</option>
<option value="1">Superuser</option>
<option value="2">Requester</option>
<option value="3">Reporter</option>
<option value="4">Receiver</option>
<option value="5">Purchaser</option>
<option value="6">Finance</option>
<option value="7">Approver</option>
<option value="8">Peasant</option>
</select>
</td>
</tr>
`;
let row = document.createElement("tr");
row.innerHTML = row_html;
tbody.appendChild(row);
}
// Next we need to create event listeners to make the toggles usables
for(var i = 0; i < domains_count; i++){
let number = i+1;
let domain_toggle = `domain${number}`;
let function_name = `switch_for_dom${number}`;
document.getElementById(domain_toggle).addEventListener("click",function_name);
}
// Next we need to create the functions to provide the functionality for each toggles
}else{ // no domains (they need to add the domains)
}
}
document.getElementById("alldomains").addEventListener("click",applyAllDomains);
function applyAllDomains(){
document.getElementById("domain1").click();
document.getElementById("domain2").click();
document.getElementById("domain3").click();
document.getElementById("domain4").click();
document.getElementById("domain5").click();
switch_for_dom1();
switch_for_dom2();
switch_for_dom3();
switch_for_dom4();
switch_for_dom5();
}
document.getElementById("first_name").addEventListener("input",map_first_name);
document.getElementById("last_name").addEventListener("input",map_last_name);
document.getElementById("email").addEventListener("input",map_email);
document.getElementById("phone").addEventListener("input",map_phone);
document.getElementById("position").addEventListener("input",map_position);
document.getElementById("role").addEventListener("input",map_role);
function map_first_name(){
alert("here");
var fn = document.getElementById("first_name").value;
if(document.getElementById("first_name_domain1").disabled == false){
document.getElementById("first_name_domain1").value = fn;
}
if(document.getElementById("first_name_domain2").disabled == false){
document.getElementById("first_name_domain2").value = fn;
}
if(document.getElementById("first_name_domain3").disabled == false){
document.getElementById("first_name_domain3").value = fn;
}
if(document.getElementById("first_name_domain4").disabled == false){
document.getElementById("first_name_domain4").value = fn;
}
if(document.getElementById("first_name_domain5").disabled == false){
document.getElementById("first_name_domain5").value = fn;
}
}
function map_last_name(){
var fn = document.getElementById("last_name").value;
if(document.getElementById("last_name_domain1").disabled == false){
document.getElementById("last_name_domain1").value = fn;
}
if(document.getElementById("last_name_domain2").disabled == false){
document.getElementById("last_name_domain2").value = fn;
}
if(document.getElementById("last_name_domain3").disabled == false){
document.getElementById("last_name_domain3").value = fn;
}
if(document.getElementById("last_name_domain4").disabled == false){
document.getElementById("last_name_domain4").value = fn;
}
if(document.getElementById("last_name_domain5").disabled == false){
document.getElementById("last_name_domain5").value = fn;
}
}
function map_email(){
var fn = document.getElementById("email").value;
if(document.getElementById("email_domain1").disabled == false){
document.getElementById("email_domain1").value = fn;
}
if(document.getElementById("email_domain2").disabled == false){
document.getElementById("email_domain2").value = fn;
}
if(document.getElementById("email_domain3").disabled == false){
document.getElementById("email_domain3").value = fn;
}
if(document.getElementById("email_domain4").disabled == false){
document.getElementById("email_domain4").value = fn;
}
if(document.getElementById("email_domain5").disabled == false){
document.getElementById("email_domain5").value = fn;
}
}
function map_phone(){
var fn = document.getElementById("phone").value;
if(document.getElementById("phone_domain1").disabled == false){
document.getElementById("phone_domain1").value = fn;
}
if(document.getElementById("phone_domain2").disabled == false){
document.getElementById("phone_domain2").value = fn;
}
if(document.getElementById("phone_domain3").disabled == false){
document.getElementById("phone_domain3").value = fn;
}
if(document.getElementById("phone_domain4").disabled == false){
document.getElementById("phone_domain4").value = fn;
}
if(document.getElementById("phone_domain5").disabled == false){
document.getElementById("phone_domain5").value = fn;
}
}
function map_position(){
var fn = document.getElementById("position").value;
if(document.getElementById("position_domain1").disabled == false){
document.getElementById("position_domain1").value = fn;
}
if(document.getElementById("position_domain2").disabled == false){
document.getElementById("position_domain2").value = fn;
}
if(document.getElementById("position_domain3").disabled == false){
document.getElementById("position_domain3").value = fn;
}
if(document.getElementById("position_domain4").disabled == false){
document.getElementById("position_domain4").value = fn;
}
if(document.getElementById("position_domain5").disabled == false){
document.getElementById("position_domain5").value = fn;
}
}
function map_role(){
var fn = document.getElementById("role").value;
if(document.getElementById("role_domain1").disabled == false){
document.getElementById("role_domain1").value = fn;
}
if(document.getElementById("role_domain2").disabled == false){
document.getElementById("role_domain2").value = fn;
}
if(document.getElementById("role_domain3").disabled == false){
document.getElementById("role_domain3").value = fn;
}
if(document.getElementById("role_domain4").disabled == false){
document.getElementById("role_domain4").value = fn;
}
if(document.getElementById("role_domain5").disabled == false){
document.getElementById("role_domain5").value = fn;
}
}
function switch_for_dom1(){
let check = document.getElementById("domain1");
if(check.checked == true){
document.getElementById("first_name_domain1").disabled = false;
document.getElementById("last_name_domain1").disabled = false;
document.getElementById("email_domain1").disabled = false;
document.getElementById("phone_domain1").disabled = false;
document.getElementById("position_domain1").disabled = false;
document.getElementById("role_domain1").disabled = false;
}else{
document.getElementById("first_name_domain1").disabled = true;
document.getElementById("last_name_domain1").disabled = true;
document.getElementById("email_domain1").disabled = true;
document.getElementById("phone_domain1").disabled = true;
document.getElementById("position_domain1").disabled = true;
document.getElementById("role_domain1").disabled = true;
document.getElementById("first_name_domain1").value = "";
document.getElementById("last_name_domain1").value = "";
document.getElementById("email_domain1").value = "";
document.getElementById("phone_domain1").value = "";
document.getElementById("position_domain1").value = "";
document.getElementById("role_domain1").value = "Role";
}
}
function switch_for_dom2(){
let check = document.getElementById("domain2");
if(check.checked == true){
document.getElementById("first_name_domain2").disabled = false;
document.getElementById("last_name_domain2").disabled = false;
document.getElementById("email_domain2").disabled = false;
document.getElementById("phone_domain2").disabled = false;
document.getElementById("position_domain2").disabled = false;
document.getElementById("role_domain2").disabled = false;
}else{
document.getElementById("first_name_domain2").disabled = true;
document.getElementById("last_name_domain2").disabled = true;
document.getElementById("email_domain2").disabled = true;
document.getElementById("phone_domain2").disabled = true;
document.getElementById("position_domain2").disabled = true;
document.getElementById("role_domain2").disabled = true;
document.getElementById("first_name_domain2").value = "";
document.getElementById("last_name_domain2").value = "";
document.getElementById("email_domain2").value = "";
document.getElementById("phone_domain2").value = "";
document.getElementById("position_domain2").value = "";
document.getElementById("role_domain2").value = "Role";
}
}
function switch_for_dom3(){
let check = document.getElementById("domain3");
if(check.checked == true){
document.getElementById("first_name_domain3").disabled = false;
document.getElementById("last_name_domain3").disabled = false;
document.getElementById("email_domain3").disabled = false;
document.getElementById("phone_domain3").disabled = false;
document.getElementById("position_domain3").disabled = false;
document.getElementById("role_domain3").disabled = false;
}else{
document.getElementById("first_name_domain3").disabled = true;
document.getElementById("last_name_domain3").disabled = true;
document.getElementById("email_domain3").disabled = true;
document.getElementById("phone_domain3").disabled = true;
document.getElementById("position_domain3").disabled = true;
document.getElementById("role_domain3").disabled = true;
document.getElementById("first_name_domain3").value = "";
document.getElementById("last_name_domain3").value = "";
document.getElementById("email_domain3").value = "";
document.getElementById("phone_domain3").value = "";
document.getElementById("position_domain3").value = "";
document.getElementById("role_domain3").value = "Role";
}
}
function switch_for_dom4(){
let check = document.getElementById("domain4");
if(check.checked == true){
document.getElementById("first_name_domain4").disabled = false;
document.getElementById("last_name_domain4").disabled = false;
document.getElementById("email_domain4").disabled = false;
document.getElementById("phone_domain4").disabled = false;
document.getElementById("position_domain4").disabled = false;
document.getElementById("role_domain4").disabled = false;
}else{
document.getElementById("first_name_domain4").disabled = true;
document.getElementById("last_name_domain4").disabled = true;
document.getElementById("email_domain4").disabled = true;
document.getElementById("phone_domain4").disabled = true;
document.getElementById("position_domain4").disabled = true;
document.getElementById("role_domain4").disabled = true;
document.getElementById("first_name_domain4").value = "";
document.getElementById("last_name_domain4").value = "";
document.getElementById("email_domain4").value = "";
document.getElementById("phone_domain4").value = "";
document.getElementById("position_domain4").value = "";
document.getElementById("role_domain4").value = "Role";
}
}
function switch_for_dom5(){
let check = document.getElementById("domain5");
if(check.checked == true){
document.getElementById("first_name_domain5").disabled = false;
document.getElementById("last_name_domain5").disabled = false;
document.getElementById("email_domain5").disabled = false;
document.getElementById("phone_domain5").disabled = false;
document.getElementById("position_domain5").disabled = false;
document.getElementById("role_domain5").disabled = false;
}else{
document.getElementById("first_name_domain5").disabled = true;
document.getElementById("last_name_domain5").disabled = true;
document.getElementById("email_domain5").disabled = true;
document.getElementById("phone_domain5").disabled = true;
document.getElementById("position_domain5").disabled = true;
document.getElementById("role_domain5").disabled = true;
document.getElementById("first_name_domain5").value = "";
document.getElementById("last_name_domain5").value = "";
document.getElementById("email_domain5").value = "";
document.getElementById("phone_domain5").value = "";
document.getElementById("position_domain5").value = "";
document.getElementById("role_domain5").value = "Role";
}
}
</script>
The problem is function_name is a string, rather than the reference to a function.
May I propose you do the following.
const switch_for_dom1 = function () { }
const switch_for_dom2 = function () { }
etc.
Then in
function create_table(domains_names){
.
.
.
let dom_functions = [switch_for_dom1,switch_for_dom2,....];
// Next we need to create event listeners to make the toggles usables
for(var i = 0; i < domains_count; i++){
let number = i+1;
let domain_toggle = `domain${number}`;
let function_name = dom_functions[i];
document.getElementById(domain_toggle).addEventListener("click",function_name);
}
}

Conversion between different versions of BT.601,BT.709 and RGB

Since the color-space conversion confused me ago, I have created this tool to easy conversion between different versions of BT.601,BT.709 and RGB.
But I still not sure if I should use floor or round to calculate the conversion result. please help comment then I will improve this tool.
A601v1 = [[0.257, 0.504, 0.098],
[-0.148, -0.291, 0.439],
[0.439, -0.368, -0.071]];
O601v1 = [[16, 128, 128]];
A601v2 = [[0.299, 0.587, 0.114],
[-0.173, -0.339, 0.511],
[0.511, -0.428, -0.083]];
O601v2 = [[16, 128, 128]];
A601v3 = [[0.299, 0.587, 0.114],
[-0.169, -0.331, 0.500],
[0.500, -0.419, -0.081]];
O601v3 = [[0, 128, 128]];
A709v1 = [[0.1826, 0.6142, 0.0620],
[-0.1006, -0.3386, 0.4392],
[0.4392, -0.3989, -0.0403]];
O709v1 = [[16, 128, 128]];
A709v2 = [[0.2126, 0.7152, 0.0722],
[-0.1146, -0.3854, 0.5000],
[0.5000, -0.4542, -0.0468]];
O709v2 = [[0, 128, 128]];
A = A601v1;
O = O601v1;
function combo(thelist) {
var idx = thelist.selectedIndex;
var colspace = thelist.options[idx].value;
if (colspace === "BT.601v1") {
A = A601v1;
O = O601v1;
}else if (colspace === "BT.601v2") {
A = A601v2;
O = O601v2;
}else if (colspace === "BT.601v3") {
A = A601v3;
O = O601v3;
}else if (colspace === "BT.709v1") {
A = A709v1;
O = O709v1;
}else if (colspace === "BT.709v2") {
A = A709v2;
O = O709v2;
}
}
function yuv2rgb(f) {
var y, u, v,r,g,b, yuv,rgb,offset;
y = parseInt(f.y.value);
u = parseInt(f.u.value);
v = parseInt(f.v.value);
yuv = [[y,u,v]];
Ainv = math.inv(A);
yuv = math.subtract(yuv,O);
rgb = math.multiply(yuv,math.transpose(Ainv))
rgb = math.round(rgb);
rgb = clip(rgb,0,255);
r = rgb[0][0];
g = rgb[0][1];
b = rgb[0][2];
f.red.value = r;
f.green.value = g;
f.blue.value = b;
var yuvElem = document.getElementById('yuv');
yuvElem.src = getDataUrl(r,g,b);
}
function rgb2hex(r,g,b) {
var v;
if (g !== undefined) {
v = Number(0x1000000 + r*0x10000 + g*0x100 + b).toString(16).substring(1);
}else {
v = Number(0x1000000 + r[0][0]*0x10000 + r[0][1]*0x100 + r[0][2]).toString(16).substring(1);
}
return "#" + v;
}
function clip(m1,low,high) {
var result = [];
for (var i = 0; i < m1.length; i++) {
result[i] = [];
for (var j = 0; j < m1[0].length; j++) {
if (m1[i][j] < low) {
result[i][j] = low;
}else if (m1[i][j] > high) {
result[i][j] = high;
}else{
result[i][j] = m1[i][j];
}
}
}
return result;
}
function rgb2yuv(f) {
var y, u, v, r, g, b,yuv,rgb,offset;
r = parseInt(f.red.value);
g = parseInt(f.green.value);
b = parseInt(f.blue.value);
rgb = [[r,g,b]];
yuv = math.multiply(rgb,math.transpose(A));
yuv = math.add(yuv,O);
yuv = math.round(yuv);
yuv = clip(yuv,0,255);
f.y.value = yuv[0][0];
f.u.value = yuv[0][1];
f.v.value = yuv[0][2];
var yuvElem = document.getElementById('yuv');
yuvElem.src = getDataUrl(r,g,b);
}
function getDataUrl(r,g,b) {
var canvas = document.createElement('canvas');
var height=100;
var width=100;
canvas.height=height;
canvas.width=width;
var context = canvas.getContext("2d");
var imageData=context.createImageData(width, height);
var data = imageData.data;
for (var i=0; i<height*width; i++) {
data[i*4+0] = r | 0;
data[i*4+1] = g | 0;
data[i*4+2] = b | 0;
data[i*4+3] = 255;
}
context.putImageData(imageData, 0, 0);
var url = canvas.toDataURL("image/png");
return url;
}
<!DOCTYPE html>
<html>
<head>
<title>yuv rgb converter</title>
</head>
<body>
<form name="yuv2rgb_form">
<label for="colspace">Color space:</label>
<select name="colspace" onChange="combo(this)">
<option>BT.601v1</option>
<option>BT.601v2</option>
<option>BT.601v3</option>
<option>BT.709v1</option>
<option>BT.709v2</option>
</select>
<table border="1">
<tr>
<td>
<table border="0">
<tr>
<td>Red</td>
<td><input type="text" name="red" value="0" size=5></td>
</tr>
<tr>
<td>Green</td>
<td><input type="text" name="green" value="0" size=5></td>
</tr>
<tr>
<td>Blue</td>
<td><input type="text" name="blue" value="0" size=5></td>
</tr>
<tr>
<td><input type="button" value="rgb2yuv" onclick="rgb2yuv(this.form);"></td>
</tr>
</table>
</td>
<td>
<table>
<tr>
<td>Y</td>
<td><input type="text" name="y" value="0" size=5></td>
</tr>
<tr>
<td>U</td>
<td><input type="text" name="u" value="0" size=5></td>
</tr>
<tr>
<td>V</td>
<td><input type="text" name="v" value="0" size=5></td>
</tr>
<tr>
<td><input type="button" value="yuv2rgb" onclick="yuv2rgb(this.form);"></td>
</tr>
</table>
</td>
<td><Image id="yuv" style="width:100px; height:100px;"></div></td>
</tr>
</table>
</form>
</body>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.2.1/math.js"></script>
</html>

remove node from xml and save it using Javascript or Jquery

I have tried the last post example which works fine with IE from this link
How to write data from Form in HTML to XML with Javascript
but i would like to add a button 'delete' to remove each time a node of xml
using Javascript or Jquery. These examples don't work for me.
http://www.w3schools.com/xml/met_element_removechild.asp. Any one can help?
<!DOCTYPE html>
<html>
<head>
<title>Display Emp Details</title>
<script type="text/javascript" language="javascript">
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var FILENAME='D:\\example.xml';
function SaveXMLData()
{
validations();
}
function createfile()
{
var file;
var e1=document.getElementById('empName').value;
var p1=document.getElementById('empNumber').value;
var em1=document.getElementById('empEmail').value;
var d1=document.getElementById('empDate').value;
var tablemain = document.getElementById('tblmain');
if(fso.fileExists(FILENAME))
{
xmlDoc.load(FILENAME);
var lng;
lng=xmlDoc.getElementsByTagName("Details");
var xmlread= fso.OpenTextFile(FILENAME,1,true,0);
var x=xmlread.readAll();
var replace=x.replace('</Emp>','');
var sno=lng.length + 1;
file=fso.OpenTextFile(FILENAME,2,true);
file.writeLine(replace);
file.WriteLine('<Details category="'+sno+'">');
file.WriteLine('<SNo>'+sno+'</SNo>');
file.WriteLine('<Name>'+e1+'</Name>');
file.WriteLine('<PhoneNumber>'+p1+'</PhoneNumber>');
file.WriteLine('<Emailid>'+em1+'</Emailid>');
file.WriteLine('<Date>'+d1+'</Date>');
file.WriteLine('</Details>');
file.WriteLine('</Emp>');
alert('another file updated');
}
else
{
file= fso.CreateTextFile(FILENAME, true);
file.WriteLine('<?xml version="1.0" encoding="utf-8" ?>');
file.WriteLine('<?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?>');
file.WriteLine('<Emp>');
file.WriteLine('<Details category="1">');
file.WriteLine('<SNo>'+1+'</SNo>');
file.WriteLine('<Name>'+e1+'</Name>');
file.WriteLine('<PhoneNumber>'+p1+'</PhoneNumber>');
file.WriteLine('<Emailid>'+em1+'</Emailid>');
file.WriteLine('<Date>'+d1+'</Date>');
file.WriteLine('</Details>');
file.WriteLine('</Emp>');
alert('file updated');
}
<!-- displayData();-->
document.getElementById('empName').value='';
document.getElementById('empNumber').value='';
document.getElementById('empEmail').value='';
document.getElementById('empDate').value='';
addRow('tablemain');
file.close();
}
function validations()
{
var emp1=document.getElementById('empName').value;
var letters = /^[\s A-Za-z]+$/;
if(emp1!="")
{
if(emp1.match(letters))
{
allnumeric();
}
else
{
alert('Please input alphabet characters only');
return false;
}
}
else
{
alert('Please Enter Name.');
}
}
<!--For checking Email-->
function checkemail()
{
var email = document.getElementById('empEmail');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(email.value!="")
{
if (!filter.test(email.value))
{
alert('Please provide a valid email address');
return false;
}
else
{
DateValidation();
}
}
else
{
alert('Please Enter Email.');
}
}
<!--For checking Date Format-->
function DateValidation()
{
var date=/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{2,4}$/;
var empDate=document.getElementById("empDate");
if(empDate.value!="")
{
if(empDate.value.match(date))
{
createfile();
}
else
{
alert("Please provide valid date : DD-MM-YY(YYYY)");
return(false);
}
}
else
{
alert('Please Enter Date.');
}
}
<!--For checking phone number-->
function allnumeric()
{
var numbers=/^\d{10}$/;
var empNumber=document.getElementById("empNumber");
if(empNumber.value!="")
{
if(empNumber.value.length=="10")
{
if(empNumber.value.match(numbers))
{
checkemail();
}
else
{
alert("Phone number should be numeric");
return(false);
}
}
else
{
alert('Phone Number should be like: 9876543210');
}
}
else
{
alert('Please Enter Phone Number.');
}
}
function addRow(id)
{
if(fso.fileExists(FILENAME))
{
xmlDoc.load(FILENAME);
var x;
x=xmlDoc.getElementsByTagName("Details");
var table = document.getElementById('tbl');
var nxtbtn= document.getElementById("btnnext");
var prvbtn=document.getElementById("btnprev");
nxtbtn.disabled=true;
prvbtn.disabled=true;
if(x.length >5)
{
nxtbtn.disabled=false;
}
var j=0;k=5;
if(k>x.length)
{k=x.length;}
var store=document.getElementById("txtstore");
var maxval=document.getElementById("txtmax");
if(id=="btnprev")
{
if((store.value % k)==0)
{
store.value = store.value - k ;
if(store.value>0)
{
j = parseInt(store.value);
k += parseInt(store.value);
}
}
else
{
store.value =store.value - (store.value % k) ;
if(store.value >0)
{
j = store.value - k;
k = store.value;
}
}
if(j > 0)
{
prvbtn.disabled=false;
}
}
if(id=="btnnext")
{
if(store.value==0)
{
store.value=table.rows.length;
}
else if(store.value <0)
{
store.value=maxval.value;
}
prvbtn.disabled=false;
if(store.value >=k)
{
j +=parseInt(store.value);
k +=parseInt(store.value);
if(k >= x.length)
{
k=x.length;
nxtbtn.disabled = true;
prvbtn.disabled = false;
}
}
}
table.innerHTML = "";
var rowCount = 0;
for (i=j;i<k;i++)
{
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.id = "id2" ;
cell1.appendChild(element1);
// Create label
var label = document.createElement("label");
label.htmlFor = "id2" ;
cell1.appendChild(label);
var cell2 = row.insertCell(1);
cell2.innerHTML = x[i].getElementsByTagName("SNo")[0].childNodes[0].nodeValue;
var name = row.insertCell(2);
var elname =document.createElement("input");
elname.type = "text";
elname.readOnly=true;
elname.value=x[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue;
name.appendChild(elname);
var phnno = row.insertCell(3);
var elphn =document.createElement("input");
elphn.type = "text";
elphn.readOnly=true;
elphn.value=x[i].getElementsByTagName("PhoneNumber")[0].childNodes[0].nodeValue;
phnno.appendChild(elphn);
var email = row.insertCell(4);
var elemail =document.createElement("input");
elemail.type = "text";
elemail.readOnly=true;
elemail.value=x[i].getElementsByTagName("Emailid")[0].childNodes[0].nodeValue;
email.appendChild(elemail);
var date = row.insertCell(5);
var eldate =document.createElement("input");
eldate.type = "text";
eldate.readOnly=true;
eldate.value=x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue;
date.appendChild(eldate);
rowCount +=1;
}
maxval.value=x[table.rows.length - 1].getElementsByTagName("SNo")[0].childNodes[0].nodeValue;
if(id=="btnprev")
{
store.value =store.value - 5;
}
else
{
store.value =parseInt(k);
}
}
}
</script>
</head>
<body onload="addRow('tbl')">
<form id="empForm" action="" method="get">
<p><b>Emp Registration:</b></p>
<table>
<tr>
<td>Name:</td>
<td><input type="text" id="empName" maxlength="25"/></td>
</tr>
<tr>
<td>Phone Number:</td>
<td><input type="text" id="empNumber" maxlength="10"/></td>
</tr>
<tr>
<td>EmailId:</td>
<td><input type="text" id="empEmail"/></td>
</tr>
<tr>
<td>Date:</td>
<td><input type="text" id="empDate" maxlength="10"/></td>
</tr>
<tr>
<td align="center">
<input type="button" value="Submit" onclick="SaveXMLData()"/></td>
<td>
<input type="button" value="Show Data" id="show" onclick="displayData(this.id)" style="display:none;"/></td>
</tr>
</table>
<!-- <table><tr><td><input type="button" onclick="displayData(this.id)" value="Prev" id="prev" disabled="disabled"></td>
<td><input type="button" onclick="displayData(this.id)" value="Next" id="next" disabled="disabled"></td></tr></table> -->
<div id='displaydatadiv'>
</div>
<!-- <INPUT type="button" value="Add Row" onclick="addRow('tbl')" /> -->
<div style="height: 135px; width:650px; background-color: Lavender;" >
<TABLE id="tbl" width="350px">
</TABLE>
</div>
<table id="tblmain" border="1" style="display:true" ></table>
<input type="button" id="btnprev" value="Prev" onclick="addRow(this.id)" disabled="disabled">
<input type="button" id="btnnext" value="Next" onclick="addRow(this.id)" disabled="disabled">
<input type="hidden" id="txtstore" style="display:none;">
<input type="hidden" id="txtmax" style="display:none;">
</body>
</html>

Get Javascript calculator to do an equation like (5-3+2) with only 2 number inputs

I'm making this Javascript Calculator and I can't figure out how to get the calculator to do a problem like 5-(3+1), 5-3+1.
It only prints the 5-3 part of the equation not the +1
Here is my code:
<html>
<script>
function calc()
{
var D = "";
var A = document.getElementById("num1").value;
var B = document.getElementById("op").value;
var C = parseInt(document.getElementById("num2").value);
if(B == "+")
{
D = parseInt(A)+parseInt(C);
}
else if(B == "-")
{
D = parseInt(A)-parseInt(C);
}
else if(B == "*")
{
D = parseInt(A)*parseInt(C);
}
else if(B == "/")
{
D = parseInt(A)/parseInt(C);
}
else
{
alert("Error")
}
document.getElementById("result").value = parseInt(D);
}
function conteq()
{
var D = document.getElementById("result").value;
var E = "";
document.getElementById("num1").value = D;
document.getElementById("op").value = E;
document.getElementById("num2").value = E;
document.getElementById("result").value = E;
}
function resetcalc()
{
var E = "";
document.getElementById("num1").value = E;
document.getElementById("op").value = E;
document.getElementById("num2").value = E;
document.getElementById("result").value = E;
}
</script>
<body>
<table align="center">
<td>This is a basic Javascript Calculator.<br /></td></table>
<table align="center"><td>(Number 1)<input type="text" id="num1" align="middle" name="num1" />
</td>
<table align="center"><td>(Operator)<input type="text" align="middle" id="op" name="op" /></td> </table>
<table align="center"> <td>(Number 2)<input type="text" align="middle" id="num2" name="num2" /></td> </table>
<table align="center"> <td><input type="button" align="middle" value="=" onClick="calc()" /></td> </table>
<table align="center"><td>(Result)<input type="text" id="result" name="result" readonly />
</td></table>
<table align="center"><td><input type="button" value="Set Answer to Number 1" onClick="conteq()" /></td></table>
<table align="center"><td><input type="button" value="Reset" onClick="resetcalc()" /></td></table>
</table>
</p>
</body>
</html>
You're trying to convert ( to an integer, and you can't (because it isn't):
function calc()
{
var D = "";
var A = document.getElementById("num1").value;
var B = document.getElementById("op").value;
var C = document.getElementById("num2").value;
D = eval(A + B + C);
document.getElementById("result").value = D;
}

validation form in table mode with javascript

i made my form in table mode
like this:
<form name="register" method="post" action="#" onSubmit="return validasi()">
<table width="507" border="0">
<h1 class="title">Form Perubahan Password</h1>
<tr>
<td width="190" ><span id="usernameerror" class="style20">Masukkan Username </span></td>
<td width="319"><input name="username" type="text"></td>
</tr>
<tr>
<td><span id="passworderror" class="style20">Masukkan Password Lama</span></td>
<td><input name="pass" type="password"></td>
</tr>
<tr>
<td><span id="password1error" class="style20">Masukkan Password Baru</span></td>
<td><input name="pass1" type="password"></td>
</tr>
<tr>
<td><span id="password2error" class="style20">Ulangi Masukkan Password Baru</span></td>
<td><input name="pass2" type="password"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Submit">
<input type="reset" name="reset" value="Reset"></td>
</tr>
</table>
</form>
and this my validation code with javascript. check it out..
<script language="javascript">
function checkName(register)
{
var eobj = document.getElementById('usernameerror');
var susername = register.username.value;
var oRE = /^[a-z0-9]+[_.-]?[a-z0-9]+$/i;
var error = false;
eobj.innerHTML = '';
if (susername == '') {
error = 'Error: Username tidak boleh kosong';
register.username.focus();
}
else if (!oRE.test(susername))
{
error="Salah format";
}
if (error)
{
register.username.focus();
eobj.innerHTML = error;
return false;
}
return true;
}
function validatePwd(register) /* old password verification */
{
var eobj = document.getElementById('passworderror');
var invalid = ' ';
var pw = register.pass.value;
var error = false;
eobj.innerHTML = '';
if (pw.length < 1)
{
error = 'Masukkan password anda';
}
else if (pw.indexOf(invalid) > -1)
{
error = 'Anda harus mengisi password';
}
if (error)
{
register.pass.focus();
eobj.innerHTML = error;
return false
}
return true;
}
function validatePwd1(register) /* password & retype-password verification */
{
var eobj1 = document.getElementById('password1error');
var eobj2 = document.getElementById('password2error');
var invalid = ' ';
var pw1 = register.pass1.value;
var pw2 = register.pass2.value;
var error = false;
eobj1.innerHTML = '';
eobj2.innerHTML = '';
if (pw1.length < 1)
{
error = 'Masukkan password anda';
}
else if (pw1.indexOf(invalid) > -1)
{
error = 'Anda harus mengisi password';
}
if (error)
{
register.pass1.focus();
eobj1.innerHTML = error;
return false
}
if (pw1 != pw2)
{
eobj2.innerHTML = ' password tidak sama, coba masukkan kembali password anda';
return false;
}
return true;
}
function validasi()
{
var form = document.forms['register'];
var ary = [checkName, validatePwd, validatePwd1];
var rtn = true;
var z0 = 0;
for (var z0 = 0; z0 < ary.length; z0++)
{
if (!ary[z0](form))
{
rtn = false;
}
}
return rtn;
}
</script>
When i use this validation in usually form its work But in table mode that's validation code doesn't work..help me to solve this problem...tq
view demo
http://jsfiddle.net/andricoga/u9eZz/
You have declared onSubmit="return validasi()" in form , but where you defined function for that. for validation working you need to define function for that.
function validasi(){
// validation code goes here
}
In your validatePwd() function replace
eobj1.innerHTML = error;
with
eobj.innerHTML = error;
you have not defined this eobj1 object and hence it is causing a run time javascript error.
I changed the code to display the error beside the field, try this out
Javascript
<script language="javascript">
function checkName()
{
var obj = document.getElementById('usernameerror');
var susername = document.getElementById('username').value;
var oRE = /^[a-z0-9]+[_.-]?[a-z0-9]+$/i;
var error = false;
obj.innerHTML = '';
if (susername == '') {
error = 'Username can not be empty';
}
else if (!oRE.test(susername))
{
error = 'One format';
}
if (error)
{
document.getElementById('username').focus();
obj.innerHTML = error;
return false;
}
return true;
}
function validatePwd() /* password & retype-password verification */
{
var obj = document.getElementById('pwderror');
var invalid = ' ';
var pw = document.getElementById('pass').value;
var error = false;
obj.innerHTML = '';
if (pw.length < 1)
{
error = 'Enter your old password';
}
else if (pw.indexOf(invalid) > -1)
{
error = 'You need a password';
}
if (error)
{
document.getElementById('pass').focus();
obj.innerHTML = error;
return false
}
return true;
}
function validatePwd1() /* password & retype-password verification */
{
var obj = document.getElementById('pwd1error');
var invalid = ' ';
var pw1 = document.getElementById('pass1').value;
var pw2 = document.getElementById('pass2').value;
var error = false;
obj.innerHTML = '';
if (pw1.length < 1)
{
error = 'Enter your new password';
}
else if (pw1.indexOf(invalid) > -1)
{
error = 'You need a password';
}
if (error)
{
document.getElementById('pass1').focus();
obj.innerHTML = error;
return false
}
if (pw1 != pw2)
{
obj.innerHTML = 'passwords are not the same, try to re-enter your password';
return false;
}
return true;
}
function validate()
{
var form = document.forms['register'];
var ary = [checkName, validatePwd, validatePwd1];
var rtn = true;
var z0 = 0;
for (var z0 = 0; z0 < ary.length; z0++)
{
if (!ary[z0](form))
{
rtn = false;
}
}
return rtn;
}
</script>
Form
<form name="register" method="post" action="#" onSubmit="return validate()">
<table border="0">
<tr>
<td colspan="2">
<h1 class="title">Password Change Form</h1>
</td>
</tr>
<tr>
<td><span class="style20">Username </span></td>
<td><input name="username" id="username" type="text"></td>
<td><span id="usernameerror" class="style20"> </span></td>
</tr>
<tr>
<td><span class="style20">Old Password</span></td>
<td><input name="pass" id="pass" type="password"></td>
<td><span id="pwderror" class="style20"> </span></td>
</tr>
<tr>
<td><span class="style20">New Password</span></td>
<td><input name="pass1" id="pass1" type="password"></td>
<td><span id="pwd1error" class="style20"> </span></td>
</tr>
<tr>
<td><span class="style20">Repeat New Password</span></td>
<td><input name="pass2" id="pass2" type="password"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Submit">
<input type="reset" name="reset" value="Reset"></td>
</tr>
</table>
</form>

Categories