Javascript form checking without innerhtml response - javascript

Hi im just starting to learn web development but I can't seem to find why my innerHTML won't appear on my page can someone help me ? I need to show these error messages if the fields are left empty but I can't seem to get it working for some reason :/
JS:
// B. email
const frmOrder = document.querySelector('#frmOrder');
const inpEmail = frmOrder.querySelector('#inpEmail');
const msgEmail = frmOrder.querySelector('.message');
// B. Dropdown
const selMeasure = frmOrder.querySelector('#selMeasure');
const msgMeasure = frmOrder.querySelector('.selMeasure .message');
//B. Checking
frmOrder.setAttribute('novalidate', 'novalidate');
frmOrder.addEventListener('sumbit', function (e) {
e.preventDefault();
let numErrors = 0 ;
msgEmail.innerHTML = '' ;
msgMeasure.innerHTML = '' ;
if (inpEmail.value == '' ) {
msgEmail.innerHTML = "please fill in ur email!";
numErrors++;
}
if (selMeasure.value == '' ) {
msgMeasure.innerHTML = "please fill in ur Measurement!";
numErrors++
}
if (numErrors == 0) {
frmOrder.sumbit();
lblMessage.innerHTML = `Het formulier is correct ingevuld`;
}
});

There are syntax errors in your code.
Change the word sumbit to submit.

Related

conditional statement for contact form not working

Im trying to first, check if both fields are not empty. if empty, alert user its empty. Then check if both user and password math and if they do match, then alert('welcome'). but if I type anything in the boxes, it passes and says welcome? Help!
const container = document.querySelector('.container');
const userInput = document.querySelector('#username');
const passInput = document.querySelector('#password');
const button = document.querySelector('button');
button.addEventListener('click', () => {
if (!userInput.value || !passInput.value) {
alert('One or more fields are empty. Please enter password and username');
}
if (!userInput.value == 'user21' || !passInput.value == 'user21') {
alert('password or username inavlid')
} else if (userInput.value == 'user21' && passInput.value == 'user21') {
alert(`Welcome ${userInput.value}`);
}
})*
Remove * at the end of your code and put ;
This:
if (!userInput.value == 'user21' || !passInput.value == 'user21') {
evaluates the ! first. It's like:
if ((!userInput.value) == 'user21' || (!passInput.value) == 'user21') {
which of course won't result in the comparison you want.
Check if the username and password match, and if they don't, just have a plain else, without an else if there.
button.addEventListener('click', () => {
if (!userInput.value || !passInput.value) {
alert('One or more fields are empty. Please enter password and username');
} else if (userInput.value == 'user21' && passInput.value == 'user21') {
alert(`Welcome ${userInput.value}`);
} else {
alert('password or username inavlid')
}
})
Also consider
using a proper modal instead of alert
if this is something you want any sort of reasonable security for, validate the logins using a backend database instead of hard-coding it on the front-end (which is trivially bypassable)

Tried to get data from a form and append it to a global array, but for some reason the data isn't being added

I am trying to get data from a form and append it to a global array but for some reason, the data isn't being added to the array. The code should basically accept the input from the form and store it into the global array. I updated the HTML so you can see the entire syntax. The value should basically be taken from the form and placed into the global array using the "addnew" function.
function addnew()
{
//calculateAge();
//Accept values entered in form
const fname = document.getElementById('fname').value;
const mname = document.getElementById('mname').value;
const lname= document.getElementById('lname').value;
const dob= document.getElementById('dob').value;
const genderM = document.getElementsByName('male').checked;
const genderF = document.getElementsByName('female').checked;
const age = calculateAge.bYear;
const bodyType = document.getElementById('Body Type').value;
const occu= document.getElementById('occu').value;
const height= document.getElementById('height').value;
if (fname==null || fname=="")
{
alert();
}
if(mname==null || mname=="")
{
alert();
}
if (lname==null || lname=="")
{
alert();
}
if(dob==null || dob=="")
{
alert();
}
if (genderM.checked == false || genderF.checked == false){
alert();
}
if (age <=18 || age >=75)
{
alert();
}
if(height>=170 || height<=200)
{
alert();
}
if(bodyType==null || bodyType==""){
alert();
}
if(oocu==null || oocu=="")
{
alert();
}
//Append To array
records.push(fname);
records.push(mname);
records.push(lname);
records.push(dob);
records.push(genderM);
records.push(genderF);
records.push(age);
records.push(bodyType);
records.push(occu);
records.push(height);
for(i=0;i<records.length;i++)
{
console.log(records[i]);
}
//showAll();
//<h1 class="logo"><img src="New folder/logo.jpg" /></h1>
Information.addEventListener('submit', addnew);
}
</script>
```
first of all. name attribute has nothing to do with form element.
second. Information.addEventListener('submit', addnew); has no meaning because Information is not defined.
and to the core. when submiing a form, the page refreshes defaultly, so the addNew function is aborted like all the other variables. in order to prevent it you have to do as follows.
on submit button ad an id attribute:
<button id="submit" type="submit"> Submit </button>
then on top of your JS, get the button element and add an event listener to it:
let submit = document.getElementById('submit');
submit.addEventListener('click', addnew );
and here is the final step. on the addNew function, add an event argument. and on the begining of the function's code, fire the preventDefault method:
function addnew(event) {
event.preventDefault();
// the rest of the code here
}
by the way. you have a typo here. it should be occu.
if (oocu == null || oocu == "") {
alert();
}
good luck!

Looping through 2 elements at a time

I'm trying to create error messages for labels on a form. Problem is that it's not working. The submitted input must be a number. Whenever it is not, clicking on the button should return a error message on the specific label.
Problem is - it only works OK if the first thing you submit is a correct set of numbers. I can't seem to get the combinations right. Do you know how I can solve this?
let coordValues = document.getElementsByClassName("input-card__input");
let submitBtn = document.getElementsByClassName("input-card__button");
let inputLabel = document.getElementsByClassName("input-card__label");
let weatherArray = [];
let labelArray = [];
for(let j=0;j<inputLabel.length;j++) {
labelArray.push(inputLabel[j].innerHTML);
}
submitBtn[0].addEventListener("click", function checkInputs() {
for(let i = 0; i<coordValues.length;i++) {
for(let k = 0; k<inputLabel.length;k++) {
if(coordValues[i].value === "" || isNaN(Number(coordValues[i].value))) {
inputLabel[k].classList.add("input-card__label--error");
inputLabel[k].innerHTML = "Oops! Write a number here."
console.log("nop");
break;
} else {
inputLabel[k].classList.remove("input-card__label--error");
inputLabel[k].innerHTML = labelArray[k];
console.log("yep");
break;
}
}
}
});
.input-card__label--error {
color: red;
}
<head>
</head>
<body>
<div class="input-card">
<h1 class="input-card__title">Where are you?</h1>
<h3 class="input-card__label">LONGITUDE</h3>
<input type="text" placeholder="Longitude" class="input-card__input">
<h3 class="input-card__label">ALTITUDE</h3>
<input type="text" placeholder="Altitude" class="input-card__input">
<button class="input-card__button">Show me weather ⛅</button>
</div>
</body>
There's a few errors in your code, here's a version I modified:
submitBtn[0].addEventListener("click", function checkInputs() {
for(let i = 0; i<coordValues.length;i++) {
if(coordValues[i].value === "" || isNaN(Number(coordValues[i].value))) {
inputLabel[i].classList.add("input-card__label--error");
inputLabel[i].innerHTML = "Oops! Write a number here."
console.log("nop");
return;
}
inputLabel[i].classList.remove("input-card__label--error");
inputLabel[i].innerHTML = labelArray[i];
}
console.log("yep");
});
One issue is the double for loop, it over complicates what you're trying to do.
Then once removed your code is left with a for loop then a test which all end up with a break so you never do more than one iteration.
The code above basically says log yes unless you find a reason to log nop.
In this case we need a flag to remember the error state:
submitBtn[0].addEventListener("click", function checkInputs() {
let allInputValid = true
for(let i = 0; i<coordValues.length;i++) {
if(coordValues[i].value === "" || isNaN(Number(coordValues[i].value))) {
inputLabel[i].classList.add("input-card__label--error");
inputLabel[i].innerHTML = "Oops! Write a number here."
console.log("nop");
allInputValid = false
}
else {
inputLabel[i].classList.remove("input-card__label--error");
inputLabel[i].innerHTML = labelArray[i];
}
}
if ( allInputValid )
console.log("yep");
});
Whenever an error is spotted, allInputValid is set to false. If there's two errors you set allInputValid to false twice.

Javascripting not working as expected, and no syntax errors returned?

Okay guys, I am trying to use JavaScript to validate a form, and then display a "Thank you" message after its all been validated with correct information. I've got it working to validate the first name, email address, and a radio selection, however I can't seem to get it to validate the state selection, or display the thank you message, but I've also used my browser's(Firefox) Dev Console to dig for syntax errors. None are displayed. Any help?
A small snip of the code is below, and a jsfiddle link to the whole code, plus the HTML is below that.
function validForm() { // reference point
/* first name, email, comments and phone */
var fname = document.form1.fname;
var email = document.form1.email;
var comments = document.form1.comments;
var phone1 = document.form1.phone1;
var phone2 = document.form1.phone2;
var phone3 = document.form1.phone3;
/* collecting the error spans for later use */
var fnErr = document.getElementById('fnErr');
var lnErr = document.getElementById('lnErr');
var emErr = document.getElementById('emErr');
var phErr = document.getElementById('phErr');
var cmErr = document.getElementById('cmErr');
var state = document.getElementById('stErr');
if(fname.value=="") {
fnErr.innerHTML = "We need your name, please.";
fname.focus();
return false;
} else {
fnErr.innerHTML = "";
}
if(email.value=="") {
emErr.innerHTML = "We need your email, please.";
email.focus();
return false;
} else {
emErr.innerHTML = "";
}
if(state.value=="none") {
fnErr.innerHTML = "Please select your state.";
state.focus();
return false;
} else {
fnErr.innerHTML = "";
}
/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/i;
if(isNaN(phone1.value) || isNaN(phone2.value) ||
isNaN(phone3.value)) {
phErr.innerHTML = "If you include a phone number it should be numbers only.";
phone1.select();
return false;
} else {
phErr.innerHTML = "";
}
var notices = document.form1.notices;
var selected;
for(var i=0;i<notices.length;i++) {
if(notices[i].checked) {
selected = notices[i].value;
}
}
/* set up a message for a advert recipient */
var msg = "Thank you, <b>"+fname.value
+"!</b> Your message has been received and one of our representatives will reply to <a href='"
+email.value+"'>"+email.value+"</a> within a day or two. Relax, and enjoy the rest of the site!";
if(selected != undefined) {
document.getElementById('notePref').innerHTML = "";
if (selected == "yes") { // here's where we test the contents of "selected"
document.getElementById('fnlMsg').innerHTML = msg;
} else {
document.getElementById('fnlMsg').innerHTML = "<strong>"+fname.value+"</strong>, thank you for your feedback!";
}
var contactForm = document.getElementById('registerForm').setAttribute('class','hide');
var loseSep = document.getElementsByClassName('spec');
loseSep[0].setAttribute('class', 'hide');
} else {
document.getElementById('notePref').innerHTML = "Please make a selection:";
}
} // reference point
https://jsfiddle.net/xp5e099y/2/
first: you dont have place(div/span/etc) with id ="fnlMsg"
second: you dont have place(div/span/etc) with id ="contactForm"
then change your html
<select name="state">
with
<select id="state">
and your script from this
var state = document.getElementById('stErr');
to
var state = document.getElementById('state');
Here is your culprit 'fnlMsg' element is not defined
if (selected == "yes") { // here's where we test the contents of "selected"
document.getElementById('fnlMsg').innerHTML = msg;
} else {
document.getElementById('fnlMsg').innerHTML = "<strong>"+fname.value+"</strong>, thank you for your feedback!";
}

Javascript validation on select input

I am trying to make a javascript validating form, and am a bit stuck on validating drop down inputs (select)
I have been using this so far but am unsure on how to implement the validation to the select options, if anyone could give me some tips that would be great.
Edit: Also, how would I implement email validation, e.g containing #, thanks
Thanks
<input id="firstname" onblur="validate('firstname')"></input>
Please enter your first name
Thanks
http://jsfiddle.net/ww2grozz/13/
you need to handle select as follow
var validated = {};
function validate(field) {
// Get the value of the input field being submitted
value = document.getElementById(field).value;
// Set the error field tag in the html
errorField = field + 'Error';
// Set the success field
successField = field + 'Success';
if (value != '') {
document.getElementById(successField).style.display = 'block';
document.getElementById(errorField).style.display = 'none';
validated[field] = true;
} else {
document.getElementById(successField).style.display = 'none';
document.getElementById(errorField).style.display = 'block';
validated[field] = false;
}
}
function SimulateSubmit() {
// Query your elements
var inputs = document.getElementsByTagName('input');
// Loop your elements
for (i = 0, len = inputs.length; i < len; i++) {
var name = inputs[i].id;
if (!validated[name]) {
// Call validate
validate(name);
// Prevent default
}
}
var all_select = document.getElementsByTagName("select"); // get al select box from the dom to validate
for (i = 0, len = all_select.length; i < len; i++) {
var name = all_select[i].id;
if (!validated[name]) {
// Call validate
validate(name);
// Prevent default
}
}
}
here the Working fiddle
using jQuery function
$('input').on('keyup', function() {
var isValid = $.trim($(this).val()) ? true : false;
// show result field is Valid
});
You must use <form> tag and set your action to it I have done that check this link and I have added select tag and set it to -1 by default for checking purpose while validating

Categories