Get ID attribute of each form - javascript

I need to console log ID attribute of each form element on click. So if someone clicks not on the form element, I don't want to console log it.
Here's my code:
<form class="cf">
<div class="half left cf">
<input type="text" id="input-name" placeholder="Name">
<input type="email" id="input-email" placeholder="Email address">
<input type="text" id="input-subject" placeholder="Subject">
</div>
<div class="half right cf">
<textarea name="message" type="text" id="input-message" placeholder="Message"></textarea>
</div>
<input type="submit" value="Submit" id="input-submit">
</form>
I tried :
document.addEventListener('click', function(e) {
console.log(e.target.id);
}, false);
It does console log, but everything on click, and I need only the ID attribute of each form on click.

You can simply just add a click listener event to your form.
Example:
let forms = document.querySelectorAll('form');
function formClicked(event) {
console.log(event.target.id);
}
forms.forEach(form => {
form.addEventListener('click', formClicked, false);
});

Related

How to check all the form fields were given to enable the submit button?

I need to enable the submit button, only when all the Input values were given.
I have a form like the below in my blade file.
<form method="POST" id="contactForm">
<div class="row">
<div class="col-6">
<input type="text" name="name" id="name" value=""/>
<div class="error">Error Message</div>
</div>
<div class="col-6">
<input type="text" name="email" id="email" value=""/>
<div class="error">Error Message</div>
</div>
<div class="col-12">
<textarea name="body" id="message" rows="5"> Enter your message</textarea>
<div class="error">Error message</div>
</div>
<div class="col-12">
<input type="submit" value="Submit" class="primary" id="buttonSubmit" disabled/>
</div>
</form>
Added the required attribute inside the controller.
In controller:
public function store()
{
$data = request()->validate([
'name' => 'required',
'email' => 'required|email',
'body' => 'required',
]);
}
The problem is, even if I add the name field and click the button , the submit button is disabled on click.
The button should be disabled, only when all the input fields were given.
Script:
const button = document.querySelector("#buttonSubmit");
const buttonExpirationDataKey = 'button-disabled-expiration';
button.addEventListener("click", () => {
var form = document.getElementById("contactForm");
var fields = ["name", "email","body"];
var i, l = fields.length;
var fieldname;
for (i = 0; i < l; i++) {
fieldname = fields[i];
if(form[fieldname].value !== ""){
button.disabled = true;
let now = new Date();
let expirationTime = 1000 * 5; // 5 secs to disable the submit button
let expirationDate = new Date(now.getTime() + expirationTime);
localStorage.setItem(buttonExpirationDataKey, expirationDate);
button.dataset.enabledAt = expirationDate;
}
else {
button.disabled = false;
}
return false;
}
});
The for loop iterates over each input element, if the particular input element have a value and then If we click the submit. The button is disabled and stored in the local storage.
How to check all the form input and the textarea has values and then after clicking the submit button, the button should be disabled for 5 secs.
https://jsfiddle.net/1vgzj8oc/
How could I do this? Could anyone please help?
You can simply add the required attributes to the HTML
<input type="text" name="name" id="name" value="" required/>
But if you choose to do it with jS, you can do it this way...
<input type="text" name="name" id="name" value="" class="requiredInput"/>
<input type="submit" value="Submit" class="requiredInput primary" id="buttonSubmit" disabled/>
const requiredInputs = document.querySelectorAll(".requiredInput");
requiredInputs.forEach(function(input) {
// Logic
});
You can add required attribute. added link for reference
[https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/required]
<form method="POST" id="contactForm">
<div class="row">
<div class="col-6">
<input type="text" name="name" id="name" value="" required/>
<div class="error">Error Message</div>
</div>
<div class="col-6">
<input type="text" name="email" id="email" value="" required/>
<div class="error">Error Message</div>
</div>
<div class="col-12">
<textarea name="body" id="message" rows="5" required> Enter your message</textarea>
<div class="error">Error message</div>
</div>
<div class="col-12">
<input type="submit" value="Submit" class="primary" id="buttonSubmit" disabled/>
</div>
</form>

How to append and remove different appended divĀ“s using jquery/javascript?

I have built a form where you can add a person by clicking a button. Now, I want to add a new button to delete the latest added person. My current code only deletes one person, and after that, I can't add another person again. Do someone know what's wrong?
$(document).ready(function(){
$("#button1").click(function(){
$(".flex-container-name-adult").append($(".test1").html());
});
});
$(document).ready(function(){
$("#button3").click(function(){
$(".test1").remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="flex-container-name-adult">
<button id="button1">Add person</button>
<button id="button3">Delete person</button>
<div class="test1">
<div class="flex-wrapper-name-adult">
<span class="adult">Person</span><br>
<input type="text" class="input" placeholder="Name" name="name" required>
<input type="text" class="input" placeholder="Nachname" name="nachname" required>
<input type="date" class="input" placeholder="Geburtsdatum" name="geburtstag" required onfocus="(this.type='date')" onblur="(this.type='Geburtsdatum')">
</div>
</div>
</div>
When you click the add person button you are appending the html of test1 to the element with class flex-container-name-adult. That html don't include the div with test1 class itself. Now, when you click the delete person button you are deleting all the elements with the class test1. So, after that action, there will be no more elements with class test1 on the document that you can later use on the add person button.
I suggest to use .clone() for what you want to do, and to always delete the last added person. Something like this:
$(document).ready(function()
{
$("#button1").click(function()
{
// Clone the first ".test1" element and append it to the wrapper.
$(".flex-container-name-adult").append($(".test1").first().clone());
});
$("#button3").click(function()
{
// Delete last ".test1" element, if exists more than one.
let tests = $(".test1");
if (tests.length > 1)
tests.last().remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="flex-container-name-adult">
<button id="button1">Add person</button>
<button id="button3">Delete person</button>
<div class="test1">
<div class="flex-wrapper-name-adult">
<span class="adult">Person</span><br>
<input type="text" class="input" placeholder="Name" name="name" required>
<input type="text" class="input" placeholder="Nachname" name="nachname" required>
<input type="date" class="input" placeholder="Geburtsdatum" name="geburtstag" required onfocus="(this.type='date')" onblur="(this.type='Geburtsdatum')">
</div>
</div>
</div>

.show() doesn't work immediately - jQuery

I have a button click function like this :
$("#submitButton").click(function (e) {
e.preventDefault();
console.log("let's show my div");
$('#mydiv').show();
//and then doing a lot of front end operations and some ajax calls
})
When I click the submit button, I get the console.log message immediately. But .show() method works like 7-8 seconds after that. Can you tell me how I can make .show() work immediately? Thanks.
EDIT :
My HTML code looks like this :
<div class="main">
<form id="myform" enctype="multipart/form-data" class="contact-forms">
<div class="first-line">
<div class="span3 main-row">
<div class="input">
<input type="text" id="id" name="id" placeholder="insert your ID" maxlength="7" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" />
</div>
</div>
</div>
<div class="first-line">
<div class="span8 main-row">
<div class="input">
<input type="text" id="name" name="name" placeholder="Your name" />
</div>
</div>
</div>
<div id="mydiv" style="display:none">
<label>
Processing, please wait.
</label>
</div>
</form>
</div>
This is example of showing the div , you should hide your div with display none not hidden class , if you use hidden class just remove class to show your div
function ShowDiv(){
$("#mydiv").show();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv" style='display:none;'>Hello</div>
<button onclick="ShowDiv()"> ShowMe</button>

Onclick Cancel application event

new to js...need your help. I want to create a cancel button that cancels an online form session when the cancel button is clicked. Before cancelling the session, I want a notification popup to appear (onclick event) asking for the user's confirmation before cancelling the application session. See code below:
<form>
<div class="form-group">
<label for="Product">Product</label>
<input type="text" name="product" id="product" required="required" value="">
</div>
<div class="form-group">
<label for="Product">Product1</label>
<input type="text" name="product1" id="product1" required="required" value="">
</div>
<div class="form-group">
<label for="Product">Product2</label>
<input type="text" name="product2" id="product2" required="required" value="">
</div>
<div>
<button name="submit">Add Product</span></button> **Cancel**
</div>
</form>
First you need on click confirm function which will ask user approve before continue
**Cancel**
<script>
function confirmCancel () {
var message = "Are you sure?";
if (confirm(message)) {
// do what you want
}
}
</script>
<form id='form1'>
<div class="form-group">
<label for="Product">Product</label> <input type="text" name="product" id="product" required="required" value=""> </div>
<div class="form-group">
<label for="Product">Product1</label> <input type="text" name="product1" id="product1" required="required" value=""> </div>
<div class="form-group"> <label for="Product">Product2</label> <input type="text" name="product2" id="product2" required="required" value=""> </div>
<div>
<button name="submit">Add Product</span></button>
**Cancel** </div>
</form>
<script>
function(id){
if(confirm("do you want to cancel?")){
$("#"+id)[0].reset();
}
}
</script
>
Without editing the form select the element, attach an 'click' event listener to the element you want to listen in on, in this case, "cancel" a tag. Once the click is registered confirm using a confirm box. if Ok grab the form and reset it and redirect the user. Else, do something else.
// grab your cancel anchor tag
var anchor = document.querySelector("[href='http://www.google.com']");
// grab your form
var form = document.getElementsByTagName('form')[0];
// add an event listener on to your cancle anchor tag
anchor.addEventListener('click',clicked =>{
// assign your confirm to varable yes
var yes = confirm('are you sure you want to cancle');
if(yes===true){
// if they confirm their departure reset the form
form.reset();
//alert them of a successfull form reset and inform them of the reroute
alert('the form has been reset you are going to be rerouted to google');
// use location to reroute to a different domain
//window.location.href("http://www.google.com")
// or within the current domain using a relative path
// window.location.href = '../' one level up
// winsow.location.href = '/path' relative to a domain
}else{
alert('you decided to cancle');
// do nothing
}
});
<form>
<div class="form-group">
<label for="Product">Product</label>
<input type="text" name="product" id="product" required="required" value="">
</div>
<div class="form-group">
<label for="Product">Product1</label>
<input type="text" name="product1" id="product1" required="required" value="">
</div>
<div class="form-group">
<label for="Product">Product2</label>
<input type="text" name="product2" id="product2" required="required" value="">
</div>
<div>
<button name="submit">Add Product</span></button> **Cancel**
</div>
</form>

JavaScript: show password on hold

I have 2 inputs for passwords. Each input field has 'show' button, which shows password on holding that button.
<form name="resetting_form" method="post" action="">
<div class="form-group has-feedback">
<input type="password" id="password_first" required="required" placeholder="New Password" class="form-control">
<span class="show">show</span>
</div>
<div class="form-group has-feedback">
<input type="password" id="password_second" required="required" placeholder="Repeat Password" class="form-control">
<span class="show">show</span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
</form>
Here is what I have
$(".form-control").on("keyup",function(){
if ($(this).val())
$(".show").show();
else
$(".show").hide();
});
$(".show").mousedown(function(){
$(".form-control").attr('type','text');
}).mouseup(function(){
$(".form-control").attr('type','password');
}).mouseout(function(){
$(".form-control").attr('type','password');
});
Problem
When I click to 'show' button, both input fields are shown. How to make sure that only corresponding password is shown?
When you use $(".form-control"), jquery select all .form-control element. But you need to select target element using this variable in event function and use .prev() to select previous element.
$(".show").mousedown(function(){
$(this).prev().attr('type','text');
}).mouseup(function(){
$(this).prev().attr('type','password');
}).mouseout(function(){
$(this).prev().attr('type','password');
});
Just target the previous input instead of all inputs with the given class
$(".form-control").on("keyup", function() {
if ($(this).val())
$(this).next(".show").show();
else
$(this).next(".show").hide();
}).trigger('keyup');
$(".show").mousedown(function() {
$(this).prev(".form-control").prop('type', 'text');
}).mouseup(function() {
$(this).prev(".form-control").prop('type', 'password');
}).mouseout(function() {
$(this).prev(".form-control").prop('type', 'password');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="resetting_form" method="post" action="">
<div class="form-group has-feedback">
<input type="password" id="password_first" required="required" placeholder="New Password" class="form-control">
<span class="show">show</span>
</div>
<div class="form-group has-feedback">
<input type="password" id="password_second" required="required" placeholder="Repeat Password" class="form-control">
<span class="show">show</span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
</form>
In react We simply do with
We probably need to use the onMouseDown and onMouseUp, onMouseOut events
onMouseDown={handleShowPassword}
onMouseUp={handleShowPassword}
onMouseOut={handleShowPasswordHideOnMouseOut}

Categories