Enable login button as soon as user fills both fields in Javascipt - javascript

I need to enable the submit button as soon as all input fields has value enterred. I have two input fields type text and type password and a button which is disabled (I set its class as "disabled" than use CSS to change color etc..), I would like to remove that class whenever the above condition is met. I added 'change' and 'input' event listeners to all field like below:
const inputs = [...document.querySelectorAll('input[type="text"], input[type="password"]')];
const continueBtn = document.querySelector('continuebtn');
const signinForm = document.querySelector('#sign-in-form');
inputs.forEach((input) => {
input.addEventListener('input', function(e){
if (input.value !== '') {
continueBtn.classList.remove('disabled');
}else{
continueBtn.classList.add('disabled');
}
}
});
Tried with e.target.value.trim() === '' as well
I guess the above would be applied to all inputs and check if they're empty when the user is typing, but I'm not able to make it work: the button is being activated no matter what I do.
I would need some help in plain Javascript as this is what I'm currently learning. no jQuery. Thanks

Use the every() method to check all the inputs, not just the one that the user is currently editing.
const inputs = [...document.querySelectorAll('input[type="text"], input[type="password"]')];
const continueBtn = document.querySelector('#continuebtn');
const signinForm = document.querySelector('#sign-in-form');
inputs.forEach((input) => {
input.addEventListener('input', function(e) {
if (inputs.every(input => input.value.trim())) {
continueBtn.classList.remove('disabled');
} else {
continueBtn.classList.add('disabled');
}
});
});
#continuebtn.disabled {
background-color: grey;
}
<input type="text">
<input type="password">
<button id="continuebtn" class="disabled">Continue</button>

Related

How to override event when some value is inputted in javascript

I would like to set complicated conditions.
My desired result is when I input some value and click the button, a confirmation Have you input ? will be alerted, and then clicked with input will be alerted, and if I don't input some value, clicked without input will be alerted.
But now, when I input some value, and click on the button, all three alerts appear together in this order-
clicked without input → Have you input ?→clicked with input.
How can I achieve the desired result when some value is inputted?
const myFunc = () => {
console.log("exec");
document.getElementById('button').addEventListener('click',confirmation);
}
const confirmation = () => {
const ret = confirm('Have you input ?');
if(ret){
alert("clicked with input")
} else {
return false
}
}
const clicked = () => {
alert("clicked without input");
}
<input oninput="myFunc()">
<button id="button" onclick="clicked()">open another window</button>
Check the value of the input before triggering the alert()
const clicked = () => {
const inputValue = document.getElementById('input').value;
if (inputValue) {
if (confirm('Have you input ?')){
alert(`clicked with input: ${inputValue}`)
}
} else {
alert("clicked without input");
}
}
<input id='input'>
<button id="button" onclick="clicked()">open another window</button>

How make input RESET Button?

How make input RESET Button?
INFO:
Hi I'm trying to do that if I click on my input which has the ID search-input so that if I write something in the input then class cancel which is the cross that resets the value it's like <button type =" reset "> so if I write something so that it appears to me sodisplay: block;and if I delete or input it won't have a value to dodisplay: none;and I would like to do all this to make it work even if the user doesn't have Javascript so I would like to do it in PHP version but I don't know what I have so far I only have this code which shows the icon when something is in the input but unfortunately the code has stopped working and especially when I delete the input via the button so the icon doesn't disappear for more information be sure not to be afraid to ask.
const input = document.getElementById("search-input")
const button = document.getElementById("cancel")
const icon = document.getElementById("icon")
input.addEventListener('keyup', test);
button.addEventListener("button", test)
function test() {
let isShown = false
if (input.value.trim() == "" || isShown == false) {
icon.style.display = "none"
isShown = true
} else {
icon.style.display = "flex"
}
}
PS: Everything was translated by Google translator if there was a mistake or you did not understand something write and I will definitely tell you how it should be thought in advance thank you very much for your help.
I think Uttam Nath's answer was close to what you wanted but not exactly. This may work better:
EDIT: Alright I changed the code a bit and I added the HTML with it so there is no confusion.
<body>
<input type="text" id="search-input">
<button type="button" id="cancel">Cancel</button>
<div id="icon" style="background-color: green; width: 50px; height: 50px; display: none;"></div>
</body>
<script>
const input = document.getElementById("search-input");
const button = document.getElementById("cancel")
const icon = document.getElementById("icon");
input.addEventListener('keyup', changeIconDisplay);
button.addEventListener('click', () => {
input.value = '';
changeIconDisplay();
});
function changeIconDisplay() {
if (input.value.trim() == "" ) {
icon.style.display = "none";
} else {
icon.style.display = "flex";
}
}
</script>

Find input value in other input fields

I need to check and find if a value of the current input field is found in other input fields on the page.
$(document).on("keyup", "input.card-label", function(){
var ths = $(this),
par = ths.closest(".inputContainer"),
val = ths.val();
if (ths.closest(".allInput").find("input.card-label").val() != val) {
par.removeClass("dupe");
} else {
par.addClass("dupe");
fle.prop("disabled", true);
}
});
I seem to have a partial success. When I edit a value that's a duplicate, the "dupe" class is removed, but when I intentionally enter a duplicate value, the "dupe" class is not added. What am I missing?
If I understand correctly, you want a class added when the value of an input is the same as the value of another input. The following code adds the keyup event to any input, then loops over all other inputs to determine if the current input's value is a duplicate, in which case it adds a CSS class.
I have gone for simplicity and just used the input selector. You should be able to tailor this to your needs.
$(function () {
$('input').on('keyup', function (e) {
// reference to this input
var input = $(e.currentTarget)
// get all inputs which are not this input
var allInputs = $('input').not(this)
// loop through all other inputs
for (var i = 0; i < allInputs.length; ++i) {
// if another input's value is the same as this, add the class
if ($(allInputs[i]).val() == input.val()) {
input.addClass('dup')
} else { // otherwise remove it (if it exists)
input.removeClass('dup')
}
}
})
})
.dup {
border-color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<input type="text" />

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>
);
}

Check if inputs have text and enable button

I'm trying to find a way that I can require two inputs to have text inside of them so I can toggle the disabled attribute on and off a button.
This would mean that when one input has text, the button is disabled. When both inputs have text, the button is enabled.
Here is my current code that I'm working with:
HTML:
<input name="e" placeholder="email">
<input name="p" placeholder="password">
<button id="submit_button" disabled>Submit</button>
JavaScript (no jQuery):
// Check if there is content in our form inputs and remove `disabled`
// from the button element.
var inputs = document.querySelectorAll('input[name="e"], input[name="p"]');
var button = document.querySelector('#submit_button');
[].forEach.call(inputs, function (e) {
e.addEventListener('input', function () {
// Set states for email and password inputs
if (this.value != "") {
button.removeAttribute('disabled');
} else {
button.setAttribute('disabled', '');
}
});
});
JSFiddle here
My thoughts with this code is that I would query the page for the two inputs, query for the button, and add an event listener that would check the input of each field, and when the value isn't empty, it would enable the button. Right now though, when you type something into either of the fields, regardless if both are filled in or not, the button becomes enabled.
How could I change this JavaScript so that both inputs must have text in order to enable the button?
How about this? :
var inputs = document.querySelectorAll('input[name="e"], input[name="p"]');
var button = document.querySelector('#submit_button');
[].forEach.call(inputs, function (e) {
e.addEventListener('input', function () {
var disabled = false;
[].forEach.call(inputs, function (inputElem) {
if(inputElem.value==''){
disabled = true;
}
});
// Set states for email and password inputs
if (disabled) {
button.setAttribute('disabled', '');
} else {
button.removeAttribute('disabled');
}
});
});
JSFiddle : http://jsfiddle.net/aecaaa9e/14/

Categories

Resources