Replace innerhtml on form submit with javascript - javascript

I want to have a form that asks the user their name, then welcomes them to the website with that name without redirecting to a different page or reloading. So basically replace a form with "Welcome NAME" after submit is clicked.
My code:
<div id="welcomeText">
<form onsubmit="changeText()" method="post">
Name: <input type="text" name="fname">
<input type="submit">
</form>
</div>
<script>
function changeText() {
var name = document.getElementById(welcomeForm).fname.value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
}
</script>

You need to give a name to the form before trying to access it, something like this:
//create the name attribute for the form
<form onsubmit="changeText()" method="post" name="myForm">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<script>
function changeText() {
//access myForm using document object
var name = document.name.fname.value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
}
</script>

<div id="welcomeText">
<form onsubmit="changeText()" method="post" id="welcomeForm">
Name: <input type="text" name="fname">
<input type="submit">
</form>
</div>
<script>
function changeText() {
var name = document.getElementById("welcomeForm").fname.value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
}
</script>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="welcomeText">
Name: <input type="text" name="fname" id="name">
<input id="submit" type="submit" onclick="changeText()" onsubmit="changeText()">
</div>
<script>
function changeText() {
var name = document.getElementById("name").value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
document.getElementById("name").style.display = "none";
document.getElementById("submit").style.display = "none";
}
</script>
</body>
</html>
Try this it will display "welcome user" and also make button and input disappear. In this case you don't even need a form. You can access the name directly from the input without ever submitting the form.

Here we are:
<div id="welcomeText">
<form id="myform" method="post">
Name: <input type="text" name="fname">
<input type="submit">
</form>
</div>
<script>
var form = document.getElementById("myform");
form.addEventListener('submit', function (e) {
e.preventDefault(); // This will prevent submitting the form
var name = form.fname.value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
});
</script>

Related

add data to array/object via form javascript

I have a form. If you fill in the form, the data must be placed in the constant USERS with (vanilla) javascript. Can somebody help me, please?
It is also intended that the CONST USERS will be shown in the div 'show', but doesn't have to.
My Code:
<!DOCTYPE html>
<head>
<title>Users</title>
</head>
<body>
<main>
<form>
<label for="ordername">Name:</label>
<input type="text" id="name" name="name"/>
<label for="age">Age:</label>
<input type="number" id="age" name="age"/>
<input type="submit" value="submit" class="submit"/>
</form>
<div class="show">
</div>
</main>
<script>
const USERS = [
{
name: Brit,
age: 45,
},
{
name: John,
age: 55,
}];
</script>
</body>
</html>
in your code const = USERS is also not a valid. read syntax before use.
You can push as below
const USERS = [];
var form_el = document.getElementById("myForm");
form_el.addEventListener("submit", function(evt) {
evt.preventDefault();
var name = document.getElementById("name").value;
var age = document.getElementById("age").value;
var objsingle = {};
objsingle.name = name;
objsingle.age = age;
USERS.push(objsingle);
//console.log(USERS);
document.getElementById("show").innerHTML = JSON.stringify(USERS);
});
<!DOCTYPE html>
<head>
<title>Users</title>
</head>
<body>
<main>
<form id="myForm">
<label for="ordername">Name:</label>
<input type="text" id="name" name="name"/>
<label for="age">Age:</label>
<input type="number" id="age" name="age"/>
<input type="submit" value="submit" class="submit"/>
</form>
<div class="show" id="show">
</div>
</main>
</body>
</html>
In your code with the provided users example, you have name: Brit and name: John, They should be strings like, name: "Brit", and name: "John".
In your comment "Oh I forgot to say if I leave the website again that the data will remain on the webpage" do you mean using something like localstorage ?
The following snippet should do it:
<!DOCTYPE html>
<head>
<title>Users</title>
</head>
<body>
<main>
<form id="user-form">
<label for="ordername">Name:</label>
<input type="text" id="name" name="name"/>
<label for="age">Age:</label>
<input type="number" id="age" name="age"/>
<input type="submit" value="submit" class="submit"/>
</form>
<div class="show"></div>
</main>
<script>
const users = JSON.parse(localStorage.getItem("users") || "[]");
console.log(users);
const form = document.getElementById("user-form");
form.addEventListener("submit", function(e) {
e.preventDefault();
const name = document.getElementById("name").value;
const age = document.getElementById("age").value;
const user = { name, age };
users.push(user);
localStorage.setItem("users", JSON.stringify(users));
console.log(users);
});
</script>
</body>
</html>

How to save input in an array then add to saved input

I am creating a form with two text boxes: Task and Description. What I want to do is be able to console.log in both boxes and save the input through a submit button.
i.e:
task: do laundry
Description: do a buttload of laundry(idk lol)
Alright, I got that down(I think). But what I want to do after is that once I backspace and clear it, I want to add another task and description, but I also want to add that AFTER the saved input.
ie:
task: do laundry, study
Description, do a buttload of laundry, study a lot
Can someone check my code and see what's wrong? It's just showing the console.log input, which is nice, but I want to be able to use the push method to add to the end of my arrays and SAVE it.
function submitForm() {
var FormData = {
task: myForm.task.value,
description: myForm.description.value
};
myJSON = JSON.stringify(FormData);
localStorage.setItem("formJSON", myJSON);
text = localStorage.getItem("formJSON");
obj = JSON.parse(text);
console.log(FormData);
return false;
};
newArray = [task, description];
var taskArray = [];
var descriptionArray = [];
var task = document.getElementById("task").value;
var description = document.getElementById("description").value;
function addTask(task) {
taskArray.push(task);
console.log(" " + taskArray.join(", "));
}
function addTask(task) {
taskArray.push(task);
console.log(" " + taskArray.join(", "));
}
function addDescription(description) {
descriptionArray.push(task);
console.log(" " + descriptionArray.join(", "));
}
<!DOCTYPE html>
<html>
<title>Task Form</title>
<body>
<form class="form-inline" name="myForm" onsubmit=" return submitForm()">
<label class="required">*Task and Description* </label>
<!first text box>
<div class="form-group">
<input type="text" id="task" placeholder="Task">
</div>
<!second comment box>
<div class="form-group">
<input type="text" id="description" placeholder="Description">
</div>
<button type="submit" class="btn btn-default submit">Submit</button>
</form>
<script type="text/javascript " src="json.js "></script>
</div>
</p>
</form>
</body>
</html>
All tasks and description has to be in array form and packaged in JSON.
You just need to call your addTask and addDescription functions when the form submits. JSFiddle: http://jsfiddle.net/wcrg804z/
Some errors with your code:
You have two addTask functions when you only need one.
Your addDescription function is trying to push task (which is undefined) to descriptionArray.
There are extra closing </div> </p> </form> tags after your form which are unnecessary.
<!DOCTYPE html>
<html>
<title>Task Form</title>
<body>
<form class="form-inline" name="myForm" onsubmit="return submitForm()">
<label class="required">*Task and Description* </label>
<!--first text box-->
<div class="form-group">
<input type="text" id="task" placeholder="Task">
</div>
<!--second comment box-->
<div class="form-group">
<input type="text" id="description" placeholder="Description">
</div>
<button type="submit" class="btn btn-default submit">Submit</button>
</form>
<script>
function submitForm() {
var task = myForm.task.value;
var desc = myForm.description.value;
var FormData = {
task: task,
description: desc
};
//myJSON = JSON.stringify(FormData);
//localStorage.setItem("formJSON", myJSON);
//text = localStorage.getItem("formJSON");
//obj = JSON.parse(text);
addTask(task);
addDescription(desc);
console.log(FormData);
return false;
};
newArray = [task, description];
var taskArray = [];
var descriptionArray = [];
var task = document.getElementById("task").value;
var description = document.getElementById("description").value;
function addTask(task) {
taskArray.push(task);
console.log(" " + taskArray.join(", "));
}
function addDescription(description) {
descriptionArray.push(description);
console.log(" " + descriptionArray.join(", "));
}
</script>
</body>
</html>

Javascript: Writing HTML dynamically via innerHTML

Im not sure why I cannot dynamically write to the paragraph element. I've even tried with just a string to no avail. What am I doing wrong here? Im guessing the default behavior is to POST because that's all that happens, even though I'm not telling it to do it.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
<!--
function submit() {
var fName = "";
var lName = "";
var eLevel = "";
fName = document.person.elements["fName"].value;
lName = document.person.elements["lName"].value;
eLevel = document.person.elements["eLevel"].value;
var result = fName + " " + lName + "<br>" + eLevel;
document.getElementById("result").innerHTML = result;
};
//-->
</script>
</head>
<body>
<form action="" id="person">
Please fill in all fields.<br /><br />
<fieldset><legend>Name:</legend>
First: <input type="text" id="fName" name="fName" /><br /><br />
Last:
<input type="text" id="lName" name="lName" />
</fieldset>
<br />
<fieldset>
<legend>Education:</legend>
Highest Level:
<input list="eLevels" name="eLevel" />
<datalist id="eLevels">
<option value="High School">
<option value="Associate Degree">
<option value="Bachelors Degree">
<option value="Graduate Degree">
</datalist>
</fieldset>
<br /><button value="click" onclick="submit()">click</button>
</form>
<p id="result"></p>
</body>
</html>
You need to preventDefault on the form submit, this way your code can execute.
function submit(event) {
event.preventDefault();
var fName = "";
var lName = "";
var eLevel = "";
fName = document.person.elements["fName"].value;
lName = document.person.elements["lName"].value;
eLevel = document.person.elements["eLevel"].value;
var result = fName + " " + lName + "<br>" + eLevel;
document.getElementById("result").innerHTML = result;
};
For the event parameter you will need to pass it in the onClick() event
<button value="click" onclick="submit(event)">click</button>

Why my text is printed on page and soon disappears in js

this is my code
i was trying to make a signup form and i made a script
i jst tried that the username should contain both alphabets and numbers and nothing else
if this condition is true than it continues
else it will give an error message displayed jst below it
<html>
<head>
</head>
<body>
<style>
#sign_up_details {
padding: 10px;
}
</style>
<form name="sign_up_details">
<h3>Enter your details below</h3>
<input type="textbox" id="username" placeholder="Enter your desired username" />
<p id="usrnm_check"></p><br>
<input type="password" id="password" placeholder="Enter your desired password" />
<p id="pass_check"></p><br>
<input type="textbox" id="email" placeholder="Enter your email id" />
<p id="email_check"></p><br>
<input type="submit" name="submit" value="Submit" onclick="store()" />
</form>
<script>
var usrnm = document.getElementById("username");
var pass = document.getElementById("password");
var email = document.getElementById("email");
var usrnm_check = document.getElementById("usrnm_check");
var pass_check = document.getElementById("pass_check");
var email_check = document.getElementById("email_check");
function store() {
var newReg = /^[A-Z]+[a-z]+[0-9]+$/
if (usrnm.value.match(newReg)) {
//next action here
} else {
usrnm_check.innerHTML = "Username should have alphabets and numbers";
}
}
</script>
</body>
</html>
for eg when i keep the username field empty and click on submit the error which is to be displayed comes below it but it soon disappears.
i dont know the reason for it.
you will have to set the store in onsubmit event and not on the submit button onclick event because,onclick will execute the function and submit the form as well.
here is fiddle
execute function before submit
<html>
<head>
</head>
<body>
<style>
#sign_up_details {
padding: 10px;
}
</style>
<form name="sign_up_details" onsubmit="return store()">
<h3>Enter your details below</h3>
<input type="textbox" id="username" placeholder="Enter your desired username" />
<p id="usrnm_check"></p><br>
<input type="password" id="password" placeholder="Enter your desired password" />
<p id="pass_check"></p><br>
<input type="textbox" id="email" placeholder="Enter your email id" />
<p id="email_check"></p><br>
<input type="submit" name="submit" value="Submit" />
</form>
<script>
var usrnm = document.getElementById("username");
var pass = document.getElementById("password");
var email = document.getElementById("email");
var usrnm_check = document.getElementById("usrnm_check");
var pass_check = document.getElementById("pass_check");
var email_check = document.getElementById("email_check");
function store() {
var newReg = /^[A-Z]+[a-z]+[0-9]+$/
if (usrnm.value.match(newReg)) {
//next action here
return true;
} else {
usrnm_check.innerHTML = "Username should have alphabets and numbers";
return false;
}
}
</script>
</body>
</html>
You can try something like this:
<form action="/dosomething.htm" method="GET" onsubmit="return store(this)">
[...]
<input type="submit" value="Go">
</form>
<script type="text/javascript">
function store() {
var newReg = /^[A-Z]+[a-z]+[0-9]+$/
if (usrnm.value.match(newReg)) {
//next action here
return true;
} else {
usrnm_check.innerHTML = "Username should have alphabets and numbers";
return false;
}
}
</script>
Notice return true and return false statements in store() and in form onSubmit. If the store() will return false the form will not get submitted. At present your message goes away after display because your form gets submitted even if the validation fails.
Hope this helps!!

Keep user logged in between browser sessions

Here is the sample code for my project. It contains two forms on a single page.
The first form contains username and a textbox, when I enter the username and click the login button the user's name should be displayed and the logout form should be displayed.
How do I ensure that the user will remain logged in once the browser window is closed?
Code
<!DOCTYPE html>
<html>
<title>Login Page</title>
<head>
<script>
function set(x)
{
document.getElementById(x).value="";
}
</script>
<script>
function showDiv(e)
{
var divs = document.getElementsByTagName('div');
if (e==1)
{
for(i=0;i<divs.length;i++)
{
if (divs[i].id=="hidevar1")divs[i].style.visibility="visible";
else if (divs[i].id=="hidevar2")divs[i].style.visibility="hidden";
}
}
else {
for(i=0;i<divs.length;i++)
{
if (divs[i].id=="hidevar1")divs[i].style.visibility="hidden";
else if (divs[i].id=="hidevar2") {
divs[i].style.visibility="visible";
}
}
}
}
function put()
{
var x = document.getElementById("fname").value;
currentTime=new Date();
if(currentTime.getHours()<12)
var y = "Good Morning ";
else if(currentTime.getHours()<17)
var y = "Good Afternoon ";
else
var y = "Good Evening ";
document.getElementById("devin").innerHTML = "Hello " + x + " " + y;
}
</script>
<script>
</script>
<script>
function search()
{
var dic = document.getElementById("url").value;
var str="http://www.google.co.in/#hl=en&q=";
var www=str+dic;
window.open(www);
}
</script>
</head>
<body>
<div id="devin">
</div>
<div id="hidevar1" style="visibility: visible;">
<form name="frm1" method="post" >//Login form
User Name : <input type="text" id="fname" value="Enter name here" onfocus="set(this.id)" >
</form>
<input type="button" value="Login" onClick="showDiv(2);put();">
</div>
<div id="hidevar2" style="visibility: hidden;">
<form name="frm2">//logout form
<script>
</script><br/>
<input type="submit" value="logout">
<br>
<br>
</form>
</div>
<br><br>
<input type="text" name="url1" id="url" />
<input type="submit" value="google"onclick="search();" />
</body>
</html>
If you plan to use spring, spring-security provides remember me services which would let you be logged in across browsers or sessions.
Other option is to use Apache shiro if you find spring-security too complex for your application.

Categories