How to Display User Input (composed of a few submissions) in JavaScript? - javascript

I can't figure out what exactly am I doing wrong, I only get errors.
index.html
<div id="user-pets">
</div>
<form id="user-pets-form">
<input type="text">
<input type="submit">
</form>
index.js
document.querySelector("#user-pets")
const createPetForm = document.querySelector("#user-pets-form")
createPetForm.addEventListener("submit", (e) => {
e.preventDefault()
let pet = e.target.input.value
document.querySelector("#user-pets").innerHTML += pet
}

After Reviewing your code, you have made two mistakes let me explain,
In JavaScript Code you forgot to add small bracket on second last line,
that's why its through error
In Html you need to add name attribute to Input field, otherwise the listener of submit will always return undefined
I modified both code for you, please have look below
HTML
<div id="user-comments">
</div>
<form id="user-comments-form">
<input type="text" name="comments">
<input type="submit">
</form>
JavaScript
document.addEventListener('DOMContentLoaded', () => {
console.log("DOM is loaded")
document.querySelector("#user-comments")
const createCommentForm = document.querySelector("#user-comments-form")
createCommentForm.addEventListener("submit", (e) => {
e.preventDefault()
let comment = e.target.comments.value;
document.querySelector("#user-comments").innerHTML += comment;
})
})

I suggest you would change the second input to <button type="submit">Submit</button> and add the event listener to it (not the form). Then you can select the value of the input tag, insert it to the comment div when user clicks the submit button

Related

Conditionally required form field (Checkbox)

I already checked multiple sites and posts regarding this topic, but couldn't find an answer yet. I simply want to fire the following JS code if someone clicked a specific Checkbox in my form:
function updateRequirements() {
var escortWrapper = document.querySelector(".elementor-field-type-html .elementor-field-group .elementor-column .elementor-field-group-field_ceffa28 .elementor-col-100");
if (escortWrapper.style.display != 'none') {
document.getElementById('escort').required = true;
} else {
document.getElementById('escort').required = false;
}
}
You can check and test that for yourself on the following site:
Advelio Website
If you click on the second checkbox field, there is a field appearing where you can type in your name. And this field is currently optional, but I want to make this required if someone clicked the second checkbox.
You can do it like this:
function updateRequirements() {
const btn = document.getElementById('escort');
btn.required = !btn.required;
}
document.querySelector("#requireCheck").addEventListener('click', updateRequirements);
<form>
<input type="checkbox" id="requireCheck">
<label for="requireCheck">Should the the other input be required?</label>
<br>
<input type="text" id="escort">
<input type="submit" value="submit">
</form>
I simplified the function updateRequirements for the scope of this answer, but it can be changed to anything or any condition.
You have to have event listener for click event and if you dont have create one and wrote the function with logic what to do if is click

Display error style with javascript using html 5 validations

I have a form with HTML validations and I am using JS to add or remove error style.
<form action="" id="addForm">
<div>
<label for="name">Name</label>
<input type="text" id="name" name="name" required minlength="3" />
</div>
<button type="submit">Add</button>
</form>
window.onload = handleLoad;
function handleLoad() {
const form = document.forms.addForm;
const name = form.name;
name.onkeyup = function () {
if (name.checkValidity()) {
name.classList.remove("error");
} else {
name.classList.add("error");
}
};
}
In this case the error class gets applied as the user is typing in the field. Is there a way to prevent this?
You are using the onkeyup event, which means the event is triggered every time the user releases a key.
If you want to check the input field only when the user moves to the next field, you could use the onfocusout event.
name.onkeyup = function () {
if (name.checkValidity()) {
name.classList.remove("error");
} else {
name.classList.add("error");
}
}
P.S., If you have a small form, you could also implement validation when the submit button is clicked.

How do I submit data from a text field in HTML to a JavaScript variable?

I cannot figure out how to pass an HTML input to a JS variable.
<form id="form" target="_self">
<input type="text" id="task" placeholder="What's on the agenda?" onsubmit="getForm()">
</form>
My HTML form with the function being called as follows:
function getForm() {
var form = document.getElementById("task").value;
console.log(form);
}
However, when I press enter after typing into the input text, it just refreshes the page and changes the URL from index.html to index.html?task=foo and doesn't log anything in the console.
Try this:
<form id="form" onsubmit="getForm()" target="_self">
<input id="task" placeholder="What's on the agenda?" type="text">
</form>
and
function getForm(event) {
event.preventDefault();
var form = document.getElementById("task").value;
console.log(form);
}
…but keep in mind that you need at least a button or an input to submit the form.
There are two issues with the OP's code.
The getForm function will not execute because onsubmit is wired up against the input element instead of the form element. HTMLInputElement doesn't emit submit events.
The default action of a form is to submit the form to the server, so even if the getForm function were correctly wired up it would execute quickly and then the page would refresh. Likely you want to prevent that default action.
Generally speaking, it's good practice to wire up event listeners in your JavaScript code. Here's a snippet that demonstrates working code akin to what the OP is attempting.
'use strict';
const taskFrm = document.getElementById('taskFrm');
const taskTxt = document.getElementById('taskTxt');
taskFrm.addEventListener('submit', e => {
e.preventDefault();
console.log(taskTxt.value);
});
<form id="taskFrm">
<input id="taskTxt" placeholder="What's on the agenda?">
</form>
For the sake of completeness, if you want to wire up the onsubmit function in the HTML, here's how:
function getForm(e) {
var form = document.getElementById("task").value;
console.log(form);
e.preventDefault(); // Or return false.
}
<form id="form" target="_self" onsubmit="getForm(event)">
<input type="text" id="task" placeholder="What's on the agenda?">
</form>

Form help(HTML/JS)

I'm (very) new to web development and am working on learning back-end currently.
I am trying to figure out how to use multiple inputs inside a form, but am struggling to get the actual input, instead of the element itself using this code to create the form:
<form id="newPostForm">
<input name="titleInput" placeholder="title"><br>
<input name="bodyInput" placeholder="body">
<button>Submit</button>
</form>
and this JS to try and output the user input to the console:
const newPost = document.getElementById("newPostForm")
const title = document.querySelector(".titleInput")
const body = document.querySelector(".bodyInput")
newPost.addEventListener("submit", (e) => {
e.preventDefault()
console.log(title, Body)
})
When I hit the submit button the console displays null null. This is probably a super simple question, but I'd appreciate any help.
After fixing the case issue with your body variable, you need to get the value of the inputs by accessing their value property. Then you want to move those variables into your submit handler, otherwise you're only getting the value once, when the page loads, and they're blank:
const newPost = document.getElementById("newPostForm");
newPost.addEventListener("submit", (e) => {
const title = document.querySelector(".titleInput").value;
const body = document.querySelector(".bodyInput").value;
e.preventDefault()
console.log(title, body)
})
<form id="newPostForm">
<input name="titleInput" class="titleInput" placeholder="title"><br>
<input name="bodyInput" class="bodyInput" placeholder="body">
<button>Submit</button>
</form>

Javascript getElementByID from form input

I am providing a form where the user shall enter an arithmetic calculation. Further down the result shall appear, once the user hits enter. It might just be a problem of syntax, but I couldn't find the mistake. Here is what I did so far:
<!DOCTYPE html>
<html>
<body>
<p>What do you want to calculate?</p>
<form method="post"><span>Type here:</span><input type="text" id="calc"></input>
</form>
<script>
num_field = document.getElementById("calc");
num_field.onsubmit=function ()
{
document.getElementById("display_result").innerHTML = num_field;
}
</script>
<p id="display_result"></p>
</body>
</html>
So, the user shall enter for instance "1+2". The result shall appear below.
Any idea where is my mistake?
Best regards
Here is how you can achieve that.
eval is the best way for doing that but eval is risky to use so make sure to sanitize the value of input before using eval.
I am using this regex /(^[-+/*0-9]+)/g to extract only numbers and few operators (-+/*) and doing eval on that value.
remove the <form> that is not required use keypress event listener and check for enter key. keycode of enter key is 13
num_field = document.getElementById("calc");
num_field.onkeypress = function(e) {
if(e.which==13)
{
var value = num_field.value.match(/(^[-+/*0-9]+)/g);
if(!value) return;
else value = value[0];
var res = eval(value);
document.getElementById("display_result").innerText = res;
}
}
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="calc" />
<p id="display_result"></p>
You were nearly there, your code just needed a bit of tweaking - see below (comments in code as what I have done and why)
The following seems to be an alternate and safer way to do this without using eval (function taken from the second answer in this post):
<!DOCTYPE html>
<html>
<body>
<p>What do you want to calculate?</p>
<form method="post" id="form">
<span>Type here:</span>
<input type="text" id="calc"> <!-- inputs are self closing no need for closing tag -->
<input type="submit" value="submit"> <!-- added a submit button -->
</form>
<script>
form = document.getElementById("form");
num_field = document.getElementById("calc");
form.onsubmit = function() { // attach this event to the form
document.getElementById("display_result").innerHTML = evalAlternate(num_field.value); // add .value here to get the value of the textbox
return false; // return false so form is not actually submitted and you stay on same page (otherwise your display result will not be updated as the page is reloaded
}
function evalAlternate(fn) { // function safer alternate to eval taken from here: https://stackoverflow.com/questions/6479236/calculate-string-value-in-javascript-not-using-eval
fn = fn.replace(/ /g, "");
fn = fn.replace(/(\d+)\^(\d+)/g, "Math.pow($1, $2)");
return new Function('return ' + fn)();
}
</script>
<p id="display_result"></p>
</body>
</html>
see the below fiddle
https://jsfiddle.net/ponmudi/13y9edve/
num_field = document.getElementById("calc");
num_field.onkeydown = (event) => {
if (event.keyCode === 13) {
document.getElementById("display_result").innerHTML = eval(num_field.value);
return false;
}
}
This should work:
calc = document.getElementById("calc");
formula = document.getElementById("formula");
calc.addEventListener('click', function() {
document.getElementById("display_result").innerHTML = eval(formula.value);
});
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="formula" />
<button id="calc" type="submit">calc</button>
<p id="display_result"></p>
eval() JavaScript Method
Try this:
var calculation_input = document.getElementById('calculation_input');
calculation_input.onkeydown = function(event) {
if (event.keyCode == 13) { // Enter key.
// Sanitize before using eval()
var calculation = calculation_input.value.replace(/[^-()\d/*+.]/g, '');
document.getElementById("display_result").innerHTML = eval(calculation);
}
}
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="calculation_input" />
<p id="display_result"></p>
You don't need to submit the calculation in a form, you can just use native javascript to calculate the result. And don't forget to always sanitize before using eval :)

Categories