How to remove specific row in table using js - javascript

I am learning javascript and i made this simple page where you add your title and author. By clicking on add button the input is entered to table where you have remove button.
How can i implement a function remove(){} in javascript that removed the row of the table from where it was called, because i tried using output.lastElement.remove(); but that only removes the last row not the row from where the button is clicked. If you know how can i make this please give me an answer ty :).
var title = document.getElementById("title");
var author = document.getElementById("author");
var output = document.getElementById("output");
function addToTable(){
output.innerHTML += "<tr>" + "<td>" + title.value + "</td>" +
"<td>" + author.value + "</td>" +
"<td>" + "<input type='button' onclick='remove();' id='remove'value ='Remove'>"+ "</td>" + "</tr>"
}
function remove(){
}
label{
width: 100px;
display: inline-block;
}
table,th,td,tr,td{
border: 1px solid black;
border-collapse: collapse;
}
table td{
text-align: center;
}
<!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></title>
</head>
<body>
<div>
<div>
<label for="Title">Title</label>
<input type="text" id="title">
</div>
<div>
<label for="Author">Author</label>
<input type="text" id="author">
</div>
</div>
<div>
<input type="button" value="Add" onclick="addToTable();">
</div>
<div>
<table id="output">
<th style="width:45%;">Title</th>
<th style="width:45%;">Author</th>
<th style="width:10%;">Button</th>
</table>
</div>
</body>
</html>

Just throw this to remove function as parametr and then call removeChild on parent.
var title = document.getElementById("title");
var author = document.getElementById("author");
var output = document.getElementById("output");
function addToTable(){
output.innerHTML += "<tr>" + "<td>" + title.value + "</td>" +
"<td>" + author.value + "</td>" +
"<td>" + "<input type='button' onclick='remove(this);' id='remove'value ='Remove'>"+ "</td>" + "</tr>"
}
function remove(btn){
var row = btn.parentNode;
row.parentNode.removeChild(row);
}
label{
width: 100px;
display: inline-block;
}
table,th,td,tr,td{
border: 1px solid black;
border-collapse: collapse;
}
table td{
text-align: center;
}
<!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></title>
</head>
<body>
<div>
<div>
<label for="Title">Title</label>
<input type="text" id="title">
</div>
<div>
<label for="Author">Author</label>
<input type="text" id="author">
</div>
</div>
<div>
<input type="button" value="Add" onclick="addToTable();">
</div>
<div>
<table id="output">
<th style="width:45%;">Title</th>
<th style="width:45%;">Author</th>
<th style="width:10%;">Button</th>
</table>
</div>
</body>
</html>

Using modern javascript syntax:
const title = document.getElementById("title");
const author = document.getElementById("author");
const output = document.getElementById("output");
const addToTable = () => {
const dataId = `table-row-${new Date().getTime()}`;
output.innerHTML += `
<tr data-row-id="${dataId}">
<td>${title.value}</td>
<td>${author.value}</td>
<td>
<input type="button" onclick="remove('${dataId}')" value="Remove">
</td>
</tr>`;
}
const remove = (dataRowID) => {
output.querySelector(`[data-row-id="${dataRowID}"]`).remove();
}
label{
width: 100px;
display: inline-block;
}
table, th, td, tr, td {
border: 1px solid black;
border-collapse: collapse;
}
table td{
text-align: center;
}
<!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></title>
</head>
<body>
<div>
<div>
<label for="Title">Title</label>
<input type="text" id="title">
</div>
<div>
<label for="Author">Author</label>
<input type="text" id="author">
</div>
</div>
<div>
<input type="button" value="Add" onclick="addToTable();">
</div>
<div>
<table id="output">
<th style="width:45%;">Title</th>
<th style="width:45%;">Author</th>
<th style="width:10%;">Button</th>
</table>
</div>
</body>
</html>
I advise you not to completely use old javascript syntax.

An example using event delegation.
function addToTable() {
const title = document.getElementById("title");
const author = document.getElementById("author");
const output = document.getElementById("output");
output.innerHTML +=
"<tr>" +
"<td>" +
title.value +
"</td>" +
"<td>" +
author.value +
"</td>" +
"<td>" +
"<button type='button'>remove</button>" +
"</td>" +
"</tr>";
}
function removeRow(e) {
if (e.target.tagName === "BUTTON") {
e.target.closest("tr").remove();
}
}
document.querySelector("#output").addEventListener("click", removeRow);
label{
width: 100px;
display: inline-block;
}
table,th,td,tr,td{
border: 1px solid black;
border-collapse: collapse;
}
table td{
text-align: center;
}
<!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></title>
</head>
<body>
<div>
<div>
<label for="Title">Title</label>
<input type="text" id="title">
</div>
<div>
<label for="Author">Author</label>
<input type="text" id="author">
</div>
</div>
<div>
<input type="button" value="Add" onclick="addToTable();">
</div>
<div>
<table id="output">
<th style="width:45%;">Title</th>
<th style="width:45%;">Author</th>
<th style="width:10%;">Button</th>
</table>
</div>
</body>
</html>

Related

Input to table in javascript

How can i add a content to html table with input fields.
For example here is html code:
function add(){
var name = document.getElementById("name");
var surname = document.getElementById("surname");
var output = document.getElementById("output");
output.innerHTML = "<tr><td>"+name+"</td><td>"+surname+"</td></tr>"
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial- scale=1.0">
<title>Document</title>
<style>
table,td{
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
<body>
<form action="">
<div>
<label for="name">Name</label>
<input type="text" id="name">
</div>
<div>
<label for="name">Surname</label>
<input type="text" id="surname">
</div>
</form>
<input type="button" onclick="add();" value="Add">
<div>
<table id="output">
<thead><td>Name</td><td>Surname</td></thead>
<tbody></tbody>
</table>
</div>
</body>
</html>
I want to output my input fields in the table like rows.. but it does not work i dont know where is my problem i get [object HTMLInputElement].
And how can i make it work for entering more values because like this i can only enter one row
How about using this code?
It adds surname and name below the thead.
function add(){
var name = document.getElementById("name");
var surname = document.getElementById("surname");
var output = document.querySelector("#output tbody");
output.innerHTML += "<tr><td>"+name.value+"</td><td>"+surname.value+"</td></tr>"
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial- scale=1.0">
<title>Document</title>
<style>
table,td{
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
<body>
<form action="">
<div>
<label for="name">Name</label>
<input type="text" id="name">
</div>
<div>
<label for="name">Surname</label>
<input type="text" id="surname">
</div>
</form>
<input type="button" onclick="add();" value="Add">
<div>
<table id="output">
<thead><td>Name</td><td>Surname</td></thead>
<tbody></tbody>
</table>
</div>
</body>
</html>
you should assign the value of the input fields like below.
function add(){
var name = document.getElementById("name");
var surname = document.getElementById("surname");
var output = document.getElementById("output");
output.innerHTML = "<tr><td>"+name.value+"</td><td>"+surname.value+"</td></tr>"
}
Try:
Give tbody an id to avoid removing thead
<tbody id="output2"></tbody>
function add(){
var name = document.getElementById("name");
var surname = document.getElementById("surname");
var output = document.getElementById("output2");
output.innerHTML = "<tr><td>" + name.value + "</td><td>" + surname.value + "</td></tr>";
}
You are trying to insert an HTML input element instead of the value of the element.
To make multiple entries possible try the last line of the function to:
output.innerHTML += "<tr><td>" + name.value + "</td><td>" + surname.value + "</td></tr>";

HTML formular JavaScript

I have a problem with JavaScript. When I push the "Add" button I want to create a table with the listings from the form.
So for example:
New course: name: A, content: B => Add
|name|content
| A | B
And every new record comes to the end of the table.
Do you have an idea how can I do this? With PHP I would be easy but I want to do it with JavaScript.
My idea is to add this code into script:
document . addEventListener( 'DOMContentLoaded', registerCallbacks ); function registerCallbacks( ) { var addButton = document.getElementById( 'add‘ ); addButton.addEventListener( 'click', function( evt ){ add( ); evt.preventDefault( ); } );
document.addEventListener('DOMContentLoaded', registerCallbacks);
function registerCallbacks() {
var addButton = document.getElementById('add‘ ); addButton.addEventListener( '
click ', function( evt ){ add( ); evt.preventDefault( ); } );
<html>
<body>
<form id="new">
<label for="name">Name of lecture: <br>
<input class="text" type="text" id="name"></input><br>
<label for="content">Content: <br>
<textarea class="text" id="content"></textarea><br>
<button id="add"> Add </button>
</form>
<script>
</script>
</body>
</html>
So step one is to activate the button:
// Here we call the function Add() if someone clicks the button.
<button id="add" onclick="Add()"> Add </button>
Now we want to add the Javascript function Add() to our script:
function Add() {
// We request here all the information what the user fill out.
}
So here is a working snippet:
let table = document.getElementById("table");
function Add() {
// We request here all the information what the user fill out.
let name = document.getElementById("name").value,
content = document.getElementById("content").value;
// Add to table
table.innerHTML += "<tr><td>" + name + "</td><td>" + content + "</td></tr>"
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 3px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<label for="name">Name of lecture: <br>
<input class="text" type="text" id="name"><br>
<label for="content">Content: <br>
<textarea class="text" id="content"></textarea><br>
<button id="add" onclick="Add()"> Add </button>
<table id="table">
<tr>
<th>Lecture</th>
<th>Content</th>
</tr>
</table>
Hope this will work
$(document).ready(function() {
$("#add").click(function(){
var name=document.getElementById("name").value;
var content=document.getElementById("content").value;
$("#table").find('tbody').append("<tr><td class='column'>"+name+"</td><td class='column'>"+content+"</td></tr>");
});
});
<html>
<head>
<title>Add New Row</title>
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
.head {
border: 1px solid ;
background:#AEB6BF;
}
.column {
border: 1px solid ;
background:#EAEDED;
}
</style>
</head>
<body>
<label for="name">Name of lecture: <br>
<input class="text" type="text" id="name"></input><br>
<label for="content">Content: <br>
<textarea class="text" id="content"></textarea><br>
<button id="add"> Add </button>
<table id="table" class="head">
<thead>
<tr>
<td>Name</td>
<td>Content</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
</script>
</body>
</html>
Here's a way to achieve it:
var add_button = document.getElementById("add");
var name_field = document.getElementById("name");
var content_field = document.getElementById("content");
var table = document.getElementById("table");
add_button.addEventListener("click", function(e) {
e.preventDefault();
table.style = "display: block;";
table.innerHTML += "<tr><td>" + name_field.value + "</td><td>" + content_field.value + "</td></tr>"
});
<head>
<title>HTML Formular Table</title>
</head>
<body>
<form id="new">
<label for="name">Name of lecture: <br>
<input class="text" type="text" id="name"></input><br>
<label for="content">Content: <br>
<textarea class="text" id="content"></textarea><br>
<button id="add"> Add </button>
</form>
<table id="table" style= "display: none;">
<tr>
<th>Name</th>
<th>Content</th>
</tr>
</table>

javaScript dynamic table [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I've just started learning javascript and I'm having trouble with a homework problem. The problem gets user input via php (inputs are years to forecast, population, and growth rate). then the javascript should produce a table in the format of (years, population and change).
Example of output
<!doctype html>
<META HTTPEQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
<meta httpequiv="expires" content="0" />
<html lang="en">
<head>
<title> hw8 </title>
<link rel="stylesheet" href="hw8.css">
<script src="hw8.js"></script>
</head>
<body>
<form name="inputform">
<div id="input">
<h2> Population Growth </h2>
Years to forecast: <input type="text" value="<? print $_POST['years']; ?>" name="years"> <br/> <br/>
Current Population: <input type="text" value="<? print $_POST['population']; ?>" name="population"> <br/> <br/>
Growth Rate: <input type="text" value="<? print $_POST['rate']; ?>" name="rate"> <br/> <br/>
<div id="button"> <input type="submit" value="Calculate" id="calc"> </div>
</div>
</form>
<div id="tables">
<table id="table">
<tr>
<th> Year </th> <th> Population </th> <th> Change </th>
<tr>
<td> 2017 </td> <td> . </td> <td> . </td>
</tr>
</table>
</div>
</body>
</html>
window.addEventListener("load", link_events, false);
function link_events() {
document.getElementById("calc").onclick = calculate;
}
function calculate() {
var form = document.forms["inputform"];
var year = 2017;
var i;
var years = document.getElementById('years');
for (i=0; i < years.length; i++){
year[i]++
}
var
var change = parseFloat(form)["population"] * (parseFloat(form)["rate"]/100)
I put together an example for you with the result you want.
JSFiddle: https://jsfiddle.net/0sfrrewc/
Code:
<!DOCTYPE html>
<html>
<head>
<title>hw08 demo</title>
<style type="text/css">
div#errorContainer {
max-width: 400px;
margin-top: 20px;
border: 1px solid #000;
background-color: red;
border-radius: 5px;
padding: 10px;
}
div#errorContainer > span {
color: white;
}
</style>
<script type="text/javascript">
window.onload = function () {
/* Calculate click */
document.getElementById('calculate').addEventListener('click', function() {
/* Get years */
var years = parseInt(document.getElementById('years').value);
if (isNaN(years) || years <= 0) {
alert('Invalid year'); return;
}
/* Get population */
var population = parseInt(document.getElementById('population').value);
if (isNaN(population) || population <= 0) {
alert('Invalid population'); return;
}
/* Get rate */
var rate = parseInt(document.getElementById('rate').value);
if (isNaN(rate) || rate <= 0) {
alert('Invalid rate'); return;
}
/* Create table */
var table = '' +
'<table>' +
'<thead>' +
'<th><strong>Year</strong></th>' +
'<th><strong>Population</strong></th>' +
'<th><strong>Change</strong></th>' +
'</thead>' +
'';
var currentYear = new Date().getFullYear();
table += '' +
'<tbody>' +
'';
for (var i = currentYear; i < (currentYear+years); i++) {
var change = (population*rate)/100;
population += change;
table += '' +
'<tr>' +
'<td>' + i + '</td>' +
'<td>' + population.toFixed() + '</td>' +
'<td>' + change.toFixed() + '</td>' +
'</tr>' +
'';
}
table += '' +
'</tbody>' +
'</table>' +
'';
/* Display table */
document.getElementById('result').innerHTML = table;
});
}
</script>
</head>
<body>
<h2>hw08 - Population Growth</h2>
<br>
<label for="years">Years to forecast:</label>
<input type="number" id="years" />
<br>
<label for="population">Current Population:</label>
<input type="number" id="population" />
<br>
<label for="rate">Growth Rate:</label>
<input type="number" id="rate" />
<br><br>
<input type="submit" id="calculate" value="Calculate!" />
<br><br>
<div id="result"></div>
</body>
</html>
Result:
Explanation:
We create a event listener, thats being fired upon clicking the button. Then we fetch the necessary data (year, population and rate), we validate the data then we create the table. We store the entire table in a variable until we are done generating the table, then we place it inside the div with the id result.
EDIT: Edited the code, it's now a html & pure javascript solution.

Saving form data using localstorage and dynamically reading data to a table

I am currently creating a signup form for a client and one of the requirements is for the form to be able to transmit and store data offline. I have already tried to work with a database, but I am still in beginning stages learning php so I decided t quit while I am behind.
I found another method of storign data locally suing localstorage with JS, but I am unable to display the stored data in a dynamic table.
Any help on this matter would be greatky appreciated, here is the code I have so far
<!DOCTYPE html>
<html lang="en">
<head>
<title>CIVIC Registration Form</title>
<link rel="icon" href="civic.ico" type="image/x-icon">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/custom.css">
<link rel="stylesheet" href="css/styles.css">
<style>
p.finePrint {
color:#818185;
font-size:70%;
}
</style>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script type="text/javascript">
(function()
{
var Applicant = {
fname: "",
lname: "",
age: 0,
phonenum: "",
email: ""
};
var storageLogic = {
saveItem: function (){
var lscount = localStorage.length;
var inputs = document.getElementsByClassName("form-control");
Applicant.fname = inputs[0].value;
Applicant.lname = inputs[1].value;
Applicant.age = inputs[2].value;
Applicant.phonenum = inputs[3].value;
Applicant.email = inputs[4].value;
localStorage.setItem("Applicant_" + lscount, JSON.stringify(Applicant));
location.reload();
},
loaddata: function() {
var datacount = localStorage.length;
if (datacount > 0)
{
var render = "<table border='1'>";
render += "<tr><th>First Name</th><th>Last Name</th><th>Age</th>" +
"<th>Phone Number</th><th>Email</th>";
for (i=0; i < datacount; i++) {
var key = localStorage.key(i);
var applicant = localStorage.getItem(key);
var data = JSON.parse(applicant);
render += "<tr><td>" + data.fname + "</td><td>" + data.lname + "</td>";
render += "<td>" + data.age + "</td>";
render += "<td>" + data.phonenum + "</td>";
render += "<td>" + data.email + "</td>";
}
render += "</table>";
var newTable = document.getElementById("dvContainer");
newTable.innerHTML = render;
}
}
};
var btnsubmit = document.getElementById('btnsubmit');
btnsubmit.addEventListener('click', storageLogic.saveItem(), false);
window.onload = function() {
storageLogic.loaddata();
};
})();
</script>
</head>
<body>
<div class="container">
<h2 style="color:#005E28"><img src="civic.jpg" height="50" width="50"></img>CIVIC Registration Form</h2>
<form role="form">
<div class="form-group">
<label for="fname">First Name:</label>
<input type="text" class="form-control" id="fname" placeholder="First Name">
</div>
<div class="form-group">
<label for="lname">Last Name:</label>
<input type="text" class="form-control" id="lname" placeholder="Last Name">
</div>
<div class="form-inline">
<label for="age">Age: <input type="text" class="form-control" id="age" placeholder="Age"></label>
<label for="phone">Phone Number: <input type="text" class="form-control" id="phonenum" placeholder="Phone Number"></label>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email">
</div>
<div>
<!-- <button type="submit" class="btn btn-default">Submit</button> -->
<input id="btnsubmit" type="button" value="Submit" class="btn btn-success"/>
<p class="finePrint">*By submitting this form you agree to receiving emails regarding
upcoming events and other information from CIVIC Ontario.
If you have any questions or concerns, please email civicontario#gmail.com*</p>
</div>
</form>
</div>
<div id="dvContainer" class="conatiner">
</div>
</body>
</html>
There are primarily two errors you need to fix:
Move the getElementById() and addEventListener() for id btnsubmit to your onload handler. The way it is now, it tries to find the element before it is actually in the DOM.
You are accidentally invoking the handler that is the second parameter of addEventListener(). In other words, get rid of the () after the second parameter.
Here is a version of your code with those changes that seems to minimally work.
<!DOCTYPE html>
<html lang="en">
<head>
<title>CIVIC Registration Form</title>
<link rel="icon" href="civic.ico" type="image/x-icon">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/custom.css">
<link rel="stylesheet" href="css/styles.css">
<style>
p.finePrint {
color:#818185;
font-size:70%;
}
</style>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script type="text/javascript">
(function()
{
var Applicant = {
fname: "",
lname: "",
age: 0,
phonenum: "",
email: ""
};
var storageLogic = {
saveItem: function (){
var lscount = localStorage.length;
var inputs = document.getElementsByClassName("form-control");
Applicant.fname = inputs[0].value;
Applicant.lname = inputs[1].value;
Applicant.age = inputs[2].value;
Applicant.phonenum = inputs[3].value;
Applicant.email = inputs[4].value;
localStorage.setItem("Applicant_" + lscount, JSON.stringify(Applicant));
location.reload();
},
loaddata: function() {
var datacount = localStorage.length;
if (datacount > 0)
{
var render = "<table border='1'>";
render += "<tr><th>First Name</th><th>Last Name</th><th>Age</th>" +
"<th>Phone Number</th><th>Email</th>";
for (i=0; i < datacount; i++) {
var key = localStorage.key(i);
var applicant = localStorage.getItem(key);
var data = JSON.parse(applicant);
render += "<tr><td>" + data.fname + "</td><td>" + data.lname + "</td>";
render += "<td>" + data.age + "</td>";
render += "<td>" + data.phonenum + "</td>";
render += "<td>" + data.email + "</td>";
}
render += "</table>";
var newTable = document.getElementById("dvContainer");
newTable.innerHTML = render;
}
}
};
window.onload = function() {
storageLogic.loaddata();
var btnsubmit = document.getElementById('btnsubmit');
btnsubmit.addEventListener('click', storageLogic.saveItem, false);
};
})();
</script>
</head>
<body>
<div class="container">
<h2 style="color:#005E28"><img src="civic.jpg" height="50" width="50"></img>CIVIC Registration Form</h2>
<form role="form">
<div class="form-group">
<label for="fname">First Name:</label>
<input type="text" class="form-control" id="fname" placeholder="First Name">
</div>
<div class="form-group">
<label for="lname">Last Name:</label>
<input type="text" class="form-control" id="lname" placeholder="Last Name">
</div>
<div class="form-inline">
<label for="age">Age: <input type="text" class="form-control" id="age" placeholder="Age"></label>
<label for="phone">Phone Number: <input type="text" class="form-control" id="phonenum" placeholder="Phone Number"></label>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email">
</div>
<div>
<!-- <button type="submit" class="btn btn-default">Submit</button> -->
<input id="btnsubmit" type="button" value="Submit" class="btn btn-success"/>
<p class="finePrint">*By submitting this form you agree to receiving emails regarding
upcoming events and other information from CIVIC Ontario.
If you have any questions or concerns, please email civicontario#gmail.com*</p>
</div>
</form>
</div>
<div id="dvContainer" class="conatiner">
</div>
</body>
</html>

jQuery Mortgage Calculator - no output

I'm trying to recreate this mortgage calculator script on jsfiddle but when i run my copy of it I get no output. I'm super new to jquery so it could be something simple. Here's my entire page with all the code copied verbatim from jsfiddle:
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Mortgage Calc Testing Yay</title>
<meta name="description" content="">
<meta name="author" content="">
<style>
label, div input, div select {
display: block;
margin: 0.5em 0;
}
label {
font-weight: bold;
}
form p {
margin: 0.5em 0;
}
</style>
</head>
<body>
<form action="#" method="post" id="test">
<p><strong>Please insert decimals using the dot notation, e.g. <code>5.9</code></strong></p>
<div>
<label for="balance">Loan balance (€)</label>
<input name="balance" id="balance" type="text" />
</div>
<div>
<label for="rate">Interest rate (%)</label>
<input name="rate" id="rate" type="text" />
</div>
<div>
<label for="term">Loan term (years)</label>
<input name="term" id="term" type="text" />
</div>
<div>
<label for="period">Period</label>
<select name="period" id="period">
<option>Select</option>
<option value="12">Monthly</option>
<option value="6">Bimonthly</option>
</select>
</div>
<p><input type="submit" id="submit" name="submit" value="Calculate" /></p>
</form>
<script async src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
(function($) {
$.fn.calculateMortgage = function(options) {
var defaults = {
currency: '€',
params: {}
};
options = $.extend(defaults, options);
var calculate = function(params) {
params = $.extend({
balance: 0,
rate: 0,
term: 0,
period: 0
}, params);
var N = params.term * params.period;
var I = (params.rate / 100) / params.period;
var v = Math.pow((1 + I), N);
var t = (I * v) / (v - 1);
var result = params.balance * t;
return result;
};
return this.each(function() {
var $element = $(this);
var $result = calculate(options.params);
var output = '<p>' + options.currency + ' ' + $result.toFixed(2) + '</p>';
$(output).appendTo($element);
});
};
})(jQuery);
$(function() {
$('#test').on('submit', function(e) {
e.preventDefault();
var $params = {
balance: $('#balance').val(),
rate: $('#rate').val(),
term: $('#term').val(),
period: $('option:selected', '#period').val()
};
$(this).calculateMortgage({
params: $params
})
});
});
</script>
</body>
</html>
I've tried changing my jquery version but that didn't help.
Thank you for any help.

Categories