how to add user data javascript - javascript

I am having trouble being able to add user input data. I can get it working when I add in the data myself all the users show up in the console in the array. For people 1-3 I would like them to enter their name and favorite color but I can't seem to be able to store it or at least have it come up in the console. I did remove person 2 and 3 from the array so I can test it easier and quicker. if you were to take the
user: document.getElementById('name').value,
color: document.getElementById('color').value,
and all the comments it would work and show up in console how i want it to but cant seem to do user data. Sorry if this is confusing i am a new to javascript.
<!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>
</head>
<body>
<form>
<div class="formBox">
<label for="name">Name</label>
<input type="text" id="name" placeholder="Name"/>
</div>
<div class="formBox">
<label for="color">Favorite color</label>
<input type="text" id="color" placeholder="Color"/>
</div>
<div class="formBox">
<button id="btn">Click to Add</button>
</div>
<div id="msg">
<pre></pre>
</div>
</form>
<script >
const person1 = {
user: document.getElementById('name').value,
color: document.getElementById('color').value,
/* user: "Sarah",
color: "Yellow",*/
};
/* const person2 = {
user: "Aaron",
color: "Yellow"
};
const person3 = {
user: "Sarah",
color: "Green",
};
*/
array = [person1]
sort = array.sort(function(a, b){
if(a.user < b.user) { return -1; }
if(a.user > b.user) { return 1; }
return 0;
})
console.log(sort)
</script>
</body>
</html>

I give you a code matches with your purpose but I recommend you found a course that builds a complete project, that can helps you to understands how to use basics to build some complex things.
// Declare Part
const users = [];
const form = document.getElementById("myForm");
// 1. Add Event Listener to our form
// when form submits the function get called
form.addEventListener("submit", (event) => {
// Stop form from refreshing the page
event.preventDefault();
// Get name field value
const userName = document.getElementById("name").value;
// Get color field value
const userColor = document.getElementById("color").value;
// Create new person
const person = {
user: userName,
color: userColor,
};
// Store new person (Add new person to array of users)
users.push(person);
// Now we sort our users
users.sort(function(a, b) {
if (a.user < b.user) {
return -1;
}
if (a.user > b.user) {
return 1;
}
return 0;
});
// See the result
console.log(users);
});
<form id="myForm">
<div class="formBox">
<label for="name">Name</label>
<input type="text" id="name" placeholder="Name" />
</div>
<div class="formBox">
<label for="color">Favorite color</label>
<input type="text" id="color" placeholder="Color" />
</div>
<div class="formBox">
<button id="btn">Click to Add</button>
</div>
<div id="msg">
<pre></pre>
</div>
</form>

The javascript in your code is running start to finish every time you refresh the page and when you're clicking the click to add button, you're submitting the form, which automatically refreshes the page. You can make a couple of tweaks in your code to fix this...
You can add type="button" as a property of your button to tell the browser that this is a button and not a way of submitting your form. By doing this your page wont refresh when you click it.
You want your javascript code to run when you click the button, not when the page loads. To do this you need to wrap it in a function and add an onclick handler to your button that executes the function when the button is clicked. You'll notice the array is initialised outside the function, this is because we do want the array to be initialised when you load the page, and not when the button is clicked, otherwise we would be overwriting the array every time we added something to it.
const array = []
const addUser = () => {
const person1 = {
user: document.getElementById('name').value,
color: document.getElementById('color').value,
};
array.push(person1)
sort = array.sort(function(a, b){
if(a.user < b.user) { return -1; }
if(a.user > b.user) { return 1; }
return 0;
})
console.log(sort)
}
<form>
<div class="formBox">
<label for="name">Name</label>
<input type="text" id="name" placeholder="Name"/>
</div>
<div class="formBox">
<label for="color">Favorite color</label>
<input type="text" id="color" placeholder="Color"/>
</div>
<div class="formBox">
<button
id="btn"
type="button"
onclick="addUser(this)"
>Click to Add</button>
</div>
<div id="msg">
<pre></pre>
</div>
</form>

Related

Validate javascript and html form

I'm doing an exercise but I can't validate and send a form.
I have this HTML code, to which I cannot add or modify anything:
</head>
<body>
<h1>Card game</h1>
<p>
<label>Displays the name of the participant</label
><input type="text" name="name" />
</p>
<p>
<label>how many games do you want to play? </ tag
><input type="number" name="games" value="0" />
</p>
<button>PARTICIPATE!</button>
<script type="text/javascript" src="rockPaperScissors.js"></script>
</body>
I am trying to validate the form, which should turn the fields red when I hit the participate button and does not meet the validation conditions. Once the data has been corrected and the form has been validated, the fields must be deactivated so that they cannot be written again and remain visual.
I have done this but I don't get my goal:
function validateName() {
const name = document.getElementsByName("name");
const expression1 = /[A-Za-z]{3,}/;
name.click();
if (!expression1.test(name.value)) {
name.classList.add("RedBackground");
false return;
}
return true;
}
function validateGames() {
games.click();
const items = document.getElementsByName("items");
if (games.value <= 0) {
games.classList.add("RedBackground");
false return;
}
return true;
}
// Indicate who launches the events
document
.getElementsByTagName("button")[0]
.addEventListener("click", validateName);
document
.getElementsByTagName("button")[0]
.addEventListener("click", validateGames);
Issue
<input type="text" name="name" />
const name = document.getElementsByName("name");
getElementsByName returns a collection and not a single element.
Possible solution
To get the first element whose name attribute equals name, you have to either get the first index of the collection:
const name = document.getElementsByName("name")[0];
or querySelector which returns the first matching element.
const name = document.querySelector("[name=name]");
Example
document.querySelector("button").addEventListener("click", function(){
//REM: Is everything valid?
let tValid = true;
//REM: Validate "name" using "querySelector"
let tName = document.querySelector("[name=name]");
if(tName){
//REM: Put your logic here
tName.classList.add("RedBackground");
tValid = false
};
//REM: Validate "games" using "getElementsByName"
let tGames = document.getElementsByName("games")[0];
if(tGames){
//REM: Put your logic here
tGames.classList.add("BlueBackground");
tValid = false
};
return tValid
});
.RedBackground{
background-color: crimson
}
.BlueBackground{
background-color: cornflowerblue
}
<h1>Card game</h1>
<p>
<label>Displays the name of the participant</label>
<input type="text" name="name" />
</p>
<p>
<label>how many games do you want to play? </ tag>
<input type="number" name="games" value="0" />
</p>
<button>PARTICIPATE!</button>
I recommend, even if possible, not to reuse the keyword name as variable name.

Reset (reset to previous value) only the form fields that are changed

I need to reset only the form fields that are changed (reset to previous value).
I tried to use the reset but it completely resets the entire form and I don't need this.
How can I do this?
function clearResult() {
document.getElementById("save").reset();
}
<div class = "container">
<form method="post" id="save" onload="onLoad()">
<div class="field">
<label for="id"> ID:</label>
<input type="number" id="id" name="id" />
</div>
<div class="field">
<label for="type"> Fragment Type: </label>
<input type="text" id="type" name="type" />
</div>
<div class="button">
<button type="submit" class="full">Save changes</button>
<input type="button" value="Cancel" onclick="clearResult()" />
</div>
</form>
</div>
First of all you should to store the predefined values of form elements to set them back when you want to reset them back.
Then you can use this globally defined initial values to set them back whnever reset event occurs.
var id, type;
const form = document.getElementById('save');
document.onload = (event) => {
id = form.id.value;
type = form.type.value;
};
function clearResult() {
form.id.value = id;
form.type.value = type;
};
It was simple. When page load just get values from that fields.
Make with document.onload:
var firstValue = document.getElementById("yourFieldId").value;
After form submit get values like below:
var currentValue = document.getElementById("yourFieldId").value;
And after submit in reset check if CURRENT VALUES equal with VALUES FROM FIRST TIME
Example
if(firstValue != currentValue){
document.getElementById("yourFieldId").value = firstValue;
}

The inputs are not showing up at all when I click on the button. If I remove the form an html then it works but I want it to work in form

I know this may be a dumb question to some but I am pretty new to this and trying to learn. I have been stuck on this for days and couldn't figure it out so I came here for help. Whenever I hit the button it doesn't display my input at all. I want to make it that when the user clicks the button their input will show up in an ol list.
let form = document.getElementById("todo");
let list = document.getElementById("myList");
let input = document.getElementById("add1");
let input2 = document.getElementById("add2");
let button = document.getElementById("button");
let id = 1;
button.addEventListener("click", addToDo)
list.addEventListener("click", removeEvent)
function addToDo (e) {
let text = input.value;
let textAdd = input2.value;
let item = `<li class="del">
${text} ============= ${textAdd} <button class="del">Delete</button>`
list.insertAdjacentHTML("beforeend",item);
id++;
document.getElementById("add1").value = "";
document.getElementById("add2").value = "";
}
function removeEvent(e) {
if(e.target.classList.contains("del")) {
list.removeChild(e.target.parentElement);
list.removeChild(list);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<h1 id="name">Todo List</h1>
<link href="project.css" rel="stylesheet"/>
</head>
<body>
<div id="todo">
<h1>Name</h1>
<input type="text" id="add1" placeholder="Title">
<br>
<h1>Add Reminder</h1>
<input type="text" id="add2" placeholder="Notes">
<button id="button">Submit</button>
</div>
<ol id="myList">
</ol>
<script src="pro.js"></script>
</body>
</html>
There is something "special" about buttons within a form.
If your HTML looks like:
<form>
<input placeholder="enter some text">
<button>Click me</button>
</form>
Your button will submit the form and therefore reset it.
I guess you would expect the form to have some crucial properties to do so, namely 'action' and 'method' (to send the data in your inputs to some remote address - because that's the main concern of forms).
If you want your button to just be a button, use the following:
<form>
<input placeholder="enter some text">
<button type="button">Click me</button>
</form>
And you'll see: nothing happens.
I've created a StackBlitz here for you (just look at the HTML file). With type="button", more and more inputs are added to the form. If you omit this, you can see the input is added, and immediately after it, the form resets itself (sending a GET request to '/' and refreshing everything - but that's something for another question).

combining data elements from two html forms is not working properly

I am trying to combine data from two HTML forms and then post it as a single form which is working fine except that some elements are not being copied from one form to the other. I have defined the following javascript function to combine form elements:
var form = document.forms['auth_form'];
var issuedata = window.opener.document.getElementById('Create').elements;
for (var i = 0; i < issuedata.length; i++) {
var data = issuedata[i];
alert(data.innerHTML);
if(data.type !== "submit")
form.appendChild(data);
}
Actual files
This is the first form:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
var childWindow = null;
function child_open() {
childWindow = window.open('new.html', "_blank",
"resizable=no,width=600, height=280,top=200,left=200");
}
function parent_disable() {
if (childWindow && !childWindow.closed)
childWindow.focus();
}
</script>
</head>
<body onclick="parent_disable();">
<input type="button" value="Create Jira Ticket" onclick="child_open()" />
<form name="auth_form" id="Create" method="post">
<input name="bug_status" value="NEW" type="hidden">
<input name="rep_platform" value="All" type="hidden">
<input name="component" value="AFAS" type="hidden">
<input name="bug_severity" value="Beeper Call" type="hidden"/>
<input type="hidden" name="comment" value="hello hi"><br>
</form>
</body>
</html>
and this is second form:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
var count = 0;
function submit_and_close() {
var form = document.forms['auth_form'];
var issuedata = window.opener.document.getElementById('Create').elements;
for (var i = 0; i < issuedata.length; i++) {
var data = issuedata[i];
alert(data.innerHTML);
if(data.type !== "submit")
form.appendChild(data);
}
alert(form.innerHTML);
form.submit();
// close the window after form submission is complete.
var docLoaded = setInterval(function() {
if (document.readyState !== "complete") {
return;
}
clearInterval(docLoaded);
//window.close();
}, 30);
}
</script>
</head>
<body>
<header>
<div id="dialog" title="JIRA Dialog">
<h1>JIRA Credentials</h1>
</div>
</header>
<div>
<form name="auth_form" id="auth_form" method="post">
<label> User Name: </label> <input type="text" name="username"><br>
<label> Password: </label> <input type="password" name="password"><br>
<input type="button" value="Log In" onclick="submit_and_close()">
</form>
</div>
</body>
</html>
For example I am not able to see the following elements being copied over from 'Create' form to 'auth_form' in second html page.
<input name="rep_platform" value="All" type="hidden">
<input name="bug_severity" value="Beeper Call" type="hidden"/>
Even after spending sometime debugging, I am not able to figure out why some elements are being succesfully copied while others not.
.elements returns a live collection of elements. When you append an element from the collection, it gets removed from the collection, so your index i into the collection get out of sync, and therefore every other element gets skipped.
Instead, just append the first element from the collection until the collection is empty. (Just detach the submit button element when it is encountered). Alternatively, loop through the collection from last to first rather than first to last.
(querySelectorAll() works because it returns a static collection, rather than a live one.)
Try changing your second form from ...
var issuedata = window.opener.document.getElementById('Create').elements;
to
var issuedata = window.opener.document.querySelectorAll('input[name]');
... and replace all innerHTML with outerHTML

Checkbox will not stay checked and submit listener does not work

I am dynamically rendering pages using Handlebars.js, and I have a "quiz-form template" with the following code:
<div id="right-pane">
<script type="text/x-handlebars-template" id="quiz-form-template">
<form class="cf" id="quiz-form">
<h2>Create a <span>quiz</span></h2>
<p>Enter a quiz name and description to get started.</p>
<div>
<input type="text" name="quiz-name" placeholder="Quiz Name" />
</div>
<div>
<textarea rows="5" cols="40" name="quiz-description"
placeholder="Description"></textarea>
</div>
<div id="checkbox">
<input type="checkbox" name="is_random" /> Create randomly generated quiz <br/>
<input type="checkbox" name="is_single_page" /> Render quiz on a single page <br/>
<input type="checkbox" name="is_immediate"/> Give immediate feedback <br/>
</div>
<input type="submit" class="btn" value="Add Questions" />
</form>
</script>
</div>
I am running into two problems that I have been trying to debug to no avail. After rendering this page on my html, when I click the checkboxes, they do not get checked at all. It seems like I click and it "almost bounces off".
Additionally when I click the submit button, it is not being listened to. I am console.log"ging" to check and their is not output. Here is my event listener:
rightPane.addEventListener("submit", function(event) {
console.log( event.target );
event.preventDefault;
if ( event.target.value === "Add Questions" ) {
//DOM elements
newQuizName = document.querySelector('#quiz-form input');
newDescription = document.querySelector('#quiz-form textarea');
randomStatus = document.querySelector('#quiz-form input[name="is_random"]');
singlePageStatus = document.querySelector('#quiz-form input[name="is_single_page"]');
immediateStatus = document.querySelector('#quiz-form input[name="is_immediate"]');
var pendingQuiz = getPendingQuiz();
pendingQuizMetaData = {name: newQuizName.value, description: newDescription.value,
random: randomStatus.checked, singlePage: singlePageStatus.checked,
immediate: immediateStatus.checked
pendingQuiz = { metadata: pendingQuizMetaData, questions: [] };
updatePendingQuiz( pendingQuiz );
rightPane.innerHTML = templates.renderQuestionType();
newQuestion = "";
newSubject = "";
// }
// Since add questions is clicked, we should send the user to select question type
// we'll need to render html on the right pane
}
});
Any input would be greatly appreciated.

Categories

Resources