I'm trying to show an error message in the span tags using jQuery. I can get the form fields to highlight in a red box and green box if input right but the text wont show up. I'm new to coding and been looking on the web for ideas and fixes, I know I'm missing something and it maybe simple but I'm racking my brains on it.
$(document).ready(function() {
// Name can't be blank
$('#name').on('input', function() {
var input = $(this);
var is_name = input.val();
if (is_name) {
input.removeClass("invalid").addClass("valid");
}
else {
input.removeClass("valid").addClass("invalid");
}
});
// Email must be an email
$('#email').on('input', function() {
var input = $(this);
var re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var is_email = re.test(input.val());
if (is_email) {
input.removeClass("invalid").addClass("valid");
}
else {
input.removeClass("valid").addClass("invalid");
}
});
// Message can't be blank
$('#message').keyup(function(event) {
var input = $(this);
var message = $(this).val();
console.log(message);
if (message) {
input.removeClass("invalid").addClass("valid");
}
else {
input.removeClass("valid").addClass("invalid");
}
});
// After Form Submitted Validation
$("#contact_submit button").click(function(event) {
var form_data = $("#contact").serializeArray();
var error_free = true;
for (var input in form_data) {
var element = $("#contact_submit" + form_data[input]['name'], ['email'], ['message']);
var valid = element.hasClass("valid");
var error_element = $("span", element.parent());
if (!valid) {
error_element.removeClass("error").addClass("error_show");
error_free = false;
}
else {
error_element.removeClass("error_show").addClass("error");
}
}
if (!error_free) {
event.preventDefault();
}
else {
alert('No errors: Form will be submitted');
}
});
});
.error {
display: none;
margin-left: 10px;
}
.error_show {
color: red;
margin-left: 10px;
}
input.invalid,
textarea.invalid {
border: 2px solid red;
}
input.valid,
textarea.valid {
border: 2px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<section class="body">
<form id="contact" method="post" enctype="multipart/form-data" action="">
<h1 class="title">Contact</h1>
<div>
<label for="name">Your Fullname</label>
<input type="text" id="name" name="name" required placeholder="Your Name">
<span class="error error_show">This field is required</span>
</div>
<div>
<label for="email">Your Full Email</label>
<input name="email" type="email" id="email" required placeholder="Your Email">
<span class="error error_show">This field is required</span>
</div>
<div>
<label for="message">Message</label>
<textarea id="message" name="message" cols="20" rows="5" required placeholder="Message"></textarea>
<span class="error error_show">This field is required</span>
</div>
<div id="contact_submit">
<button type="submit"></button>
</div>
</form>
</section>
I think you might have made it more complicated than it needed to be. See if the below snippet doesn't work the way you expected.
$(document).ready(function() {
$('#name').on('input', function() {
var input = $(this);
var is_name = input.val();
if (is_name) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
$('#email').on('input', function() {
var input = $(this);
var re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var is_email = re.test(input.val());
if (is_email) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
$('#message').keyup(function(event) {
var input = $(this);
var message = $(this).val();
console.log(message);
if (message) {
input.removeClass("invalid").addClass("valid");
} else {
input.removeClass("valid").addClass("invalid");
}
});
$("#contact_submit #submit_button").click(function(event) {
$("#name_error").hide();
$("#email_error").hide();
$("#message_error").hide();
var success = true;
if (!$("#name").hasClass("valid")) {
success = false;
$("#name_error").show();
}
if (!$("#email").hasClass("valid")) {
success = false;
$("#email_error").show();
}
if (!$("#message").hasClass("valid")) {
success = false;
$("#message_error").show();
}
if (success === false) {
event.preventDefault();
}
else {
alert('No errors: Form will be submitted');
}
});
});
.error {
display: none;
margin-left: 10px;
}
.error_show {
color: red;
margin-left: 10px;
display: none;
}
input.invalid,
textarea.invalid {
border: 2px solid red;
}
input.valid,
textarea.valid {
border: 2px solid green;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<section class="body">
<form id="contact" method="post" enctype="multipart/form-data" action="">
<h1 class="title">Contact</h1>
<div>
<label for="name">Your Fullname</label>
<input type="text" id="name" name="name" required placeholder="Your Name">
<span id="name_error" class="error_show">This field is required</span>
</div>
<div>
<label for="email">Your Full Email</label>
<input name="email" type="email" id="email" required placeholder="Your Email">
<span id="email_error" class="error_show">This field is required</span>
</div>
<div>
<label for="message">Message</label>
<textarea id="message" name="message" cols="20" rows="5" required placeholder="Message"></textarea>
<span id="message_error" class="error_show">This field is required</span>
</div>
<div id="contact_submit">
<input type="submit" id="submit_button" value="Submit">
</div>
</form>
</section>
</body>
</html>
var element = $("#contact_submit" + form_data[input]['name'], ['email'], ['message']);
var valid = element.hasClass("valid");
var error_element = $("span", element.parent());
I think these lines don't select the right span.
I got to it on logging the error_element:
console.log(error_element);
Here is a JSFIDDLE with a "working" selector.
var error_element=$("#contact div span");
Now you can change the selector that it fits your needs!
Related
I want to show the error message of required if mandatory fields are left blank. I implement it using the following way but every time the function checkinput() is invoked it adds a new span element due to which "required" message is outputted multiple times. I want the span element to be added once and disappears when user fills in the requirement. Here is my code.
const checkinput=(event)=>{
if(event.target.value===""){
event.target.insertAdjacentHTML('afterend','<span class="text-danger">Required</span>')
}
if(event.target.value!==""){
var child=document.querySelector('span');
child.remove();
}
}
document.getElementById("username").addEventListener('blur',checkinput);
document.getElementById("password").addEventListener('blur',checkinput);
document.getElementById("confirmPassword").addEventListener('blur',checkinput);
Reason why new span element is added each time you have a empty input field is because you are calling insertAdjacentHTML each time and inserting a new span element.
What you should do is add span elements with each input field in the html and initially they should be empty.When you want to validate the input fields, if any of the input is empty, select the span element next to that input element and show the error message in that span element using .textContent property. To clear the error message, you just need to set .textContent of the span element to an empty string.
Following code snippets show different ways of validating form inputs.
Form validation on form submit
Following code snippet validates form inputs when form is submitted.
const form = document.querySelector('form');
const usernameError = document.querySelector('#usernameError');
const passwordError = document.querySelector('#passwordError');
form.addEventListener('submit', (event) => {
event.preventDefault();
const usernameValid = validateField(form, 'username', usernameError);
const passwordValid = validateField(form, 'password', passwordError);
if (usernameValid && passwordValid) {
console.log('form submitted');
form.reset();
}
});
function validateField(form, fieldName, errorEl) {
if (form.elements[fieldName].value == '') {
errorEl.textContent = `${fieldName} is required`;
return false;
} else {
errorEl.textContent = '';
return true;
}
}
form div {
margin: 0 0 10px;
display: flex;
flex-direction: column;
max-width: 200px;
}
form label { margin: 0 0 5px; }
span { color: red; }
<form>
<div>
<label>Username</label>
<input type="text" name="username" />
<span id="usernameError"></span>
</div>
<div>
<label>Password</label>
<input type="password" name="password" />
<span id="passwordError"></span>
</div>
<button>Submit</button>
</form>
Form validation on input focus loose
Following code snippet validates form inputs when any of the input looses focus.
const form = document.querySelector('form');
const inputsContainer = document.getElementById('formInputsContainer');
const submitBtn = document.querySelector('button');
form.addEventListener('submit', (event) => {
event.preventDefault();
const usernameValid = validateField(form, 'username');
const passwordValid = validateField(form, 'password');
if (usernameValid && passwordValid) {
console.log('form submitted');
form.reset();
}
});
submitBtn.addEventListener('focus', () => {
form.requestSubmit();
});
inputsContainer.addEventListener('focusout', (event) => {
validateField(form, event.target.name);
});
function validateField(form, fieldName) {
const errorEl = document.getElementById(`${fieldName}Error`);
if (form.elements[fieldName].value == '') {
errorEl.textContent = `${fieldName} is required`;
return false;
} else {
errorEl.textContent = '';
return true;
}
}
form div {
margin: 0 0 10px;
display: flex;
flex-direction: column;
max-width: 200px;
}
form label { margin: 0 0 5px; }
span { color: red; }
<form>
<div id="formInputsContainer">
<div>
<label>Username</label>
<input type="text" name="username" />
<span id="usernameError"></span>
</div>
<div>
<label>Password</label>
<input type="password" name="password" />
<span id="passwordError"></span>
</div>
</div>
<button>Submit</button>
</form>
Form validation as user types in the input field
Following code snippet validates form input as user types in any input field.
const form = document.querySelector('form');
const inputsContainer = document.getElementById('formInputsContainer');
form.addEventListener('submit', (event) => {
event.preventDefault();
const usernameValid = validateField(form, 'username');
const passwordValid = validateField(form, 'password');
if (usernameValid && passwordValid) {
console.log('form submitted');
form.reset();
}
});
inputsContainer.addEventListener('input', (event) => {
validateField(form, event.target.name);
});
function validateField(form, fieldName) {
const errorEl = document.getElementById(`${fieldName}Error`);
if (form.elements[fieldName].value == '') {
errorEl.textContent = `${fieldName} is required`;
return false;
} else {
errorEl.textContent = '';
return true;
}
}
form div {
margin: 0 0 10px;
display: flex;
flex-direction: column;
max-width: 200px;
}
form label { margin: 0 0 5px; }
span { color: red; }
<form>
<div id="formInputsContainer">
<div>
<label>Username</label>
<input type="text" name="username" />
<span id="usernameError"></span>
</div>
<div>
<label>Password</label>
<input type="password" name="password" />
<span id="passwordError"></span>
</div>
</div>
<button>Submit</button>
</form>
You need something like
if(event.target.value==="" && document.querySelector('span') === null){
event.target.insertAdjacentHTML('afterend','<span class="text-danger">Required</span>')
}
if(event.target.value!==""){
var child=document.querySelector('span');
child.remove();
}
You only want to add a span IF the value is an empty string AND the span hsan't been added yet.
You can use this code which create a span which is add to the DOM with the ID which is based on the form element'sname attribute. And that element can be refered to based on the ID which was attach to it before It's been add to the DOM
const checkinput=(event)=>{
if(event.target.value===""){
let spanId = `input-${event.target.name}`
let span = `<span id="${spanId}" class="text-danger">Required</span>`
setTimeout(() =>{
document.getElementById(spanId).remove();
}, 5000);
event.target.insertAdjacentHTML('afterend',span)
}
}
document.getElementById("username").addEventListener('blur',checkinput);
document.getElementById("password").addEventListener('blur',checkinput);
document.getElementById("confirmPassword").addEventListener('blur',checkinput);
<form>
<input type="text" name="username" id="username"/>
<input type="text" name="password" id="password"/>
<input type="text" name="confirmPassword" id="confirmPassword"/>
</form>
May it help
<style>
.errorMsg {
border: 1px solid red;
}
.err {
color: red;
}
</style>
<form>
<input type="text" name="name" id="name">
<input type="password" name="password" id="password">
<button id="submit" type="submit">Submit</button>
</form>
<script>
let nameTag = document.querySelector('#name');
let passwordTag = document.querySelector('#password');
let submitBtn = document.querySelector('#submit');
nameTag.addEventListener('blur', e => validation(e));
passwordTag.addEventListener('blur', e => validation(e));
function validation(e) {
if (e.target.value == '') {
e.target.classList.add('errorMsg')
submitBtn.setAttribute('disabled', true) // Disable submit that user cannot submit
e.target.insertAdjacentHTML('afterend', `<span class="err ${e.target.id}">It is required</span>`)
// In the above line we are inserting an element with class same as id of input that in the remove we remove a particular error message only
} else {
e.target.classList.remove('errorMsg')
submitBtn.removeAttribute('disabled')
document.querySelector(`.err.${e.target.id}`).remove();
//Here code is saying that the element with if 'err' and 'class same as id of input' if both class present then remove it
}
}
</script>
Adding the class = id that a special error message delete
I want to check if all my inputs are filled to activate a submit button, but with my code it checks only one input.
My HTML (with TWIG) :
<div class="content-wrapper content-wrapper--close">
<form class="form form--width">
<fieldset class="form__fieldset input">
<input class="input__field" id="name" name="name"/>
<label class="input__label" for="name">Nom et prénom</label>
</fieldset>
<fieldset class="form__fieldset input">
<input class="input__field" id="structure" name="structure"/>
<label class="input__label" for="structure">Structure</label>
</fieldset>
<fieldset class="form__fieldset input">
<input class="input__field" id="email" name="email"/>
<label class="input__label" for="email">Adresse email</label>
</fieldset>
<fieldset class="form__fieldset input">
<textarea class="input__field input__field--textarea" name="message" id="message" rows="10">
</textarea>
<label class="input__label" for="message">Message</label>
</fieldset>
<fieldset class="form__fieldset">
<div class="cta is-disabled">
<input type="submit" class="cta__link button" value="Envoyer">
</div>
</fieldset>
</form>
</div>
My javascript:
/**
* Add event listener on input.
*
* #param form
*/
addListener(form) {
const inputs = form.querySelectorAll('.input__field');
[...inputs].map( input => {
input.addEventListener('focus', (event) => {
event.target.classList.add('is-fill');
});
input.addEventListener('blur', (event) => {
if (event.target.value === '') {
event.target.classList.remove('is-fill');
}
});
});
}
// // If all fields are filled, remove class 'is-disabled'
handleInputs(items) {
const inputs = items.querySelectorAll('.input__field');
const submitButton = document.querySelector('.form .cta');
[...inputs].map( input => {
input.addEventListener('input', (e) => {
if(e.target.value !== '') {
submitButton.classList.remove('is-disabled');
} else {
if(!submitButton.classList.contains('is-disabled')) {
submitButton.classList.add('is-disabled');
}
}
});
});
}
For now it only works with only one input and I don't know how to do to check all the input. If somebody can help me, I don't find any answer.
Thanks
With HTML5 you can style the form button when the form is not invalid. Simple CSS rule and it will apply the styles. It also by default prevents the form from submitting.
The button will remain red until the form is filled in with a valid name, email, and date. I also added a rule that alters the current element being edited which your code is also doing.
input {
margin: .5rem;
}
input:focus {
box-shadow: 0px 0px 5px 5px #0ff;
}
form:invalid input[type="submit"] {
background-color: red
}
<form>
<fieldset>
<legend>User:</legend>
<label for="name">Name:</label>
<input type="text" id="name" required><br>
<label for="email">Email:</label>
<input type="email" id="email" required><br>
<label for="dob">Date of birth:</label>
<input type="date" id="bod" required>
</fieldset>
<input type="submit" />
</form>
You might need to loop through each input every time an input changes:
$(document).ready(function () {
var shouldShowSubmitBtn = true;
$("input").change(function () {
$(":input").each(function () {
if ($(this).val() == '') {
shouldShowSubmitBtn = false;
return false;
}
});
});
});
The code I used :
for (const input of inputs) {
input.addEventListener(`input`, () => {
for (const input of inputs) {
if (input.value.length === 0) {
submitButton.disabled = true;
cta.classList.add('is-disabled');
break;
} else {
submitButton.disabled = false;
cta.classList.remove('is-disabled');
}
}
});
}
check email validation and give error under the email block field
function email_check()
{
var email = document.getElementById('email').value;
var datas = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if(datas.test(email) == false)
{
document.getElementById('errorpassword').innerHTML = "this is an invalid email";
}
return false;
}
<input type ="email" placeholder="email id" id="email" required onblur="email_check(this.value)"/>
<span id="erroremail"></span>
Try the following code and edit it in the way you need it
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validate() {
var $result = $("#result");
var email = $("#email").val();
$result.text("");
if (validateEmail(email)) {
$result.text(email + " is valid :)");
$result.css("color", "green");
} else {
$result.text(email + " is not valid :(");
$result.css("color", "red");
}
return false;
}
$("#validate").bind("click", validate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<p>Enter an email address:</p>
<input id='email'>
<button type='submit' id='validate'>Validate!</button>
</form>
<h2 id='result'></h2>
HTML Code:
<div class="form-group">
<label class="control-label" for="event-mail">Email: </label>
<div class="events">
<input id="emailaddress" name="emailaddress" placeholder="Email Address" type="email" data-error-empty="Please enter your email" data-error-invalid="Invalid email address" >
</div>
<button name="submit" id="validate" type="submit"> Validate
</button>
</div><!-- End Email input -->
JS Code:
$(document).ready(function () {
$('#validate').click(function () {
$('.error-message').remove();
$('.success-message').remove();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
alert($('#emailaddress').val());
if (!emailReg.test($.trim($('#emailaddress').val()))) {
var invalidEmail = $('#emailaddress').data('error-invalid');
$('#emailaddress').parents('.events').append('<span class="error-message" style="display:none;">' + invalidEmail + '.</span>').find('.error-message').fadeIn('fast');
$('#emailaddress').addClass('inputError');
}
else
{
$('#emailaddress').parents('.events').append('<span class="success-message" style="display:none;">Valid email address.</span>').find('.success-message').fadeIn('fast');
$('#emailaddress').addClass('inputSuccess');
}
});
});
CSS:
.inputError{
color: red;
}
.inputSuccess{
color: green;
}
Jsfiddle
I have my HTML and JS, how would I use this form in my JS so if one of the fields are not entered, the form doesnt submit and shows me my original please enter all fields error
Form:
<form id="myForm" action="http://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
HTML:
<!doctype html>
<html lang="en">
<head>
<title> Forms </title>
<style>
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button { margin-left: 10px; }
body {
width: 80%; margin: auto; font-family: sans-serif;
border: 1px solid black;
}
</style>
<meta charset="utf-8">
<script src="prototype.js"></script>
<script src="forms.js"></script>
</head>
<body>
<h1> Keyboard Events and Form Submit </h1>
<!-- Form -->
<form id="myForm" action="http://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
<p> <span>Name:</span> <input id="input1" value="" placeholder="Enter Name" name="Name"></p>
<p> <span>Id:</span> <input id="input2" value=""
placeholder="Enter ID" name="ID"></p>
<p> <span>Email:</span> <input id="input3" value="" placeholder="Enter Email" name="Email"></p>
<p>
<button id="submitButton" type="button" onclick="submit()"> Submit </button>
<button id="resetButton" type="button" onclick="reset()"> Reset </button>
</p>
<p style="color:red" id="ErrorMessage"> </p>
</body>
</html>
JS:
function reset(){
document.getElementById('input1').value = "";
document.getElementById('input2').value = "";
document.getElementById('input3').value = "";
document.getElementById('ErrorMessage').innerHTML = "";
}
function submit(){
var inp1 = document.getElementById('input1').value;
var inp2 = document.getElementById('input2').value;
var inp3 = document.getElementById('input3').value;
if(inp1 == "" || inp2 == "" || inp3 == "")
{
document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
}
else{
//do your code here
document.getElementById('ErrorMessage').innerHTML = "";
}
}
change your function name submit() to another because it conflict with builtin JS function, doing onclick="submit()" is same with this.form.submit() or document.getElementById('myForm').submit();
function reset() {
document.getElementById('input1').value = "";
document.getElementById('input2').value = "";
document.getElementById('input3').value = "";
document.getElementById('ErrorMessage').innerHTML = "";
}
function checkSubmit() {
var inp1 = document.getElementById('input1').value;
var inp2 = document.getElementById('input2').value;
var inp3 = document.getElementById('input3').value;
if (inp1 == "" || inp2 == "" || inp3 == "") {
document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
} else {
//do your code here
document.getElementById('ErrorMessage').innerHTML = "submitting form";
document.getElementById('myForm').submit();
}
}
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button {
margin-left: 10px;
}
body {
width: 80%;
margin: auto;
font-family: sans-serif;
border: 1px solid black;
}
<h1> Keyboard Events and Form Submit </h1>
<!-- Form -->
<form id="myForm" action="https://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
<p> <span>Name:</span> <input id="input1" value="" placeholder="Enter Name" name="Name"></p>
<p> <span>Id:</span> <input id="input2" value="" placeholder="Enter ID" name="ID"></p>
<p> <span>Email:</span> <input id="input3" value="" placeholder="Enter Email" name="Email"></p>
<p>
<button id="submitButton" type="button" onclick="checkSubmit()"> Submit </button>
<button id="resetButton" type="button" onclick="reset()"> Reset </button>
</p>
<p style="color:red" id="ErrorMessage"> </p>
</form>
Change button type to "submit" and do validation in onsubmit event handler:
<form onsubmit="return validateMethod()" />
Move all your validation logics into validateMethod, return false if the validation is failed.
Below is an example but I think you should use a jquery lib for this:
function validateMethod(){
var inp1 = document.getElementById('input1').value;
var inp2 = document.getElementById('input2').value;
var inp3 = document.getElementById('input3').value;
if(!inp1 || !inp2 || !inp3)
{
document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
return false;
}
else{
//do your code here
document.getElementById('ErrorMessage').innerHTML = "";
return true;
}
}
You could simply use document.getElementById('myForm').addEventListener('submit', () => submit());
But you need to change <button id="submitButton" type="button" onclick="submit()"> Submit </button> to <button id="submitButton" type="submit"> Submit </button> (as Barmar said) and you also need to close your <form> tag.
Upon button click of the submission button you can iterate over all the input fields, determine whether or not they have the attribute required and then determine whether or not their value is an empty string (!field.value)
We put this in a try/catch block so that if a field is required and does not have a value, we can break out of the forEach loop by throwing an error and displaying the message Please Enter All Required Fields
let submit = document.querySelector("button");
submit.addEventListener("click", submitFn);
function submitFn() {
try {
document.querySelectorAll("form input").forEach(function(field) {
if (field.hasAttribute("required") && !field.value) {
throw error("not all fields filled in");
}
});
alert("all required fields filled in!")
} catch {
alert("please enter all required fields");
}
}
<form>
<label>first name </label><input required/>
<br/>
<label>last name</label><input required/>
<br/>
<label>email ( not required )</label><input />
<hr>
<button type="button">submit</button>
</form>
Note: It would be better code if you changed the type of the submit button to submit and changed the event from the above code from click to submit, but I've no idea if there was a reason for your markup or not so I leave that to your discretion.
I am writing a toggle in pure JavaScript.
There are 2 input fields, 1 is hidden and the other is visible. When we click on the first 1, the second input should appear and when both of the input fields are visible and one of the input fields is clicked then that input field should display:block and the other input field should display:none. Also, the latest clicked input element should remain on top and the other one below it. (es6 would be also good)
if anyone knows please check ?
code
<form action="#" class="navbar-top" role="search" autocomplete="off"><input name="p" data-hit="Type" type="text" autocomplete="new-password" value="" data-open="false" class="input-bg neww" placeholder="Type "></form>
<form action="#" class="navbar-top" role="search" autocomplete="off"><input name="p" data-hit="Type" type="text" autocomplete="new-password" value="" data-open="false" class="input-bg neww1" placeholder="Type "></form>
body{
background:#873e66;
}
.input-bg{
background:white;
border:none;
color:black;
height:50px;
text-indent:15px;
width:500px;
border-radius:26px;
outline:none;
}
.neww1{
margin-top:5px;
}
::-webkit-input-placeholder {
color: black;
}
::-moz-placeholder {
color: black;
}
:-ms-input-placeholder {
color: black;
}
.neww1{
display:none;
}
function toggleClass(element, className){
if (!element || !className){
return;
}
var classString = element.className, nameIndex = classString.indexOf(className);
if (nameIndex == -1) {
classString += ' ' + className;
}
else {
classString = classString.substr(0, nameIndex) + classString.substr(nameIndex+className.length);
}
element.className = classString;
}
Thanks!
you can proceed like :
const inputs = [].slice.call(document.getElementsByClassName("input-bg"));
inputs.forEach((input) => {
console.log()
input.addEventListener("click", (event) => {
const somehidden = inputs.filter((_input) => {
return _input.getAttribute("class").match(/neww1/i);
})
if (somehidden.length > 0) {
somehidden[0].classList.remove("neww1");
} else {
inputs.forEach((i) => {
if (i !== event.target)
i.classList.add("neww1");
});
}
});
});
body {
background: #873e66;
}
.grid {
display: grid;
grid-template-areas: "up" "down";
}
form:focus-within {
grid-area: up;
}
.input-bg {
background: white;
border: none;
color: black;
height: 50px;
text-indent: 15px;
width: 500px;
border-radius: 26px;
outline: none;
}
.neww1 {
margin-top: 5px;
}
::-webkit-input-placeholder {
color: black;
}
::-moz-placeholder {
color: black;
}
:-ms-input-placeholder {
color: black;
}
.neww1 {
display: none;
}
<div class="grid">
<form action="#" class="navbar-top" role="search" autocomplete="off"><input name="p" data-hit="Type" type="text" autocomplete="new-password" value="" data-open="false" class="input-bg neww" placeholder="Type "></form>
<form action="#" class="navbar-top" role="search" autocomplete="off"><input name="p" data-hit="Type" type="text" autocomplete="new-password" value="" data-open="false" class="input-bg neww1" placeholder="Type2 "></form>
</div>
Although your requirement is not very clear but my answer might be of some help
Let's say we have two input fields like this:
<div class="input-container">
<input type="password" placeholder="Input 1" class="myInput first" />
<input type="password" placeholder="Input 2" class="myInput second hidden" />
</div>
CSS can be like:
.input-container {
display: flex;
flex-direction: column;
}
.myInput {
margin: 10px;
padding: 5px
}
.first {
order: 1;
}
.second {
order: 2;
}
.hidden {
display: none;
}
Now the toggle function (JS):
var allInputs = document.querySelectorAll('.myInput');
allInputs.forEach(function(node) {
node.addEventListener("click", function(){
var allHiddenInputs = document.querySelectorAll('.hidden');
if(allHiddenInputs.length === 0) {
allInputs.forEach(function(input) {
input.classList.add("hidden");
input.classList.add("second");
input.classList.remove("first");
});
node.classList.remove("hidden");
node.classList.remove("second");
node.classList.add("first");
} else {
allHiddenInputs.forEach(function(input) {
input.classList.remove("hidden");
});
}
});
});
https://codepen.io/tusharshukla/pen/rrqvQz?editors=1010
Something like this could help you. I'm directly changing the CSS but you can also toggle classes using the classList.
<html>
<body>
<form action="#" class="navbar-top" role="search" autocomplete="off">
<input name="p" id="input1" data-hit="Type" type="text" autocomplete="new-password" value="" data-open="false" class="input-bg neww"
placeholder="Input One ">
</form>
<form action="#" class="navbar-top" role="search" autocomplete="off">
<input name="p" id="input2" data-hit="Type" type="text" autocomplete="new-password" value="" data-open="false" class="input-bg neww1"
placeholder="Input Two ">
</form>
<script>
(function () {
const inputOne = document.getElementById('input1');
const inputTwo = document.getElementById('input2');
const handleClick = i => (i === inputOne ? inputTwo : inputOne)
.style.display = 'none';
const handleBlur = i => {
if (i === inputOne) {
inputTwo.style.display = 'block';
inputOne.style.display = 'none';
} else {
inputTwo.style.display = 'none';
inputOne.style.display = 'block';
}
}
[inputOne, inputTwo].forEach((i) => {
i.addEventListener('click', () => handleClick(i))
i.addEventListener('focusout', () => handleBlur(i))
});
})();
</script>
</body>
</html>
You have the classList attribute with your HTML Element.
So first you need the element reference, you can use your constructor and private variables and set the private variable with document.getElementByClassName according to initial state of your page, or set an ID. Let's take for example an ID :
<form onclick="toggleClass()" id="password1" action="#" class="navbar-top" role="search" autocomplete="off"><input name="p" data-hit="Type" type="text" autocomplete="new-password" value="" data-open="false" class="input-bg neww" placeholder="Type "></form>
<form onclick="toggleClass()" id="password2" action="#" class="navbar-top" role="search" autocomplete="off"><input name="p" data-hit="Type" type="text" autocomplete="new-password" value="" data-open="false" class="input-bg neww1" placeholder="Type "></form>
Then just find the reference
const password1 = document.getElementById("password1");
const password2 = document.getElementById("password2");
and after that, you can write this function :
function toggleClass() {
const password1 = document.getElementById("password1");
const password2 = document.getElementById("password2");
if (password1.classList.contains('hidden')){
password1.classList.remove('hidden');
password2.classList.add('hidden');
}
else {
password2.classList.remove('hidden');
password1.classList.add('hidden');
}
}
.neww1 {
background-color : red;
}
.neww {
background-color : green;
}
.hidden {
display:none;
}
input {
margin:5px;
}