I'm having trouble getting a javascript function to run on the data from an html form.
I have this form in HTML:
<form id = "form1" onSubmit="getFormObj('form1')">
First name: <input type="text" name="FirstName" value="First"><br>
Last name: <input type="text" name="LastName" value="Last"><br>
Email: <input type="text" name="email" value="johndoe#email.com"><br>
Phone Number: <input type="text" name="phonenumber" value="Phone Number"><br>
<input id="button1" type="submit" value="Create Patient">
</form>
<script type="text/javascript">
document.write(PatientLabel);
</script>
The submit button is hooked up to a JavaScript function in JQuery:
$('#button1').click(function() {
createpatient(this);
});
The Javascript function I'm trying to run stores the form data to an object and then sets PatientLabel to one of the object's values:
var patientdata = {};
var PatientLabel = "";
function createpatient(formId) {
//Turn form data into array data.
var inputs = $('#'+formId).serializeArray();
$.each(inputs, function (i, input) {
patientdata[input.name] = input.value;
});
//If we got this far, print an example
patientLabel = patientdata["FirstName"];
}
However, when I run this code, the HTML Script that's supposed to print patientLabel doesn't show anything! Where did I go wrong?
Final Example:
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Change As You Like</title>
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='rename.js'></script>
</head>
<body>
<form id='form1' name='form1'>
<label id='firstNameLabel' for='firstName'>First Name: </label><input type='text' id='FirstName' name='firstName' value='First' />
<label id='lastNameLabel' for='lastName'>Last Name: </label><input type='text' id='lastName' name='lastName' value='Last' />
<label id='emailLabel' for='email'>email: </label><input type='text' id='email' name='email' value='johndoe#email.com' />
<label id='phoneNumberLabel' for='phoneNumber'>phone: </label><input type='text' id='phoneNumber' name='phoneNumber' value='(555)555-5555' />
<input type='submit' id='button1' name='button1' value='Create Patient' />
</form>
</body>
</html>
Now on rename.js:
$(function(){
function createPatient(formElement) {
var patientData = {}, inputs = formElement.serializeArray();
$.each(inputs, function(i, o){
patientData[o.name] = o.value;
});
console.log(patientData.firstName);
// in FireBug could see Object like: console.log(patientData);
}
$('#form1').submit(function(){
// run other functions here
createPatient($(this));
return false;
});
});
You might change the way you call your function. Try this code if this will help createpatient($(this).attr('id'));
Related
I have written a program which takes inputs and store in local storage as an object into an array. until I don't refresh the page and give inputs, it makes a NEW array every time and put those input values with the same property into an object. bur whenever I refresh the page and run that function again, the local storage lose it's all previous data and start storing new data. although I didn't style the structure and didn't give any input validation. but jus insert inputs and check the local-storage and you will understand.
How can I store those data into local-storage even if the page has been refreshed?
Thanks in advance.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form id="regform">
<div id="name">
<h2 class="name">Name</h2>
<input id="firstName" type="text" name="first" value=""><br>
<label class="firstlabel" name="firstname">first name</label>
<input id="lastName" type="text" name="last" value=""><br>
<label class="lastlabel" name="lastname">last name</label>
</div>
<h2 class="name">Email</h2>
<input id="email" type="text" name="email">
<h2 class="name">Password</h2>
<input id="pass" type="password" name="password" autocomplete="off">
<h2 class="name">Phone</h2>
<input id="code" type="text" name="area_code">
<label class="area-code">Area Code</label>
<input id="number" type="text" name="phone">
<label class="phone-number">Phone Number</label>
<button type="submit" id="btnreg" >Register</button>
</form>
<script>
var fname=document.getElementById("firstName");
var lname=document.getElementById("lastName");
var btn=document.getElementById("btnreg");
var password=document.getElementById("pass");
var mail=document.getElementById("email");
var ariacode=document.getElementById("code");
var pnumber=document.getElementById("number");
let datas = [];
var addData= (ev)=>{
ev.preventDefault();
var data = {
name: fname.value +" "+ lname.value,
passcode: password.value,
email: mail.value,
phonenumber: "+"+ariacode.value +" "+ pnumber.value
};
datas.push(data);
document.getElementById('regform').reset();
var data_serialized = JSON.stringify(datas);
localStorage.setItem("datas", data_serialized);
var data_deserialized = JSON.parse(localStorage.getItem("datas"));
};
document.addEventListener('DOMContentLoaded', ()=>{
btn.onclick=addData;
});
</script>
</body>
</html>
Have you tried checking the local storage to see if it's not empty before assigning new data to it? If you do not, you might be re-writing the local storage each time the page is refreshed. Please show your code.
I changed your code a bit and now it works.
The problem was: You just overwrite the storage entry on every submit.
Solution: read existing entry, push new data, write new entry.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form id="regform">
<div id="name">
<h2 class="name">Name</h2>
<input id="firstName" type="text" name="first" value=""><br>
<label class="firstlabel" name="firstname">first name</label>
<input id="lastName" type="text" name="last" value=""><br>
<label class="lastlabel" name="lastname">last name</label>
</div>
<h2 class="name">Email</h2>
<input id="email" type="text" name="email">
<h2 class="name">Password</h2>
<input id="pass" type="password" name="password" autocomplete="off">
<h2 class="name">Phone</h2>
<input id="code" type="text" name="area_code">
<label class="area-code">Area Code</label>
<input id="number" type="text" name="phone">
<label class="phone-number">Phone Number</label>
<button type="submit" id="btnreg" >Register</button>
</form>
<script>
var fname=document.getElementById("firstName");
var lname=document.getElementById("lastName");
var btn=document.getElementById("btnreg");
var password=document.getElementById("pass");
var mail=document.getElementById("email");
var ariacode=document.getElementById("code");
var pnumber=document.getElementById("number");
let datas = [];
var addData= (ev)=>{
ev.preventDefault();
var data = {
name: fname.value +" "+ lname.value,
passcode: password.value,
email: mail.value,
phonenumber: "+"+ariacode.value +" "+ pnumber.value
};
var datas = JSON.parse(localStorage.getItem("datas"));
datas.push(data);
document.getElementById('regform').reset();
var data_serialized = JSON.stringify(datas);
localStorage.setItem("datas", data_serialized);
};
document.addEventListener('DOMContentLoaded', ()=>{
btn.onclick=addData;
});
</script>
</body>
</html>
I would like to add some text before the onchange="input()" function.
anyone knows the trick? cheers
<head>
<script type="text/javascript">
function input(){
var input_taker = document.getElementById('email').value;
document.getElementById('display').innerHTML = input_taker;
}
</script>
</head>
<form method="post" action="#">
<input type="text" name="email" placeholder="email#example.com" id="email" onchange="input()">
<input type="submit" name="save" value="save">
I am creating a library management system and I can't validate the HTML(To add a book copy to the library) with javaScript. I will be uploading the HTML and JS files. When I click on submit I am redirected to the librarian's dashboard. It would be a great help if you could help out with the code.
var btnSubmit = document.getElementById("btn-submit");
btnSubmit.addEventListener("click", function(e) {
e.preventDefault();
validate(e);
});
function validate(e) {
var numbers = /[^0-9]/;
var isbn = document.getElementById("isbn").value;
var copies = document.getElementById("copies").value;
if (isbn.length != 13) {
alert("Please enter a valid ISBN Number");
} else if (isbn.match(numbers)) {
alert("Please enter a valid ISBN Number");
} else if (copies == "") {
alert("Please fill in the number of copies");
} else if (copies.match(numbers)) {
alert("Please enter a valid number of copies");
}
}
<!doctype html>
<html>
<head>
<title>Add Book Copy</title>
<link rel="stylesheet" href="../fonts/fonts.css" />
<link rel="stylesheet" href="../style/style.css" />
<link rel="stylesheet" href="../style/librarian.css">
<link rel="stylesheet" href="../style/add_book.css">
</head>
<body>
<header>
<h2>Librarian</h2>
<form action="../admin/logout.php" method="post">
<input type="submit" id="btn-logout" value="Logout">
</form>
<br style="clear: both" />
</header>
<form action="../admin/add_book_copy.php" method="post">
<h2>Add Book Copy</h2>
<input type="text" name="copyId" placeholder="Book Copy Id" />
<input type="text" name="isbn" placeholder="ISBN" />
<input type="text" name="date" id="date" hidden />
<input type="submit" value="submit" id="btn-submit" />
</form>
<script src="../js/add_book_copy.js"> </script>
</body>
</html>
You have not given id to your input's i.e : isbn and copies that's the reason it is not working .I have given id to input boxes .i.e :
var btnSubmit = document.getElementById("btn-submit");
btnSubmit.addEventListener("click", function(e) {
e.preventDefault();
validate(e);
});
function validate(e) {
var numbers = /[^0-9]/;
//you are getting values by using id give input id attribute as well
var isbn = document.getElementById("isbn").value;
var copies = document.getElementById("copies").value;
if (isbn.length != 13) {
alert("Please enter a valid ISBN Number");
} else if (isbn.match(numbers)) {
alert("Please enter a valid ISBN Number");
}
if (copies == "") {
alert("Please fill in the number of copies");
}
else if (copies.match(numbers)) {
alert("Please enter a valid number of copies");
}
}
<!doctype html>
<html>
<head>
<title>Add Book Copy</title>
<link rel="stylesheet" href="../fonts/fonts.css" />
<link rel="stylesheet" href="../style/style.css" />
<link rel="stylesheet" href="../style/librarian.css">
<link rel="stylesheet" href="../style/add_book.css">
</head>
<body>
<header>
<h2>Librarian</h2>
<form action="../admin/logout.php" method="post">
<input type="submit" id="btn-logout" value="Logout">
</form>
<br style="clear: both" />
</header>
<form action="../admin/add_book_copy.php" method="post">
<h2>Add Book Copy</h2>
<!--added id-->
<input type="text" name="copyId" id="copies" placeholder="Book Copy Id" />
<input type="text" name="isbn" id="isbn" placeholder="ISBN" />
<input type="text" name="date" id="date" hidden />
<input type="submit" value="submit" id="btn-submit" />
</form>
<script src="../js/add_book_copy.js"> </script>
</body>
</html>
You can simply add the pattern attribute in the input tag
<input type="text" name="copyId" placeholder="Book Copy Id" pattern="[0-9]+" />
<input type="text" name="isbn" placeholder="ISBN" pattern="[0-9]{13}"/>
<input type="text" name="date" id="date" hidden />
<input type="submit" value="submit" id="btn-submit" />
With the help of this , you will not need the javascript function .
You did not give id to <input>:
<input type="text" name="copyId" placeholder="Book Copy Id" id="copies"/>
<input type="text" name="isbn" placeholder="ISBN" id="isbn"/>
I want to save this data in JSON format without using PHP ,when user give the value and press send ,its data add in JSON so that ,I can use this JSON as Database.
<!DOCTYPE html>
<html>
<body>
<form action="action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Thank you so much for your help :) in advance
You can iterate through your form and collect it's values in an array, which you can encode in JSON format.
<!DOCTYPE html>
<html>
<body>
<form action="action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit" onclick="logJsonInputs()">
</form>
<script type="text/javascript">
function logJsonInputs() {
var nameFormElements = document.getElementById("name_form").elements;
var inputs = [];
for(var i = 0; i < nameFormElements.length; i++) {
var element = nameFormElements[i];
inputs[element.name] = element.value;
}
var jsonInputs = JSON.stringify(inputs);
console.log(jsonInputs);
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
function stringifyForm(formObject)
{
var jsonObject = {};
var inputElements = formObject.getElementsByTagName("input");
inputElements = Array.prototype.slice.apply(inputElements); //Because I want to use forEach and getElementsByTagName returns an object.
inputElements.forEach(function(e,i,a)
{
if (e.type != "submit")
{
jsonObject[e.name] = e.value;
}
}
);
$.post("https://www.apiaas.com/consume.php",
{
"data":jsonObject
},
function(data)
{
console.log(data);
}
);
}
function jquerySolution(formObject)
{
var jsonObject = JSON.stringify( $(formObject).serializeArray() );
$.post("https://www.apiaas.com/consume.php",
{
"data":jsonObject
},
function(data)
{
console.log(data);
}
);
}
</script>
</head>
<body>
<form onsubmit="jquerySolution(this);return false;">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<button type="submit" value="Submit">Submit</button>
</form>
</body>
</html>
I am trying to create a circular progress loader that shows each progress of filling form input . As form is filled completely . The loader should show 100%. Here's the whole code I am using .
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
First name: <input type="text" name="firstname" required="required"><br>
Last name: <input type="text" name="lastname" required="required">
Age: <input type="text" name="age" required="required">
Gender: <input type="text" name="gender" required="required">
City: <input type="text" name="city" required="required">
Locality: <input type="text" name="locality">
Address: <input type="text" name="address">
</form>
<p id='percentage'>0% completed</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="myctrl" ng-app='app' ng-controller="MyCtrl">
<p ng-model="counter"></p>
<input type="text" value="{{counter}}" class="dial">
</div>
</body>
<script src="https://raw.github.com/aterrien/jQuery-Knob/master/js/jquery.knob.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>
<script>
$(".dial").knob({
readOnly: true,
fgColor: "#00ABC6",
bgColor: "#666666",
thickness: 0.2
});
$(document).ready(function(){
$('input').on('change', function(){
var cntreq = 0;
var cntvals = 0;
$('input').each(function(i, val) {
if($(this).attr('required') == 'required') {
cntreq++;
if($(this).val() != '') {
cntvals++;
}
}
});
var count = (cntvals/cntreq)*100;
//$('#percentage').empty();
//$('#percentage').append(count+'% completed');
angular.element($("#myctrl")).scope().anyFunc(count);
//$('.dial').val(count);
});
});
angular.module('app', [])
.controller('MyCtrl', function ($scope) {
$scope.anyFunc = function (var1) {
alert(var1);
$scope.counter = var1;
};
});
</script>
</body>
</html>
This loader changes as wechange value of input tag so I am using angular js to pass count variable to input value . So as we fill each input it will change automatically .
I found this loader from here "http://jsfiddle.net/CU7KM/"
and form percent calculator from here "http://jsfiddle.net/ktozh5sd/2/".
I am trying to achieve a circular loader that show progress of every input field.