I am trying to create a fill button that will fill the input values with the a default. When I go to click the fill button the defaults shows up for 2 seconds and then disappears. How do I get the information to stay without it clearing itself.
var enter, replace, FirstName, Telephone, email, BithDate, LastName, ZipCode, SS, Cash;
window.onload = function() {
//calls the functions when buttons clicked
replace = document.getElementById("fill");
replace.addEventListener("click", filler);
enter = document.getElementById("enter");
enter.addEventListener("click", calculate);
var clear = document.getElementById("clear");
clear.addEventListener("click", clear);
}
function filler() {
//list the default values to fill when the fill button is clicked
FirstName = document.getElementById("FirstName").value = "Jane";
Telephone = document.getElementById("tel").value = "888-777-9999";
email = document.getElementById("email").value = "JaneDoe#example.com";
BithDate = document.getElementById("birth").value = "2017";
LastName = document.getElementById("LastName").value = "Doe";
ZipCode = document.getElementById("zip").value = "12345";
SS = document.getElementById("SocSec").value = "123-45-6789";
Cash = document.getElementById("income").value = "123456";
}
function clear() {
//clears the form and resets it to the default
document.getElementById("form").reset();
}
You named your local variable for the clear button "clear" which shadows the global clear function, so clear.addEventListener("click", clear); doesn't work. Try renaming the local variable to something like clearBtn.
Related
I have a group of dynamically generated input fields. I want to loop through all of them and check if the user has indeed written something on them. If all fields have been filled, activate the button, otherwise, desactivate it. Code is really long, so here is the most important part :
//Here is the loop that creates the number of inputs to create based on what the user enters:
(CourseObject.course_array).forEach((evaluation,value) => {
const percentage_value = CourseObject.each_evaluation_value[value];
//Some lists
const li_inputs = document.createElement('li');
li_inputs.id = ((`${evaluation}-of-${CourseName}-input-li`.replace(/°/g, "")).replace(/ /g, "")).toLocaleLowerCase();
li_inputs.className = "list-group-item";
(document.getElementById(`${CourseName}-input-ul`).appendChild(li_inputs));
//Here starts the important stuff, creation of the inputs and attributes
const text_input = document.createElement('input');
text_input.type = 'text';
text_input.placeholder = `Nota de ${evaluation} (${percentage_value}%)`;
text_input.id = ((`${evaluation}-of-${CourseName}-input-text`.replace(/°/g, "")).replace(/ /g, "")).toLocaleLowerCase();
text_input.className = 'form-control grade-input';
(document.getElementById(((`${evaluation}-of-${CourseName}-input-li`.replace(/°/g, "")).replace(/ /g, "")).toLocaleLowerCase())).appendChild(text_input);
}
);
//Creating the button
const SendAndShow = document.createElement('button');
SendAndShow.textContent = 'Calcular';
SendAndShow.id = 'send-and-show-button';
SendAndShow.disabled = true; //Desactivated from the beggining
SendAndShow.className = 'btn btn-dark';
document.getElementById('second-column').appendChild(SendAndShow);
//Here I want to loop through the inputs. If they are all filled, SendAndShow.disabled = false
//A random event set to be activated once the button is clicked
document.getElementById('send-and-show-button').onclick = function() {
.
. //Something to do
.
}
I have tried querySelectorAll and getting the element by class but I can't seem to be able to hack it, any suggestions?
Note : I would like a pure JS answer, no JQuery.
You can use the onchange method in every input element, then check the values of inputs with FormData
const form = document.querySelector('#form')
function getFormData() {
formData = new FormData(form)
console.log(formData.entries())
}
text_input.onchange = function(){
getFormData()
}
<form id='form'></form>
for dynamic element add listener to the parent or body then check your input elements
createInput.addEventListener('click', function() {
let input = document.createElement('input')
myform.prepend(input)
submit.setAttribute('disabled', '')
})
// the parent
myform.addEventListener('input', function(el) {
if (el.target.tagName != 'INPUT') return;
// chack all input
let allFilled = true
document.querySelectorAll('#myform input').forEach(function(input) {
if (!input.value)
allFilled = false;
})
// set the button state
if (allFilled)
submit.removeAttribute('disabled')
else
submit.setAttribute('disabled', '')
})
input{display:block;margin:10px;}
<button id="createInput">Create input</button><br><br>
<form id="myform">
<button id="submit" disabled>Submit</button>
</form>
I have been working on a small contact form for a webpage and I used some code from a website to create the form. My problem is that the submit button wants to post the data and all is the submit button to create a message alert, and also redirect to another page after the message appears..
Any help would be greatly appreciated! Thanks!
here is the JS:
// Fetching HTML Elements in Variables by ID.
var x = document.getElementById("form_sample");
var createform = document.createElement('form'); // Create New Element Form
createform.setAttribute("action", ""); // Setting Action Attribute on Form
//createform.setAttribute("method", "post"); // Setting Method Attribute on Form
x.appendChild(createform);
var heading = document.createElement('h2'); // Heading of Form
heading.innerHTML = "Contact Form ";
createform.appendChild(heading);
var line = document.createElement('hr'); // Giving Horizontal Row After Heading
createform.appendChild(line);
var linebreak = document.createElement('br');
createform.appendChild(linebreak);
var namelabel = document.createElement('label'); // Create Label for Name Field
namelabel.innerHTML = "Your Name : "; // Set Field Labels
createform.appendChild(namelabel);
var inputelement = document.createElement('input'); // Create Input Field for Name
inputelement.setAttribute("type", "text");
inputelement.setAttribute("name", "dname");
createform.appendChild(inputelement);
var linebreak = document.createElement('br');
createform.appendChild(linebreak);
var emaillabel = document.createElement('label'); // Create Label for E-mail Field
emaillabel.innerHTML = "Your Email : ";
createform.appendChild(emaillabel);
var emailelement = document.createElement('input'); // Create Input Field for E-mail
emailelement.setAttribute("type", "text");
emailelement.setAttribute("name", "demail");
createform.appendChild(emailelement);
var emailbreak = document.createElement('br');
createform.appendChild(emailbreak);
var messagelabel = document.createElement('label'); // Append Textarea
messagelabel.innerHTML = "Your Message : ";
createform.appendChild(messagelabel);
var texareaelement = document.createElement('textarea');
texareaelement.setAttribute("name", "dmessage");
createform.appendChild(texareaelement);
var messagebreak = document.createElement('br');
createform.appendChild(messagebreak);
var submitelement = document.createElement('input'); // Append Submit Button
submitelement.setAttribute("type", "submit");
submitelement.setAttribute("name", "dsubmit");
submitelement.setAttribute("value", "Submit");
createform.appendChild(submitelement);
If I'm understanding your question correctly, you want the page to verify before submitting, correct?
If so, you can add a listener which optionally cancels the submit action.
createform.addEventListener("submit", function() {
return confirm("Continue?");
});
You can add an event listener for submit event on submit button. Prevent it's default behavior, show an alert and then redirect to whatever page you want
createform.addEventListener("submit", function(e) {
e.preventDefault();
var msg = window.confirm("Want to go to other page?");
if (msg) {
window.location.href = "url";
}
})
Please i have a problem here in my work i have an input field and have a button that i use to create new input field with onclick event, but my problem is how to multiply numbers in both input fields and alert the answer.
function create(){
var main_input = document.getElementById("main_input").value,
newinput = document.createElement('input');
newinput.placeholder = "test1";
newinput.value;
document.getElementById("mytest").appendChild(newinput);
}
function multiply(){
var ans = newinput * main_input;
alert(ans);
}
In the absence of clarity, I am posting this solution. Looks like you are not clear on few concepts so let me try to explain them:
You need to move your variables outside the scope of create() so that they are available in the multiply() function.
You cannot just multiply two input fields. You need to take the values from them as shown in the code below.
Hopefully it helps you in moving ahead!
var main_input,newinput;
function create(){
main_input = document.getElementById("main_input");
newinput = document.createElement('INPUT');
newinput.placeholder = "test1";
newinput.value = 10;
document.getElementById("mytest").appendChild(newinput);
}
function multiply(){
var ans = newinput.value * main_input.value;
alert(ans);
}
create();
multiply();
<input id="main_input" value=10 />
<div id="mytest"></div>
Use eval() or you can manually multiply the values like input1.value * input2.value
function create(){
// this is unnecessary, you are creating a new element
// var main_input = document.getElementById("main-input");
var newinput = document.createElement('input');
newinput.placeholder = "test1";
newinput.id = 'test1'; // give the element an id, to access it later by id
// newinput.value; // this too is unnecessary, you'll get the value from the user
if (!document.getElementById('test1')) {
// append the child only if it doesn't exist
document.getElementById("mytest").appendChild(newinput);
}
}
function multiply(){
var newinput = document.getElementById('test1');
var mainInput = document.getElementById("main_input");
alert(eval(newinput.value + '*' + mainInput.value));
// alert(newinput.value * mainInput.value) you can also use this method
}
<div id="mytest">
<input type="text" id="main_input">
</div>
<button onclick="create()">Create</button>
<button onclick="multiply()">Multiply</button>
I am trying to dynamically add an object with values from an input field to the end of an array using JavaScript. The only catch is that I'm trying to do it with an input field. Here's what I want to happen:
The user types in something in a text field
My program already adds a unique ID for it
Add it to the end of an array in the form of a object
Keep on adding objects to that array
This is what I want in my JSON file:
{
"list": [{
"id": 0,
"description": "Task #1 Description"
}, {
"id": 1,
"description": "Task #2 Description"
}, {
"id": 3,
"description": "Task #3 Description"
}]
}
What I am currently getting is:
{
"list": [{
"id": 0,
"description": "Task #1 Description"
}, ]
}
Every time I add a new Task, it replaces the one that is already there.
Here is my JavaScript code:
// This is the counter
var indentification = 0;
// This is the submit button
var submit = document.getElementById("submit");
// This is the text field
var content = document.getElementById("text");
submit.onclick = function() {
id = indentification++;
description = content.value;
var task = {
list: []
}
task.list.push({id, description});
var jsonifyTask = JSON.stringify(task);
fs.writeFile("tasks.json", jsonifyTask, "utf8");
}
I would really appreciate it if anyone could help me out. I've spent hours trying to figure it out. Thanks!
The problem is here:
var task = {
list: []
}
task.list.push({id, description});
Each time you do this your list become empty then add new item.
change to this
// This is the counter
var indentification = 0;
// This is the submit button
var submit = document.getElementById("submit");
// This is the text field
var content = document.getElementById("text");
var task = {
list: []
}
submit.onclick = function() {
id = indentification++;
description = content.value;
task.list.push({id, description});
var jsonifyTask = JSON.stringify(task);
fs.writeFile("tasks.json", jsonifyTask, "utf8"); // what're you doing here, browser do not allow write file to disk
}
There are a couple of things that you need to consider here:
Form submit must be refreshing the page and resetting your global variables. Thus you need to prevent default action on click of submit.
(as mentioned in earlier answers) The list is being initiated on every click. You will need to initialize the variable task outside the onClick function
// This is the counter
var indentification = 0;
// This is the submit button
var submit = document.getElementById("submit");
// This is the text field
var content = document.getElementById("text");
//initialize outside the on click function
var task = {
list: []
}
submit.onclick = function(e) {
//This prevents page refresh on form submission and preserves the global variable states
e.preventDefault();
id = indentification++;
description = content.value;
task.list.push({id, description});
var jsonifyTask = JSON.stringify(task);
fs.writeFile("tasks.json", jsonifyTask, "utf8");
}
This should hopefully solve your problem.
// This is the counter
var indentification = 0;
// This is the submit button
var submit = document.getElementById("submit");
// This is the text field
var content = document.getElementById("text");
submit.addEventHandler("click", function() {
id = indentification++;
description = content.value;
task.list.push({id, description});
var jsonifyTask = JSON.stringify(task);
fs.writeFile("tasks.json", jsonifyTask, "utf8");
}
I am trying to create a form that when submitted will just output the two values to the console. However, when I run it, only the email field is being displayed and the name field is just showing 'undefined'.
I have created a JSFiddle of what I have so far.
https://jsfiddle.net/hbzxcvjj/1/
JS:
var name = document.getElementById("name");
var email = document.getElementById("email");
var submitButton = document.getElementById("btn-signup");
var sendInfo = function(){
console.log(name.value);
console.log(email.value);
}
submitButton.onclick = sendInfo;
try moving your variable definitions into the function, this is how it should look:
var submitButton = document.getElementById("btn-signup");
var sendInfo = function(){
var name = document.getElementById("name");
var email = document.getElementById("email");
console.log(name.value);
console.log(email.value);
}
submitButton.onclick = sendInfo;
https://jsfiddle.net/hbzxcvjj/2/
see the working fiddle
Try with alternate method:
submitButton.addEventListener("click", sendInfo);