So I have a project to create a webpage that accepts user input on one page and displays it in a table on another page. I know at least some of the local storage is working because I called the 'textvalue' and it always has the user input correct. I can't seem to figure out why I can't get the data to display on the table though.
This is the code that I have to the page that takes the user input and throws it into local storage.
#page
#model RSVPModel
#{
ViewData["Title"] = "RSVP";
}
<h1>#ViewData["Title"]</h1>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content=" width=device-width, initial-scale=1.0" />
<title>RSVP</title>
<link rel="stylesheet" type=" text/css" href="style.css" />
<script>
function getDetails() {
var name = document.getElementById("name").value;
localStorage.setItem("textvalue", name);
var age = document.getElementById("age").value;
localStorage.setItem("agevalue", age);
var arrtime = document.getElementById("arrtime").value;
localStorage.setItem("timevalue", arrtime);
var parking = document.getElementById("parking").value;
localStorage.setItem("parkingvalue", parking);
return false;
if (!name || !age || !arrtime || !parking) {
alert("Please fill all fields before proceeding");
return;
}
}
</script>
</head>
<body>
<div id=" container">
<div class=" input">Name: <input id="name" type="text" /></div>
<div class=" input">Age: <input id="age" type="number" /></div>
<div class=" input">Arrival Time: <input id="arrtime" type="time" /></div>
<label for="parking">Request Parking?</label>
<select name="parking" id="parking">
<option value=""></option>
<option value="yes">yes</option>
<option value="no">no</option>
</select>
<form action="Submitted">
<input type="submit" id="submit" value="Submit RSVP" onclick="getDetails();"/>
</form>
</div>
</body>
</html>
After the input page hitting the submit button will take them to a thank you page where they can navigate to the table page via a link on the page or the nav bar at the top of the page. Here is the code for that page.
#page
#model SubmittedModel
#{
ViewData["Title"] = "RSVP Submitted";
}
<body>
<div class="text-center">
<h1 class="display-4">Thank you <span id="result"></span>!</h1>
<p>It's great that you're coming. The drinks are already in the fridge!</p>
<p>Click here to see who is coming.</p>
</div>
<script>
document.getElementById("result").innerHTML = localStorage.getItem("textvalue");
</script>
</body>
And this is the code I have for the page that tries to take that out of local storage, assign it to a variable, and then display it in the table.
#page
#model PrivacyModel
#{
ViewData["Title"] = "Here is a list of people attending the party";
}
<h1>#ViewData["Title"]</h1>
<body>
<script>
var row = 1;
var submit = document.getElementById('submit');
submit.addEventListener("click", displayDetails);
function displayDetails() {
document.getElementById("guestName").innerHTML = localStorage.getItem("textvalue");
document.getElementById("guestAge").innerHTML = localStorage.getItem("agevalue");
document.getElementById("arrivalTime").innerHTML = localStorage.getItem("timevalue");
document.getElementById("parkingRequest").innerHTML = localStorage.getItem("parkingvalue");
var display = document.getElementById("display");
var newRow = display.insertRow(row);
var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);
var cell3 = newRow.insertCell(2);
var cell4 = newRow.insertCell(3);
cell1.innerHTML = guestName;
cell2.innerHTML = guestAge;
cell3.innerHTML = arrivalTime;
cell4.innerHTML = parkingRequest;
row++;
}
</script>
<table id="display">
<tr>
<th>Name</th>
<th>Age</th>
<th>Arrival Time</th>
<th>Request Parking</th>
</tr>
</table>
</body>
I couldn't really find any information on a process like this, so I'm trying to piece together like 3 different tutorials. I might just need some fresh eyes to spot a simple mistake or I could be doing it completely wrong. Any help would be greatly appreciated.
I am not sure what happened on you code. If the following code is working, maybe you can modify it.
<body>
<div>
<span>Test</span><input type="text" id="input_test" size="14" value="new">
</div>
<div>
<button type="button" id="save">Save</button>
</div>
<div>
<button type="button" id="load">Load</button>
</div>
<table id="table_test">
<tr>
<th>test</th>
</tr>
</table>
</body>
<script>
let save = document.getElementById('save');
save.addEventListener("click", saveDetails);
function saveDetails() {
localStorage.setItem("Test", document.getElementById('input_test').value);
}
let load = document.getElementById('load');
load.addEventListener("click", loadDetails);
function loadDetails() {
let t = document.getElementById('table_test');
let r = t.insertRow(1);
let c = r.insertCell(0);
c.innerHTML = localStorage.getItem("Test");
}
</script>
Related
hello I'm working on a simple project where a user inputs the information and it goes into a table. I want the user to have the ability to put in the URL for an image and have it show up when the cell is made in the table. I have a button that prompts the user to input a URL but I cant figure out how to put that into an image tag inside the created cell.
let id = 0;
let img = document.getElementById("image").addEventListener("click", () => {
function getUrl() {
var url = prompt("Enter image URL");
if (url) {
return url;
} else {
return getUrl();
}
}
image.src = getUrl();
});
document.getElementById("add").addEventListener("click", () => {
let table = document.getElementById("list");
let row = table.insertRow(1);
row.setAttribute("id", `
test - $ {
id
}
`);
row.insertCell(0).innerHTML = document.getElementById("image").src = ""
row.insertCell(1).innerHTML = document.getElementById("Game-name").value;
row.insertCell(2).innerHTML = document.getElementById("hours-played").value;
row.insertCell(3).innerHTML = document.getElementById("new-critic-score").value;
row.insertCell(4).innerHTML = document.getElementById("new-personal-score").value;
let actions = row.insertCell(5);
actions.appendChild(createDeleteButton(id++));
document.getElementById("Game-name").value = "";
document.getElementById("hours-played").value = "";
document.getElementById("new-critic-score").value = "";
document.getElementById("new-personal-score").value = ""
});
function createDeleteButton(id) {
let btn = document.createElement("button");
btn.className = "btn btn-primary";
btn.id = id;
btn.innerHTML = "Delete";
btn.onclick = () => {
console.log(`
Deleting row with id: test - $ {
id
}
`);
let elementToDelete = document.getElementById(`
test - $ {
id
}
`);
elementToDelete.parentNode.removeChild(elementToDelete);
};
return btn;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.css" />
</head>
<body class="container" style="background-color: rgb(3, 27, 63);">
<!--Using HTML, Bootstrap, and JavaScript create a single page website that contains the following:
a. A Bootstrap styled table representing your choice of data.
b. A Bootstrap styled form that allows users to add input data as a new row to the table when submitted.
-->
<br />
<div class="card" style="background-color: rgb(7, 59, 75);color: rgb(255, 255, 255);">
<div class="card-body">
<div class="row">
<div class="col-sm">
<div>
<label for="new-critic-score">Critic score</label>
<input type="text" class="form-control" id="new-critic-score" placeholder="score out of 100" />
</div>
</div>
<div class="col-sm">
<div>
<label for="new-personal-score">Personal score</label>
<input type="text" class="form-control" id="new-personal-score" placeholder="score out of 100" />
</div>
</div>
<div class="col-sm">
<div>
<label for="hours-played">Hours played</label>
<input type="text" class="form-control" id="hours-played" placeholder="hours" />
</div>
</div>
</div>
<div class="row">
<div class="col-sm">
<div>
<label for="Game-name">Game name</label>
<input type="text" class="form-control" id="Game-name" placeholder="Game title" />
</div>
</div>
</div>
<div class="col-sm">
<div> <br>
<button id="image" class="btn btn-secondary from-control">add image</button>
<button id="add" class="btn btn-primary from-control">Create</button>
</div>
</div>
</div>
</div>
<table id="list" class="table table-dark table-striped">
<tr>
<th>game image</th>
<th>games played</th>
<th>Hours played</th>
<th>critic score</th>
<th>personal score</th>
<th>Actions</th>
</tr>
</table>
<script src="index.js"></script>
<script src="node_modules/jquery/dist/jquery.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.bundle.js"></script>
</body>
</html>
<img src="" alt="">
It wasn't clear to me how you wanted to do it, I basically got the URL and stored it in a var to then make another variable that is the image element itself, using the stored URL.
let imgURL;
let imgElement;
document.getElementById("image").addEventListener("click", () => {
imgURL = prompt("Enter image URL");
imgElement = '<img src="' + imgURL + '" width="80px">';
});
I also did the deletion in a similar way. Creating the element with an onclick to a function that passes the element itself with this as a parameter.
let deleteButton = '<input type="button" value="Delete" onclick="deleteRow(this)">'
and
row.insertCell(5).innerHTML = deleteButton;
Getting the ID by working your way up the parent elements to find the rowIndex.
function deleteRow(row) {
var id = row.parentNode.parentNode.rowIndex;
document.getElementById("list").deleteRow(id);
}
Hope the code itself helps you understand it better.
https://jsfiddle.net/sahil_m03/jmk4rbp3/43/
I'm busy with an Apps Script Web App and would like to populate input boxes within the web app with data from a google sheet.
I'm trying to retrieve data when a button is clicked and populate fields within the webapp with the data that is retrieved from the sheet. I just can't seem to get the text box fields to be updated after retrieving the data from google sheets.
Any help would be greatly appreciated.
The code I have so far is:
Code.gs file
function doGet() {
var htmlOutput = HtmlService.createTemplateFromFile("page");
return htmlOutput.evaluate();
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
var idx;
var nextLead;
var totalLeads;
var remainingLeads;
function assignLead() {
var ss = SpreadsheetApp.openById("sheetId");
var ws = ss.getSheetByName("leads");
var range = ws.getRange(1, 1, ws.getLastRow(), ws.getLastColumn())
var data = range.getValues();
//console.log(data);
var status = data.map(function (row) {
return row[11];
});
//console.log(status);
idx = status.indexOf("unassigned");
//console.log(idx)
for (var i = 0; i < data.length; i++) {
nextLead = data[idx];
updateStatusAssigned(idx)
}
// console.log(nextLead);
// console.log(data);
}
function updateStatusAssigned(row) {
var ss = SpreadsheetApp.openById("SheetId");
var ws = ss.getSheetByName("leads");
var range = ws.getRange(1, 1, ws.getLastRow(), ws.getLastColumn())
ws.getRange(idx + 1, 12).setValue("assigned")
}
page html file
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<?!= include("page-css") ?>
</head>
<body>
<div>
<!-- Header -->
<div class="header">
<h1>Header</h1>
</div>
<!-- Agent Info -->
<div class="row">
<div>
<p><label for="agnet">Agent Name:</label><input id="agent" type="text" ></input>
<label for="loginTime">Login Time:</label><input id="loginTime" type="text"></input></p>
<p><label for="campaign">Current Campaign:</label><input type="text" id="campaign"></input></p>
<button id="btn-getLead" style= float: right>Get Lead</button>
</div>
<!-- <div>
<button id="btn" style=”float: right”>Get Lead</button>
</div> -->
</div>
<!-- Lead Details Banner -->
<div class="row">
<div class="container">
<h3>Lead Details</h3>
</div>
<!-- Customer Information -->
<div class="flex-container">
<div>
<p>
<h5>Customer Information</h5>
</P>
<label>Name:</label><input type="text" id="name"></input>
<label>Surname:</label><input type="text" id="surname"></input>
<label>ID Number:</label><input type="text" id="id"></input>
<p><label>Address:</label><input type="text" id="add"></input><label>Postal Code:</label><input type="text" id="code"></input></p>
<p><label>Suburb:</label><input type="text" id="sub"></input></P>
<p><label>Postal Address:</label><input type="text" id="p-add"></input></p>
<p><label>Tel Number:</label><input type="tel" id="tel"></input>
<label>Mobile Number:</label><input type="tel" id="cell"></input>
<label>Alternate Number:</label><input type="tel" id="alt"></input></p>
<p>
<label>Disposition</label>
<select id="dispo">
<option> </option>
<option>Wrong Number</option>
<option>No Answer</option>
<option>Win</option>
</select>
</p>
<p>
<button id="submit">Submit</button>
</p>
</div>
<!-- Call Notes -->
<div>
<p>
<h5>Call Notes</h5>
</p>
<textarea rows="15" cols="50" id="notes"></textarea>
</div>
</div>
<?!= include("page-js") ?>
</body>
</html>
page-js file
<script>
document.getElementById("btn-getLead").addEventListener("click",getLeadData);
function getLeadData(){
google.script.run.assignLead()
document.getElementById("name") = nextLead[0];
}
</script>
Modification points:
Unfortunately, the variables declared as the global at Google Apps Script side cannot be used for Javascript side. So nextLead of document.getElementById("name") = nextLead[0]; cannot be used.
I thought that this is due to the reason of your issue.
In this case, withSuccessHandler can be used.
And, I think that document.getElementById("name") = nextLead[0]; occurs an error. In this case, please modify to document.getElementById("name").value = nextLead[0];.
When above points are reflected to your script, it becomes as follows.
Modified script:
Google Apps Script side:
Please modify assignLead() as follows.
From:
for (var i = 0; i < data.length; i++) {
nextLead = data[idx];
updateStatusAssigned(idx)
}
// console.log(nextLead);
// console.log(data);
}
To:
for (var i = 0; i < data.length; i++) {
nextLead = data[idx];
updateStatusAssigned(idx)
}
// console.log(nextLead);
// console.log(data);
return nextLead; // Added
}
Javascript side:
From:
function getLeadData(){
google.script.run.assignLead()
document.getElementById("name") = nextLead[0];
}
To:
function getLeadData(){
google.script.run.withSuccessHandler(nextLead => {
document.getElementById("name").value = nextLead[0];
}).assignLead();
}
Note:
In this modified script, it supposes that your function of assignLead() works fine and nextLead is the correct value you want. Please be careful this.
Reference:
withSuccessHandler(function)
I'm new to Javascript and I'm having trouble comparing elements from HTML. This is what I have for a function I cannot get the if statement to compare to the word Other which is one of my list items any ideas?
function createList(form) {
var row;
var table;
var form;
table = document.getElementById("shoppingList");
row = table.insertRow(table.rows.length);
form = form;
if (form.elements["storeItems"].value === "Other"){
row.insertCell(0).innerHTML = form.elements["otherItems"].value;}
else{
row.insertCell(0).innerHTML = form.elements["storeItems"].value;
}
row.insertCell(1).innerHTML = form.elements["funStores"].value;
row.insertCell(2).innerHTML = form.elements["selectColor"].value;
row.insertCell(3).innerHTML = form.elements["notes"].value;
}
My goal is if the list option Other is selected it pulls data from a text Other box instead of the word Other.
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta Tags -->
<meta charset="utf-8">
<meta name="description" content="Benoit's living space">
<meta name="keywords" content="home, funiture, living, space, Benoit">
<meta name="author" content="Jesse Benoit">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Jesse Benoit Homework Chapter 9</title>
<link rel="stylesheet" href="../css/Homework11.css"> <!-- Import of CSS -->
</head>
<body>
<h2 class="center">Furniture Shopping List</h2> <!-- Header 2 Centered -->
<div class="row">
<p class="center"> <!-- p cenetered with instructions -->
Time to go shopping! Pick an Item or Items from the list. Pick a Store from the list. Pick a color from the list. Added any extra notes you would like.
</p>
<div class="left">
<p>
<!-- Form to gather inputs from the user -->
<form>
<label>List of Items</label>
<select id="storeItems" size="4"></select> <br>
<label>Other: </label>
<input type="text" id="otherItems"> <br>
<label>Stores</label>
<select id="funStores" size="4"></select> <br>
<label>Other: </label>
<input type="text" id="otherStores"> <br>
<label>Chose a Color</label> <br>
<input type="radio" name="selectColor" value="White">White<br>
<input type="radio" name="selectColor" value="Black">Black<br>
<input type="radio" name="selectColor" value="Blue">Blue<br>
<input type="radio" name="selectColor" value="Red">Red<br>
<input type="radio" name="selectColor" value="OtherColor">Other<br>
<div id="selectColor"></div>
<label>Notes: </label><br>
<textarea rows="5" cols="20" id="notes"></textarea><br>
<input type="button" id="submit" value="Create Shopping List" onClick="createList(this.form);"> <!-- Button to create an invitation -->
<br><br>
</form>
</p>
</div>
<div class="right">
<table id="shoppingList">
<tr>
<th>Item </th><th>Store </th><th>Color of Item </th><th>Notes </th>
</tr>
</table>
</div>
</div>
<br>
<script src="../js/homework11.js"></script>
</body>
</html>
selectItem();
selectStore();
function selectItem() {
var myItems = "Couch; Table; Dresser; Chair; Bed; Other" ;
var itemArray = myItems.split(";");
var name = 0;
var myOption = "";
for (var i = 0; i < itemArray.length; i++) {
name = itemArray[i];
myOption = document.createElement("option");
myOption.name = name;
myOption.value = name;
myOption.text = name;
document.getElementById("storeItems").appendChild(myOption);
}
}
function selectStore(){
var myStore = "Walmart; Target; Wayfair; Other" ;
var storeArray = myStore.split(";");
var name = 0;
var myOption = "";
for (var i = 0; i < storeArray.length; i++) {
name = storeArray[i];
myOption = document.createElement("option");
myOption.name = name;
myOption.value = name;
myOption.text = name;
document.getElementById("funStores").appendChild(myOption);
}
}
function createList(form) {
var row;
var table;
var form;
table = document.getElementById("shoppingList");
row = table.insertRow(table.rows.length);
form = form;
if (form.elements["storeItems"].value === "Other"){
row.insertCell(0).innerHTML = form.elements["otherItems"].value;}
else{
row.insertCell(0).innerHTML = form.elements["storeItems"].value;
}
row.insertCell(1).innerHTML = form.elements["funStores"].value;
row.insertCell(2).innerHTML = form.elements["selectColor"].value;
row.insertCell(3).innerHTML = form.elements["notes"].value;
}
If you have a dropdown, you can get the selected value via:
let dropdownEl = document.getElementById('storeItems');
console.log(dropdownEl.value);
I'm slightly confused with what form is - but I'm assuming your dropdown has id="storeItems".
Also, I'm assuming you created the dropdown using the <select>...</select> tag.
Turns out having the dropdown list as a function was the issue and I needed list my options in the HTML
I have it so you type in on a form a maximum number then it creates a table after clicking a button.
I want it so after you click the button to add the row it writes a drop down menu in the table that goes from 0 to the number you put in the form
This is my HTML code:
<html>
<head>
<title>Form Generator</title>
<link rel="stylesheet" type="text/css" href="../css/converter.css"/>
<script language="JavaScript" src="../js/exercise2.js" type="text/javascript">
</script>
</head>
<body>
<p>
<button class="button" data-modal="M2KM">Form Generator</button>
</p>
<div id="M2KM" class="modal">
<div class="modal-content">
<div class="form">
<a class="close">×</a>
<form action="">
<textarea rows="1" name="Section" id="Section" cols="10">Section</textarea>
<textarea rows="1" name="Max" id="Max" cols="10">Max</textarea>
<textarea rows="1" name="Comment" id="Comment" cols="10">Comment</textarea>
<textarea rows="1" name="Mark" id="Mark" cols="10">Mark</textarea>
<input type="button" value="Add Row" name="Add Row" onclick="conversionTable('table')" />
<input type="reset" value="Clear" name="Clear">
</form>
<div id="conversion">
<table id="table">
<thead>
<tr>
<th>Section</th>
<th>Max</th>
<th>Comment</th>
<th>Mark</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</body>
</html>
This is my JavaScript Code:
function conversionTable(tagId, from, to)
{
var section = document.getElementById("Section").value;
var max = document.getElementById("Max").value;
var comment = document.getElementById("Comment").value;
var mark = document.getElementById("Mark").value;
from = 0;
to = 1;
var total = 0;
var arr = [];
var conv = document.getElementById(tagId) ;
var pre = document.createElement("pre");
conv.appendChild(pre);
var body= conv.appendChild(document.createElement("tbody"));
for (var i=from; i<to; i++)
{ row = body.appendChild(document.createElement("tr"));
var data=row.appendChild(document.createElement("td"));
data.appendChild(document.createTextNode(section));
data=row.appendChild(document.createElement("td"));
data.appendChild(document.createTextNode(max));
var data=row.appendChild(document.createElement("td"));
data.appendChild(document.createTextNode(comment));
data=row.appendChild(document.createElement("select"));
data.setAttribute("id", "mySelect");
row.appendChild(data);
var z = document.createElement("option");
z.setAttribute("value", "volvocar");
var t = document.createTextNode("1");
z.appendChild(t);
document.getElementById("mySelect").appendChild(z);
total = total + mark;
var obj = {section: section, max: max, comment: comment, mark: mark};
arr.push(obj);
}
}
This is a screenshot showing test data:
Here's a simplified example that adds a select element with a number of options equal to the number entered by the user.
See comments in the code for an explanation of how it works.
// Identifies existing HTML elements
const maxInput = document.getElementById("max");
const button = document.getElementById("button");
const table = document.getElementById("table");
// Calls `addDropdown` when `button` is clicked
button.addEventListener("click", addDropdown);
// Defines the event listener
function addDropdown(event) { //(`event` object is available if we want it)
// Gets value from input
let max = parseInt(maxInput.value);
// Exits function early if maxInput doesn't have a number
if(!max){ return; }
// Defines the new elements
const row = document.createElement("tr");
const cell = document.createElement("td");
const dropdown = document.createElement("select");
// Enumerates options and adds them to the select element
let optNumber = -1;
while(++optNumber <= max){
let optionElement = document.createElement("option");
optionElement.value = "opt" + optNumber;
optionElement.innerHTML = "Option " + optNumber;
dropdown.appendChild(optionElement);
}
// Adds the elements to the page
cell.appendChild(dropdown);
row.appendChild(cell);
table.appendChild(row);
}
<label>
<span>Enter maximum value for dropdown:</span>
<input id="max" value="5" />
</label>
<br />
<button id="button">Add Dropdown in New Row</button>
<div id="container">
<table id="table"></table>
</div>
I have two buttons in my form for calling two JavaScript functions. The first button works good in its onclick event calling the payroll() function successfully but the second button is of type submit and it never calls the send() function on form submission. I don't know why this issue occurs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!DOCTYPE html>
<html >
<head>
<title>hr page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript"
src="/static/js/sijax/sijax.js"></script>
<script type="text/javascript">
{{ g.sijax.get_js()|safe }}</script>
<link rel="stylesheet" href="{{url_for('static', filename='styles/signupcss.css')}}">
<script type="text/javascript" >
function payroll() {
var basic=document.forms["salary"]["bsalary"].value;
var empid=document.forms["salary"]["empid"].value;
var ta,hra,da,pf,netsalary,grosssalary;
if (empid == ""||basic == "") {
alert("Employee ID and Salary details must be filled out");
return false;
}
if(isNaN(basic))
{alert("Salary must be in Numbers");
return false;
}
hra=basic*40/100;
da=basic*15/100;
pf=basic*12/100;
basic=parseInt(basic);
hra=parseInt(hra);
da=parseInt(da);
grosssalary=basic + hra + da;
ta=basic*6.2/100;
netsalary=grosssalary-ta;
document.getElementById("hra").innerHTML=hra;
document.getElementById("ta").innerHTML=ta;
document.getElementById("da").innerHTML=da;
document.getElementById("netsalary").innerHTML=netsalary;
document.getElementById("pf").innerHTML=pf;
document.getElementById("grosssalary").innerHTML=grosssalary;
window.alert("HI"+grosssalary);
return true;
}
function send()
{
var id = document.forms['salary']['empid'].value;
var basic = document.forms['salary']['bsalary'].value;
var hra = document.forms['salary']['hra'].value;
var da = document.forms['salary']['da'].value;
var ta = document.forms['salary']['ta'].value;
var pf = document.forms['salary']['pf'].value;
var gross_sal = document.forms['salary']['grosssalary'].value;
window.alert("HI"+gross_sal);
var net_sal = document.forms['salary']['netsalary'].value;
Sijax.request('send',[id, basic, hra, ta, da, pf, gross_sal, net_sal]);
}
</script>
</head>
<body style="font-family:Lato">
<div style="padding-left:5%;padding-top:0.2%;height:1%;width:100%;background-color:#11557c">
<h2>Welcome to HR Department</h2><br>
</div>
<div style="margin-left:15%" >
<h2>Name</h2>
<form id="salary" name="salary" style="margin-top: 2%" method="post" onsubmit="return send()" >
<label id = "empid">Employee ID</label><br>
<input type = "text" name = "empid" placeholder = "Employee ID" /><br><br>
<label id = "bsalary">Basic Salary</label><br>
<input type = "text" name = "bsalary" placeholder = "Basic salary" /><br><br>
<input type="button" value="Calculate" onclick="return payroll()"><br><br>
<label for ="hra">House Rent Allowance(HRA)</label>
<p id="hra" name="hra"></p><br>
<label for ="ta">Travel Allowance(TA)</label>
<p id="ta" name="ta"></p><br>
<label for ="da"> Dearness Allowance(DA)</label>
<p id="da" name="da"></p><br>
<label for ="netsalary">Net Salary</label>
<p id="netsalary" name="netsalary"></p><br>
<label for ="pf">Provident Fund(PF)</label>
<p id="pf" name ="pf"></p><br>
<label for ="grosssalary">Gross Salary</label>
<p id="grosssalary" name="grosssalary"></p><br><br>
<input type="submit" value="Upload Salary">
</form>
</div>
</body>
</html>
You can't act with <p> elements like as a form-elements. You may create a respective <input type="hidden"> elements and fill them in payroll(), or get values by .innerHtml on paragraphs.
P.S. You have actually a TypeError exception, calling undeclared form elements like document.forms['salary']['grosssalary'] and so on.
okay, quick fix, since you are using python flask library Sijax for ajax and therefore jQuery, you can alter your javascript send function like this:
function send(e){
e.preventDefault(); //it is as good as returning
//false from the function in all cases
var id = document.forms['salary']['empid'].value;
...
}
and change your onsubmit handler declaration like this:
<form id="salary" name="salary" style="margin-top: 2%" method="post"
onsubmit="return send(event)" >
please note that when you stop the event chain propagation, you will have to do a manual submission of the form.
So, you can modify your send function to do .preventDefault based on your custom criterias, otherwise, let the form submit
Your code actually works, if you're running this code as a snippet here in stack overflow, Form submission is actually blocked by default. Try running your code in codepen. I tried it and it's actually working.
http://codepen.io/jhonix22/pen/VPZagb
Check this out. It is nowhere close to a perfect solution but I think it helps. You can not access the paragraphs as if you would the form input elements. Im not entirely sure what Sijax thing is. I believe it is just a normal AJAX HTTP thing with some sort of CSRF security filters.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!DOCTYPE html>
<html>
<head>
<title>hr page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript"
src="/static/js/sijax/sijax.js"></script>
<script type="text/javascript">
{
{
g.sijax.get_js() | safe
}
}</script>
<link rel="stylesheet" href="{{url_for('static', filename='styles/signupcss.css')}}">
<script type="text/javascript">
function payroll() {
var basic = document.forms["salary"]["bsalary"].value;
var empid = document.forms["salary"]["empid"].value;
var ta, hra, da, pf, netsalary, grosssalary;
if (empid == "" || basic == "") {
alert("Employee ID and Salary details must be filled out");
return false;
}
if (isNaN(basic)) {
alert("Salary must be in Numbers");
return false;
}
hra = basic * 40 / 100;
da = basic * 15 / 100;
pf = basic * 12 / 100;
basic = parseInt(basic);
hra = parseInt(hra);
da = parseInt(da);
grosssalary = basic + hra + da;
ta = basic * 6.2 / 100;
netsalary = grosssalary - ta;
document.getElementById("hra").innerHTML = hra;
document.getElementById("ta").innerHTML = ta;
document.getElementById("da").innerHTML = da;
document.getElementById("netsalary").innerHTML = netsalary;
document.getElementById("pf").innerHTML = pf;
document.getElementById("grosssalary").innerHTML = grosssalary;
window.alert("HI" + grosssalary);
return true;
}
function send() {
var id = document.forms['salary']['empid'].value;
var basic = document.forms['salary']['bsalary'].value;
var hra = document.getElementById('hra').innerHTML;
var da = document.getElementById('da').innerHTML;
var ta = document.getElementById('ta').innerHTML;
var pf = document.getElementById('pf').innerHTML;
var gross_sal = document.getElementById('grosssalary').innerHTML;
window.alert("HI" + gross_sal);
var net_sal = document.getElementById('netsalary').innerHTML;
// I think you are missing something here.
Sijax.request('send', [id, basic, hra, ta, da, pf, gross_sal, net_sal]);
}
</script>
</head>
<body style="font-family:Lato">
<div style="padding-left:5%;padding-top:0.2%;height:1%;width:100%;background-color:#11557c">
<h2>Welcome to HR Department</h2><br>
</div>
<div style="margin-left:15%">
<h2>Name</h2>
<form id="salary" name="salary" style="margin-top: 2%" method="post" onsubmit="return false">
<label id="empid">Employee ID</label><br>
<input type="text" name="empid" placeholder="Employee ID"/><br><br>
<label id="bsalary">Basic Salary</label><br>
<input type="text" name="bsalary" placeholder="Basic salary"/><br><br>
<input type="button" value="Calculate" onclick="return payroll()"><br><br>
<label for="hra">House Rent Allowance(HRA)</label><br>
<p id="hra" readonly name="hra"></p>
<label for="ta">Travel Allowance(TA)</label><br>
<p id="ta" readonly name="ta"></p>
<label for="da"> Dearness Allowance(DA)</label><br>
<p id="da" readonly name="da"></p>
<label for="netsalary">Net Salary</label><br>
<p id="netsalary" readonly name="netsalary"></p>
<label for="pf">Provident Fund(PF)</label><br>
<p id="pf" readonly name="pf"></p>
<label for="grosssalary">Gross Salary</label><br>
<p id="grosssalary" readonly name="grosssalary"></p><br>
<input type="button" onclick="send()" value="Upload Salary">
</form>
</div>
</body>
</html>