BookAddress using localStorage (adding users) - javascript

I am making a contact list in which I will be saving the contacts, but when I save one or more contact and refresh the page it doesn't save. I tried to put it in the local storage but it doesn't work. Can anyone help me with this?
HTML:
<br><br>
Name: <input id = "name" name = "name" type = "text">
<br><br>
Gender: <input name = "gender" type = "radio" value = "Male"> Male
<input name = "gender" type = "radio" value = "Female"> Female
<br><br>
Age: <input id = "age" name = "age" type = "text">
<br><br>
Number: <input id = "number" name = "number" type = "text">
<br><br>
Contact Type: <select id = "Contact_Type" name = "Contact_Type">
<option>none</option>
<option>Friend</option>
<option>Business</option>
<option>Educational</option>
</select>
<br><br>
Address: <input id = "Address" name = "Address" type = "text">
<br><br>
Post Code: <input id = "Post_Code" name = "Post_Code" type = "text">
<br><br>
Marital Status: <select id = "Marital_Status" name = "Marital_Status">
<option>none</option>
<option>Single</option>
<option>in relationship</option>
<option>Engaged</option>
<option>Married</option>
</select>
<br><br>
<input type = "button" value = " Reset " onclick = "ResetForm()">
<input type = "button" value = " Add " onclick = "AddData(), saveList()">
<input type = "button" value = "Remove contact" onclick = "Remove()">
</form>
JS:
function AddData() {
var x = document.getElementById("age").value;
var y = document.getElementById("name").value;
var letters = '/^[a-zA-Z]+$/';
if ((parseInt(x) != (x)) && (y == parseInt(y))) {
alert("Wrong Value Entered");
} else {
var rows = "";
var name = document.getElementById("name").value;
var gender = document.querySelector('input[name="gender"]:checked');
gender = gender ? gender.value : '';
var age = document.getElementById("age").value;
var number = document.getElementById("number").value;
var Contact_Type = document.getElementById("Contact_Type").value;
var Address = document.getElementById("Address").value;
var Post_Code = document.getElementById("Post_Code").value;
var Marital_Status = document.getElementById("Marital_Status").value;
rows += "<td>" + name + "</td><td>" + gender + "</td><td>" + age + "</td><td>" + number +"</td><td>" + Contact_Type + "</td><td>"+ Address + "</td><td>" + Post_Code+ "</td><td>" + Marital_Status +" </td>";
var tbody = document.querySelector("#list tbody");
var tr = document.createElement("tr");
tr.innerHTML = rows;
tbody.appendChild(tr)
saveList();
}
}
var saveList = function () {
"use strict";
var appts = JSON.stringify(contact);
if (appts !== "") {
localStorage.contact = appts;
} else {
window.alert("Could not save appointments at this time");
}
};
function ResetForm() {
document.getElementById("contact").reset();
}

Your code has several errors.
HTML table is not found.
You're invoking saveList function two times (in button event and at the end of AddData function).
You aren't passing the contact parameter to the saveList function.
You should read Clean Code Book for improve your coding =).
The code should be the next (you could check the key "contact" in your browser).
HTML:
<br>
<br> Name:
<input id="name" name="name" type="text">
<br>
<br> Gender:
<input name="gender" type="radio" value="Male"> Male
<input name="gender" type="radio" value="Female"> Female
<br>
<br> Age:
<input id="age" name="age" type="text">
<br>
<br> Number:
<input id="number" name="number" type="text">
<br>
<br> Contact Type:
<select id="Contact_Type" name="Contact_Type">
<option>none</option>
<option>Friend</option>
<option>Business</option>
<option>Educational</option>
</select>
<br>
<br> Address:
<input id="Address" name="Address" type="text">
<br>
<br> Post Code:
<input id="Post_Code" name="Post_Code" type="text">
<br>
<br> Marital Status:
<select id="Marital_Status" name="Marital_Status">
<option>none</option>
<option>Single</option>
<option>in relationship</option>
<option>Engaged</option>
<option>Married</option>
</select>
<br>
<br>
<table id="list">
<tbody>
</tbody>
</table>
<input type="button" value=" Reset " onclick="ResetForm()">
<input type="button" value=" Add " onclick="AddData()">
<input type="button" value="Remove contact" onclick="Remove()">
JS:
<script>
function AddData() {
var x = document.getElementById("age").value;
var y = document.getElementById("name").value;
var letters = '/^[a-zA-Z]+$/';
if ((parseInt(x) != (x)) && (y == parseInt(y))) {
alert("Wrong Value Entered");
} else {
var rows = "";
var name = document.getElementById("name").value;
var gender = document.querySelector('input[name="gender"]:checked');
gender = gender ? gender.value : '';
var age = document.getElementById("age").value;
var number = document.getElementById("number").value;
var Contact_Type = document.getElementById("Contact_Type").value;
var Address = document.getElementById("Address").value;
var Post_Code = document.getElementById("Post_Code").value;
var Marital_Status = document.getElementById("Marital_Status").value;
rows += "<td>" + name + "</td><td>" + gender + "</td><td>" + age + "</td><td>" + number + "</td><td>" + Contact_Type + "</td><td>" + Address + "</td><td>" + Post_Code + "</td><td>" + Marital_Status + " </td>";
var tbody = document.querySelector("#list tbody");
var tr = document.createElement("tr");
tr.innerHTML = rows;
tbody.appendChild(tr)
contact = {name:name, gender:gender, age:age, number:number, type:Contact_Type, address: Address, zip: Post_Code, marital: Marital_Status};
saveList(contact);
}
}
var saveList = function(contact) {
"use strict";
var appts = JSON.stringify(contact);
if (appts !== "") {
localStorage.contact = appts;
} else {
window.alert("Could not save appointments at this time");
}
};
function ResetForm() {
document.getElementById("contact").reset();
}
</script>
Now you should program the function to read the localStorage.

Related

Unable to pass values to a function on click of a button

I am a beginner in javascript and was just trying to implement a simple form. However, I am unable to submit it since the values that are entered in the textbox are not getting passed further to the function that I call on clicking the submit button.
I have seen similar questions and even followed the answers still for some reason I only get undefined instead of the data passed.
Below is the code:
Html:
<form >
First Name:
<input
type="text"
id="txtfirstName"
/>
Second Name:
<input
type="text"
id="txtsecondName"
/>
User Name:
<input
type="text"
id="txtuserName"
/>
Email:
<input
type="text"
id="txtemail"
/>
Password:
<input
type="password"
id="txtpassword"
/>
<input
type="button"
id= "btnsubmit"
value="SUBMIT"
onclick="submit("name","surname","user","mail","word")"
/>
</form>
<script>
var fname = "";
var sname = "";
var uname = "";
var email = "";
var password = "";
var submitButton = document.getElementById("btnsubmit");
submitButton.onclick = function submit(fname,sname,uname,email,password) {
confirm("Are you sure you want to submit the form?");
if(confirm) {
alert("Below is the data entered by you:" + "\n" + fname + "\n" + sname + "\n" + uname + "\n"
+ email + "\n" + password )
}
}
</script>
The function called at the onclick attribute for the input does not exist and it will never work.
What you did was almost correct. You added the click event for the submit button that calls a function. That function will always (i think so) have one parameter (Event type) and not those added by you.
In order to retrieve the values for the inputs, you need to retrieve them in that function.
Check the snippet below.
var submitButton = document.getElementById("btnsubmit");
submitButton.onclick = function submit() {
confirm("Are you sure you want to submit the form?");
if(confirm) {
var fname = document.getElementById('txtfirstName').value;
var sname = document.getElementById('txtsecondName').value;
var uname = document.getElementById('txtuserName').value;
var email = document.getElementById('txtemail').value;
var password = document.getElementById('txtpassword').value;
alert("Below is the data entered by you:" + "\n" + fname + "\n" + sname + "\n" + uname + "\n"
+ email + "\n" + password )
}
}
<form >
First Name:
<input
type="text"
id="txtfirstName"
/>
Second Name:
<input
type="text"
id="txtsecondName"
/>
User Name:
<input
type="text"
id="txtuserName"
/>
Email:
<input
type="text"
id="txtemail"
/>
Password:
<input
type="password"
id="txtpassword"
/>
<input
type="button"
id= "btnsubmit"
value="SUBMIT"
/>
</form>
Here I fixed that:
<form >
First Name:
<input
type="text"
id="txtfirstName"
/>
Second Name:
<input
type="text"
id="txtsecondName"
/>
User Name:
<input
type="text"
id="txtuserName"
/>
Email:
<input
type="text"
id="txtemail"
/>
Password:
<input
type="password"
id="txtpassword"
/>
<input
type="button"
id= "btnsubmit"
value="SUBMIT"
/>
</form>
<script>
var submitButton = document.getElementById("btnsubmit");
submitButton.onclick = function () {
var fname = document.getElementById("txtfirstname").value;
var sname = document.getElementById("txtsecondname").value;
var uname = document.getElementById("txtusername").value;
var email = document.getElementById("txtemail").value;
var password = document.getElementById("password").value;
confirm("Are you sure you want to submit the form?");
if(confirm) {
alert("Below is the data entered by you:" + "\n" + fname + "\n" + sname + "\n" + uname + "\n"
+ email + "\n" + password )
}
}
</script>
Here is a fiddle working:
https://jsfiddle.net/Lk9t0bxj/
<form>
First Name:
<input
type="text"
id="txtfirstName"
/>
Second Name:1
<input
type="text"
id="txtsecondName"
/>
User Name:
<input
type="text"
id="txtuserName"
/>
Email:
<input
type="text"
id="txtemail"
/>
Password:
<input
type="password"
id="txtpassword"
/>
<input
type="button"
id= "btnsubmit"
value="SUBMIT"
onclick="submit()"
/>
</form>
Javascript:
var fname = "";
var sname = "";
var uname = "";
var email = "";
var password = "";
var submitButton = document.getElementById("btnsubmit");
submitButton.onclick = function submit() {
confirm("Are you sure you want to submit the form?");
if(confirm) {
fname = document.getElementById('txtfirstName').value;
sname = document.getElementById('txtsecondName').value;
uname = document.getElementById('txtuserName').value;
email = document.getElementById('txtemail').value;
password = document.getElementById('txtpassword').value;
alert("Below is the data entered by you:" + "\n" + fname + "\n" + sname + "\n" + uname + "\n"
+ email + "\n" + password )
}
}
There were some errors:
Confusion with quotation marks:
onclick="submit("name","surname","user","mail","word")"
There is no need to pass the name fields:
onclick="submit()"
You should get the field values and put it in the variables defined:
fname = document.getElementById('txtfirstName').value;
Another way of doing this is by adding onsubmit callback to your <form> element, and changing your <input> type to submit. You don't have to add in individual ids for all of your input, instead you can use event.target[INPUT_NAME] to get your input element, and get the value of that element with INPUT.value.
Working sample code :
const handleOnSubmit = event => {
event.preventDefault();
const { fname, sname, uname, email, password } = event.target;
confirm("Are you sure you want to submit the form?");
if (confirm) {
alert(
"Below is the data entered by you:" +
"\n" +
fname.value +
"\n" +
sname.value +
"\n" +
uname.value +
"\n" +
email.value +
"\n" +
password.value
);
}
};
<form onsubmit="handleOnSubmit(event)">
First Name:
<input type="text" name="fname" />
Second Name:
<input type="text" name="sname" />
User Name:
<input type="text" name="uname" />
Email:
<input type="text" name="email" />
Password:
<input type="password" name="password" />
<input type="submit" />
</form>
Other way to do this is use add.event.listener and template literals.
var submitButton = document.getElementById("btnsubmit");
submitButton.addEventListener("click", function(e){
e.preventDefault()
var fname = document.getElementById("txtfirstName").value;
var sname = document.getElementById("txtsecondName").value;
var uname = document.getElementById("txtuserName").value;
var email = document.getElementById("txtemail").value;
var password = document.getElementById("txtpassword").value;
confirm("Are you sure you want to submit the form?");
if(confirm) {
alert(`Below is the data entered by you: \n ${fname} \n ${sname} \n ${uname} \n ${email} \n ${password}`)
}
})

Create array from Dynamic table

How can I create an array from this table/form? The onclick function formData() from the dynamic table only returns a concatenated string. I need to create an associative array in JSON using the 'device' variable as key, however I'll settle for any sort of array at all. Clearly, I'm not very good at this...
function createInputTable()
{
var num_rows = document.getElementById('rows').value;
var tableName = document.getElementById('conn_input_device').value;
var column_number = 2;
var tdefine = '<form id="form"><table id="table" border = "1">\n';
var theader = '<tr><th>No</th><th>Input</th><th>Output</th></tr>\n';
var caption = '<caption><input id="device" value ="' + tableName + '" /></caption>';
var tbody = '';
var tfooter = '</table>';
var createNewDevice = '<button onclick="formData();">Form Data</button></form>'
var i = 0;
for (var i= 0; i < num_rows; i++)
{
tbody += '<tr><td>' + (i+1) + '</td><td><input class="cell" id="i'+ i + '" type = "text"/></td>';
tbody += '<td><input class="cell" id="o'+ i + '" type="text"/></td></tr>\n';
}
document.getElementById('wrapper').innerHTML = caption + tdefine + theader + tbody + tfooter + createNewDevice;
}
function formData()
{
var cellData = document.getElementById("form");
//var device = document.getElementById('device').value;
//var j;
var obj = [];
for(j=0; j< cellData.length; j++)
{
obj += cellData[j].value;
}
var json = JSON.stringify(obj);
alert (json);
//document.getElementById('result').innerHTML = json;
}
<form id="tableGen" name="table_gen">
<label>Connecting device: <input type = "text" name = "conn_input_device" id = "conn_input_device"/></label><br />
<label>Number of inputs: <input type="text" name="rows" id="rows"/></label><br />
<input name="generate" type="button" value="Create Input Table!" onclick='createInputTable();'/>
</form>
<div id="wrapper"></div>
1) This my answer how do this on VueJS and jQuery
2) Vanilla js - CODEPEN - DEMO
// Get DOM elements
const $el = [
'#tmpl',
'#user-count',
'#people-count',
'#form-items',
'#btn-add',
'#form',
].reduce((res, item) => {
const method = item.startsWith('#')
? 'querySelector'
: 'querySelectorAll'
const key = item
.replace(/\W/ig, ' ').trim()
.replace(/\s+\w/g, v => v.trim().toUpperCase())
res[key] = document[method](item)
return res
}, {})
// Variable for dynamic template
const tmpl = $el.tmpl.innerHTML.trim()
// Click on Add new button
$el.btnAdd.addEventListener('click', () => {
const peopleCount = +$el.peopleCount.value
const html = Array(peopleCount)
.fill(tmpl)
.join('')
$el.formItems.insertAdjacentHTML('beforeend', html)
})
// Submit form
$el.form.addEventListener('submit', e => {
e.preventDefault()
alert('Submit form by ajax or remove this method for default behavior')
})
// Add form click (it's need for dynamic handler on child elements)
$el.form.addEventListener('click', e => {
// Delete behaviors
if (e.target.classList.contains('btn-del') && confirm('Are you sure?')) {
e.target.closest('.row').remove()
}
})
<div id="app">
<div>
<div>
<button id="btn-add">Add new user</button>
<label>Number of People:</label>
<input type="number" id="people-count" value="1" min="1">
</div>
<form id="form">
<div id="form-items" data-empty="Users list is empty"></div>
<button>Send</button>
</form>
</div>
</div>
<script type="text/x-template" id="tmpl">
<div class="row">
<label>
Name:
<input class="people" name="name[]">
</label>
<label>
Surname:
<input class="people" name="surname[]">
</label>
<label>
Email:
<input type="email" class="people" name="email[]">
</label>
<button class="btn-del">Delete</button>
</div>
</script>
<style>
.people {
width: 80px;
}
#form-items:empty + button {
display: none;
}
#form-items:empty:before {
content: attr(data-empty);
display: block;
}
</style>
I have edited your code,
function createInputTable()
{
var num_rows = document.getElementById('rows').value;
var tableName = document.getElementById('conn_input_device').value;
var column_number = 2;
var tdefine = '<form id="form"><table id="table" border = "1">\n';
var theader = '<tr><th>No</th><th>Input</th><th>Output</th></tr>\n';
var caption = '<caption><input id="device" value ="' + tableName + '" /></caption>';
var tbody = '';
var tfooter = '</table>';
var createNewDevice = '<button onclick="formData();">Form Data</button></form>'
var i = 0;
for (var i= 0; i < num_rows; i++)
{
tbody += '<tr><td>' + (i+1) + '</td><td><input class="cell" id="i'+ i + '" type = "text"/></td>';
tbody += '<td><input class="cell" id="o'+ i + '" type="text"/></td></tr>\n';
}
document.getElementById('wrapper').innerHTML = caption + tdefine + theader + tbody + tfooter + createNewDevice;
}
function formData()
{
var cellData = document.getElementsByTagName("tr");
var obj = [];
for(var i=0;i<cellData.length-1;i++){
obj.push(document.getElementById("i"+i).value);
obj.push(document.getElementById("o"+i).value);
}
alert(JSON.stringify(obj));
}
<form id="tableGen" name="table_gen">
<label>Connecting device: <input type = "text" name = "conn_input_device" id = "conn_input_device"/></label><br />
<label>Number of inputs: <input type="text" name="rows" id="rows"/></label><br />
<input name="generate" type="button" value="Create Input Table!" onclick='createInputTable();'/>
</form>
<div id="wrapper"></div>

Javascript query fix

I am new to Javascript programming, can anyone help me on fixing the below script. In this script, I am getting some input from the user and then adding it to an array. Finally displaying it in a table. But for some reason, the last entry in the array overwrites all the previous entries in it.
var CountryList = new Array();
var arrNum = 0;
function initCountry(name, capital) {
this.name = name;
this.capital = capital;
//Comments
//alert(arrNum);
CountryList.push(this);
document.getElementsByName("countryName")[0].value = "";
document.getElementsByName("capitalCity")[0].value = "";
}
function funcSaveButton() {
var txt1 = document.getElementsByName("countryName")[0];
var txt2 = document.getElementsByName("capitalCity")[0];
initCountry(txt1.value, txt2.value);
//alert(txt1.value +":"+ txt2.value);
arrNum++;
}
function displayList() {
var i;
document.write("<table border='2'>");
document.write("<tr> <td> Country Name </td> <td> Capital City </td> </tr>")
for (i = 0; i < CountryList.length; i++) {
//alert("i="+i);
document.write("<tr>");
document.write("<td> " + CountryList[i].name + "</td>");
document.write("<td> " + CountryList[i].capital + "</td>");
document.write("</tr>");
}
document.write("</table>");
}
Country Name: <input type="text" name="countryName" required></input>
<Br> Capital City: <input type="text" name="capitalCity" required></input><br><br>
<input type="button" name="saveButton" value="Save Details!!" onclick="funcSaveButton()"></input>
<input type="button" name="displayButton" value="Display Country List!!" onclick="displayList()"></input>
You are pushing window object to CountryList
inside function this object is window.
use this CountryList.push({name:name,capital:capital});
var CountryList = new Array();
var arrNum = 0;
function initCountry(name, capital)
{
this.name = name;
this.capital = capital;
//Comments
//alert(arrNum);
CountryList.push({name:name,capital:capital});
document.getElementsByName("countryName")[0].value = "";
document.getElementsByName("capitalCity")[0].value = "";
}
function funcSaveButton()
{
var txt1 = document.getElementsByName("countryName")[0];
var txt2 = document.getElementsByName("capitalCity")[0];
initCountry(txt1.value, txt2.value);
//alert(txt1.value +":"+ txt2.value);
arrNum++;
}
function displayList()
{
console.log(CountryList);
var i;
document.write("<table border='2'>");
document.write("<tr> <td> Country Name </td> <td> Capital City </td> </tr>")
for(i=0;i<CountryList.length;i++)
{
//alert("i="+i);
document.write("<tr>");
document.write("<td> "+ CountryList[i].name + "</td>");
document.write("<td> "+ CountryList[i].capital + "</td>");
document.write("</tr>");
}
document.write("</table>");
}
Country Name: <input type="text" name="countryName" required></input><Br>
Capital City: <input type="text" name="capitalCity" required></input><br><br>
<input type="button" name="saveButton" value="Save Details!!" onclick="funcSaveButton()"></input>
<input type="button" name="displayButton" value="Display Country List!!" onclick="displayList()"></input>

Loading data on the same form page after submitting

I have a tiny problem with this college assignment. When the user inputs their data, an account id number is created. I've worked on that and it works like it should. But here's the problem: after the user clicks the submit button and the account id number is created, what they entered needs to be displayed below it. The assignment says I need to create a function called displayNewAccount and put in into one of the other functions. I put in inside the createEventListeners function. The text needs to be displayed in a custom ID (account) on the HTML page. The data entered into the first name input (fnameinput) should display after "First Name" (fname) and the last name input (lnameinput) should display after "Last Name" (lname) and so on. If the displayNewAccount function has to be moved inside another function then that is totally fine. I've looked online and found several examples, but I couldn't get them to work for me. What am I doing wrong? Thanks for the help.
HTML
<article>
<h2>New Account Information</h2>
<form>
<fieldset id="deliveryinfo">
<label>First Name</label><input type="text" id="fnameinput" name="fname">
<label>Last Name</label><input type="text" id="lnameinput" name="lname">
<label>Street Address</label><input type="text" id="addrinput" name="address">
<label>City</label><input type="text" id="cityinput" name="city">
<label>State</label><input type="text" id="stateinput" name="state">
<label>Zip</label><input type="text" id="zipinput" name="zip">
<label>Account ID</label><input type="text" id="accountidbox" name="accountid">
<input type="button" id="submitBtn" value="Create Account">
</fieldset>
<!-- New section -->
<fieldset>
<div id="account">
<!-- Data is displayed in here. -->
</div>
</fieldset>
</form>
</article>
JavaScript
var newAccountObject = {};
var newAccountSubmission;
function createID() {
var fname = document.getElementById("fnameinput");
var lname = document.getElementById("lnameinput");
var zip = document.getElementById("zipinput");
var account = document.getElementById("accountidbox");
var fields = document.getElementsByTagName("input");
var acctid;
var firstInit;
var lastInit;
if (fname !== "" || lname !== "" || zip !== "") {
firstInit = fname.value.charAt(0).toUpperCase();
lastInit = lname.value.charAt(0).toUpperCase();
acctid = firstInit + lastInit + zip.value;
account.value = acctid;
newAccountObject = {};
for(var i = 0; i < fields.length - 1; i++) {
newAccountObject[fields[i].name] = fields[1].value;
}
}
}
function createString() {
newAccountSubmission = JSON.stringify(newAccountObject);
}
function createEventListeners() {
var fname = document.getElementById("fnameinput");
var lname = document.getElementById("lnameinput");
var zip = document.getElementById("zipinput");
if (fname.addEventListener) {
fname.addEventListener("change", createID, false);
lname.addEventListener("change", createID, false);
zip.addEventListener("change", createID, false);
}
else if (fname.attachEvent) {
fname.attachEvent("onchange", createID);
lname.attachEvent("onchange", createID);
zip.attachEvent("onchange", createID);
}
if (button.addEventListener) {
button.addEventListener("click", createString, false);
}
else if (button.attachEvent) {
button.attachEvent("onclick", createString);
}
// Displays an account summary section when the "Create Account" button is clicked.
function displayNewAccount() {
document.getElementById("account").innerHTML = "First Name: " + fname + "<br>" + "Last Name: " + lname + "<br>" + "Address: " + addrinput + "<br>" + "City: " + cityinput + "<br>" + "State: " + stateinput + "<br>" + "Zip: " + zipinput + "<br>" + "Account ID: " + accountidbox;
}
if (window.addEventListener) {
window.addEventListener("click", displayNewAccount, false);
}
else if (window.attachEvent) {
window.attachEvent("onclick", displayNewAccount);
}
}
if (window.addEventListener) {
window.addEventListener("load", createEventListeners, false);
}
else if (window.attachEvent) {
window.attachEvent("onload", createEventListeners);
}

javascript issue with inputting a number in a form

I am inputting age in a form in HTML which has a age field. I want to take input in age as a number only so I have defined age field as number type. I am putting a check in the javascript code if(typeof name === "string" && isNaN("age") ==="false").I observed during debugging that typeof age is string.I don't know how is it getting converted to string type automatically.
I have attached my HTML and javascript codes.Plz help...
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery- 1.11.3.min.js"></script>
</head>
<script src="form_js.js"></script>
<body>
<form id="myForm">
First Name:
<input type="text" id="field1">
<br> Last Name:
<input type="text" id="field2">
<br> Age:
<input type="number" id="field3">
<br>
<br> Gender:
<select id="field5">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</form>
<p>
<input type="button" onclick="insRow('Table1')" value="Insert">
</p>
<table id="Table1" style="width:100%">
<tr>
<td>Name</td>
<td>Age</td>
<td>Gender</td>
</tr>
</table>
</body>
</html>
Javascript:
var count = 0;
function insRow() {
count += 1;
var x, y, z, a, w;
var w = document.getElementById('Table1').insertRow(count);
var name = $("#field1").val() + " " + $("#field2").val();
//var age = $('#field3').val();
//var age = $('#myForm :field3');
//var Email = $("#field4").val();
var gender = $("#field5").val();
//w = document.getElementById('Table1').insertRow(count);
//var first_name = document.getElementById("field1").value;
//var last_name = document.getElementById("field2").value;
var age = document.getElementById("field3").value;
//var gender = document.getElementById("field5").value;
if (typeof name === "string") //&& isNaN("age") ==="false")
{
x = w.insertCell(0);
y = w.insertCell(1);
a = w.insertCell(2);
x.innerHTML = name //" " + last_name;
y.innerHTML = age;
a.innerHTML = gender;
document.getElementById("myForm").reset();
} else alert("Invalid Data");
//var rows += "<tr><td>" + name + "</td><td>" + age + "</td><td>" + Email + "</td><td>" + Gender +"</td></tr>";
//$("#Table1 tbody").append(rows);
}
When you get any value from HTML it is by default string. To convert it to Number use parseInt or parseFloat according to your requirement.
The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
var age = parseInt(document.getElementById("field3").value, 10);
OR
The parseFloat() function parses a string argument and returns a floating point number.
var age = parseFloat(document.getElementById("field3").value);
When you are checking for NaN, use variable age without quotes. And for strict comparison false should be without quotes.
isNaN("age") ==="false")
Should be
isNaN(age) === false) // Without quotes for age and false
Note that document.getElementById(someId).value will always return you string type, if any. There are several methods to parse like parseInt(), parseFloat() and also +()
var str = document.getElementById('num').value;
var num = +(str);
alert("Type of " + num + " is " + (typeof num));
var price = +(document.getElementById('price').value);
alert("Type of " + price + " is " + (typeof price));
<input type="text" id="num" value="56" />
<input type="text" id="price" value="9.13" />

Categories