Validating input fields not empty - javascript

I have made this code to validate if all input fields have been filled. If not submission is not allowed, but when it is correct I have to click twice on the submit button, the first time it validates and adds the eventListener and the second time it runs because it has the event listener. How can I modify the code so that I only have to click once?
function validaInput() {
const inputs = document.querySelectorAll(".input-field");
let validez;
inputs.forEach(function(input) {
if (input.value !== "") {
validez = true;
} else {
validez = false;
}
});
if (validez) {
submitBtn.addEventListener("click", calculaPromedio);
submitBtn.addEventListener("click", addMateria);
} else {
alert("No ha llenado todos los campos.");
}
}

Just call the relevant functions instead of adding a listener. (Also, you would otherwise add new duplicate listeners every time the button is clicked.)
if (validez) {
calculaPromedio();
addMateria();
} else {
alert("No ha llenado todos los campos.");
}
If you use this inside those function, you'd need instead e.g. calculaPromedio.call(this).

Related

Hide/show element if input has value

I want to hide or show an element based on if an input field has a value. Right now I have this, but the issue here is that it will add visible class every time a key is pressed and the value is not empty. Which is not correct and will lead to many problems down the line.
Is there a built in JavaScript event that I can use to check if the element is empty or not? What is the best way to do this with using the least amount of resources?
const query_input = document.getElementsByClassName("query")[0];
query_input.addEventListener('input', event => {
if (query_input.value == ""){
document.getElementsByClassName("submit")[0].classList.add("hidden");
console.log ("empty");
}else{
console.log ("not empty");
document.getElementsByClassName("submit")[0].classList.add("visible");
}
});
I think there is no such built-in thing.
You can do some improvement:
const query_input = document.querySelector(".query");
let btn = document.querySelector(".submit");
query_input.addEventListener('input', event => {
if (query_input.value.trim() == ""){
btn.classList.remove("visible");//remove
btn.classList.add("hidden"); //add
console.log ("empty");
}else{
console.log ("not empty");
btn.classList.remove("hidden"); //remove
btn.classList.add("visible"); //add
}
});
const query_input = document.getElementsByClassName("query")[0];
query_input.addEventListener('blur', event => {
if (query_input.value == ""){
document.getElementsByClassName("submit")[0].classList.add("hidden");
console.log ("empty");
} else {
console.log ("not empty");
document.getElementsByClassName("submit")[0].classList.add("visible");
}
});

React form onSubmit not noticing the Enter button

I am working on a form including a sort of tag input. If a user inputs a tag and hits enter it will add the tag to a certain array. But, when I hit enter, it will also submitting the form. Ofcourse, I can add the e.preventDefault() trick but then again, it will still run the JavaScript code, something I don't want when I am trying to input a tag.
So I've tried to add a if statement to notice if the key is equel to enter but the form don't get notified which button is clicked, I guess.
So this function will run If I hit enter on the form.
handleForm(e) {
e.preventDefault();
// Not working..
if(e.keyCode === 32) {
alert('Enter..') // prevent submitting further here or something
} else {
let state = { ...this.state.product }
if (state.name == '' || state.price == 0 || state.ingredients.length <= 0) {
alert('Naam, prijs en ingredienten zijn verplicht');
} else {
console.log(state);
}
}
}
How can I totally block the enter key for submitting? How can I use that key code for instance with a form or something? I've tried to add a event listener but that didn't work out since it will submit when I hit a other button than Enter.
For context, my tag input function which got fired from a keyup event.
handleKeyPress(e) {
// if the event key == enter key (is working..)
if (e.keyCode === 32) {
// Check if there is a ingredient supplied
if(this.state.tag == '') {
alert('Vul een ingredient in')
} else {
// Get the value of the ingredient input
let tag = this.state.tag;
// Copy state of just the ingredients (not the product)
let ingredients = [...this.state.product.ingredients];
// Create an array including only the names of the ingredients
let names = ingredients.map((item) => {
return item.name;
});
// Check if the array already includes the ingredient
if (names.includes(this.state.tag)) {
// Alert if the ingredient already exists
alert('Deze ingredient is al toegevoegd');
} else {
// Set the ingredient with value
let ingredient = { name: tag, value: 1 };
// Push the ingredient to the ingredients array of product
ingredients.push(ingredient);
// Get the product state
let product = this.state.product;
// set the ingredients of the product object with new ingredient
product.ingredients = ingredients;
// Change and set the state of proudct and empty out the tag input (ingredient)
this.setState({ product: product }, () => {
this.setState({ tag: '' });
});
}
}
}
}
When you use a form, it will always trigger onSubmit event when you hit enter, so assuming you want to use "enter" to keep adding tags, you can leave your add tags code in the submit function and add a button with type="button" (so the button wont submit on clicks) for when you are done with the form and use its onClick event to finish the form.
Example:
constructor(props) {
super(props);
this.handleDoneWithForm = this.handleDoneWithForm.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleDoneWithForm() {
// Code for when the form is finished
}
handleSubmit(event) {
event.preventDefault();
// Add tag code
}
render() {
return (
<form onSubmit={this.handleSubmit}> // will be triggered on enter
// form inputs
<button type="button" onClick={this.handleDoneWithForm}> // will be triggered on click
Done with form
</button>
</form>
);
}

Hot to re-active preventDefault function in javascript

When user clicked on submit button, I need to check some validations before submition. If entered data is not valid page should not be submit.
$(document).ready(function() {
$("#colomnChange").submit(function(e) {
var testA = 1;
if (testA == 1) {
testA = 2;
//e.preventDefault();
return false;
} else {
return true;
}
});
});
I can stop the submition using priventDefault function in js. But again user clicked on submit button after correct the wrong data, page should be submit well. How can I re-active the default function.
The answer is: you always go into the first if (because you set the variable to 1 then check if it equals 1, which is always true)
Change testA = 1 to testA = 2 and your event will go into the else which does not have the preventDefault() method so your event will carry on

Enabled and Disabled submit button when multiple fields are empty isn't working

I have here script for Enabled and Disabled submit button. I tried to use each function but isn't working. Every fields had it's value from database. The process should not allowed to submit if one of the fields was empty. Every fields has a value because I used it for editing window. Any help will appreciate. Thanks..
And this my fiddle http://jsfiddle.net/cj6v8/
$(document).ready(function () {
var saveButton = $("#save");
var empty = true;
$('input[type="text"]').change(function () {
$('.inputs').each(function () {
if ($(this).val() != "") {
empty = false;
} else {
empty = true;
}
});
if (!empty) {
saveButton.prop("disabled", false);
} else {
saveButton.prop("disabled", true);
}
});
}); // END OF DOCUMENT READY
The problem is the first else statement.
When $('.inputs').each(... iterates through your fields the empty variable is re-assigned a new value for every input field. In other words, the way you did it, only the last field was significant. (To test it, try this: leave the last one empty, and the button will be disabled, no matter what you put in the first two fields.)
Instead, try initializing empty at false just before the loop (you assume your fields are all filled with something), and then, when you iterate, as soon as you come across an empty field, set empty to true.
var empty = false;
$('.inputs').each(function() {
if($(this).val() == "")
empty = true;
});
As you can see, I removed the problematic else.
you need to init empty to false and cange it only if you find empty inputs inside to loop. http://jsfiddle.net/cj6v8/1/
If you don't want to submit when at least one field is empty you'll need to do this:
....
var empty = true;
$('input[type="text"]').change(function () {
empty = false;
$('.inputs').each(function () {
if ($(this).val() == "") {
empty = true;
break;
}
}
...
each is asynchronous, http://jsfiddle.net/cj6v8/4/
$(document).ready(function() {
var saveButton = $("#save");
$('input[type="text"]').change(function() {
var empty = true;
var inputs = $('.inputs');
inputs.each(function(i) {
if ($(this).val().length == 0) {
console.log($(this).val());
empty = false;
}
if (i === inputs.length-1) saveButton.attr("disabled", !empty);
});
});
});// END OF DOCUMENT READY

Form won't submit once error checking breaks it

I'm working on a project where I have some error checking. However, the form wanted to submit each time so I had to break the submit. Here is what I did.
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "order-form" }))
{
...
<input type="submit" name="btnSaveOpv#(item.Id)" value="#T("Admin.Common.Save")" id="btnSaveOpv#(item.Id)" class="adminButton" style="display: none;" onclick="SaveBtn(#item.Id);" />
...
var originalIssuedQty = 0;
function SaveBtn(id) {
var quantity = parseInt($("#pvQuantity" + id).val());
var issuedQty = parseInt($("#pvIssuedQty" + id).val());
var stockQty = parseInt($("#hfStockQty" + id).val());
var availableStockQty = stockQty + parseInt(originalIssuedQty);
//Issued Quantity cannot exceed Quantity (you can't issue more than requested)
if (issuedQty > quantity) {
alert("Issued Quantity cannot exceed Quantity.");
$("#order-form").submit(function (e) { e.preventDefault(); });
return false;
}
//Make sure Issued Quantity is within Available Stock Quantity
if (issuedQty > availableStockQty) {
alert("There is not enough Products in Stock to issue this amount.");
$("#order-form").submit(function (e) { e.preventDefault(); });
return false;
}
//Present confirmation
var result = confirm('#T("Admin.Common.AreYouSure")');
if (!result) {
$("#order-form").submit(function (e) { e.preventDefault(); });
return false;
}
else {
$("#order-form").submit(function (e) { this.submit(); });
//$("#order-form").submit(function (e) { return true; });
}
}
...
}
Here is the problem. Whenever I try to submit the first time without triggering any of my error checking, things work. When I trigger the error checking, things work. However, if I fix the error and try to submit again, the page merely refreshes. Any ideas on this would be very helpful. Thanks.
You are making things too complicated.
This is a basic template on how you do validation and how you stop the form from submitting when it's not valid:
$(function() {
$("#order-form").submit(function (e) {
var isValid = false;
// Do your validation here and put the result in the variable isValid
if ( !isValid ) {
e.preventDefault(); // If the form is invalid stop the submit, otherwise proceed
}
});
});
Every time you call $("#order-form").submit(function (e) { whatever });, you add an additional handler function. It doesn't remove the handlers you've already added. This is probably why it breaks.
Repeatedly changing the submit event handler is a messy way to do it. Instead, you should have a single function which handles the submit event, and that function should do (or call) the error checking, and preventDefault() if necessary (like ZippyV is suggesting).

Categories

Resources