Load the values twice into two input fields onload - javascript

I am using local storage to save the username in the first-page.html and retrieving it into the second-page.html
But if I have two or more places in my second-page.html where I want the username to be retrieved, how can I achieve it using two different ids. Since the id once used cannot be used in another input field.
Can anyone please help.
Index.html:
<script>
function save(){
var fieldValue = document.getElementById('user').value;
localStorage.setItem('text', fieldValue);
}
</script>
<div class="form-group" id="login-fields">
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"><span class="text--white glyphicon glyphicon-user"></span></i>
</span>
<input type="text" name="user" id="user" placeholder="Username" class="form-control" required/>
</div>
</div>
</div>
<input class="view sign-in-app" type="submit" value="Sign In" id="submit-login" onclick="save()" />
SecondPage.html
<script>
function load(){
var storedValue = localStorage.getItem('text');
if(storedValue){
document.getElementById('here').value = storedValue;
}
}
</script>
<body onload="load()">
<!-- first div -->
<div class="form-group">
<div class="cols-sm-10">
<div class="input-group">
<input type="text" name="userName" id="here" class="form-control" placeholder="Username" required>
</div>
</div>
</div>
<!-- second div -->
<div class="form-group">
<div class="cols-sm-10">
<div class="input-group"> // change the id here
<input type="text" name="userName" id="here" class="form-control" placeholder="Username" required>
</div>
</div>
</div>
</body>

Just give each element different ids, really. No problem with that. And then when you set, set both:
if (storedValue) {
document.getElementById('here').value = storedValue;
document.getElementById('my-other-id').value = storedValue;
}

Related

Unable to select form with querySelector

I'm trying to select a form element in javascript using the querySelector but it won't work and sometime it returns the form element.
Here's my code:
JavaScript
const ele = document.querySelector('form');
console.log(ele);
ele.addEventListener('submit', function(e) {
console.log("in the eventlister function");
const pass = document.getElementsByClassName("P")[0].value;
const cpass = document.getElementsByClassName("CP")[0].value;
const messagePara =document.getElementById("generated_message");
if(pass != cpass){
e.preventDefault();
messagePara.textContent ="check your password!!";
messagePara.style.color= 'red';
return false;
}
else{
messagePara.textContent ="";
}
});
HTML
<form class="inputF">
<div class="inputD">
<label for="fname" >Full Name</label>
<input type="text" id="fname" required>
</div>
<div class="inputD">
<label for="uname">Username</label>
<input type="text" id="uname">
</div>
<div class="inputD">
<label>Email address</label>
<input type="email" id="Email" placeholder="example#gmail.com" required >
</div>
<div class="inputD">
<label for="phn">Phone Number</label>
<input type="number" id="phn">
</div>
<div class="inputD">
<label for="pass">Password</label>
<div class="pass">
<input type="password" class="P IptP" required>
<i class="fa fa-eye-slash show-hide"></i>
</div>
</div>
<div class="inputD">
<label for="cpass">Confirm Password</label>
<div class="pass">
<input type="password" class="CP IptP" required>
<i class="fa fa-eye-slash show-hide"></i>
</div>
</div>
<div>
<button id="save_btn" >Continue</button>
</div>
</form>
I tried adding class for the form and select the form using the ClassName but still the same problem occurred. How can I fix this problem ?
When manipulating the DOM with a <script> in the <header>, you'll want to wait until the document has loaded.
document.body.addEventListener('load',function(){
// Your DOM sensitive code here
});
otherwise, you might want to include your script after the form tag
<!DOCTYPE html>
<html>
<!-- Your header; moving your script from here -->
<body>
<!-- Your form here -->
<!-- Move script here-->
<script>
// DOM sensitive code here as the last element in the body
</script>
</body>

checkValidity() not showing any html5 error notifications when fields are empty and posting with Ajax

I have a form that posts using Ajax, I also want to set an HTML5 required attribute on some input fields, but this stops working as expected with Ajax.
So I did the following:
$("body").on("click",".register-button",function(e){
e.preventDefault();
if($('#registerform')[0].checkValidity()){
registerform = $(".register-form").serialize();
$.ajax({
type:'post',
url:"includes/registreren.php",
data:({registerform: registerform}),
success:function(data){
var content = $( $.parseHTML(data) );
$( "#registerresult" ).empty().append( content );
}
});
}else{
}
});
This way the form is not posted when empty, but I also don't get any notifications that fields are empty like I would get when only using HTML to post.
I also tried logging the validity like so:
$("body").on("click",".register-button",function(e){
e.preventDefault();
$check = $('#registerform')[0].checkValidity();
console.log($check);
registerform = $(".register-form").serialize();
$.ajax({
type:'post',
url:"includes/registreren.php",
data:({registerform: registerform}),
success:function(data){
var content = $( $.parseHTML(data) );
$( "#registerresult" ).empty().append( content );
}
});
});
Which shows false in my console when empty. So the code works, why are the HTML5 notifications not shown? I remember doing something similar in the past and I didn't have to add any custom error messages then, it just worked.
This is my HTML markup:
<form id="registerform" class="register-form" method="post">
<div class="row">
<div class="col-md-6">
<input type="text" name="voornaam" placeholder="Voornaam" required>
</div>
<div class="col-md-6">
<input type="text" name="achternaam" placeholder="Achternaam" required>
</div>
<div class="col-md-12">
<input type="text" name="bedrijf" placeholder="Bedrijfsnaam (optioneel)">
</div>
<div class="col-md-6">
<input type="text" name="telefoon" placeholder="Telefoonnummer" required>
</div>
<div class="col-md-6">
<input type="text" name="email" placeholder="E-mail" required>
</div>
<div class="col-md-3">
<input type="text" name="huisnummer" id="billing_streetnumber" placeholder="Huisnummer" required>
</div>
<div class="col-md-3">
<input type="text" name="tussenvoegsel" placeholder="Tussenvoegsel" required>
</div>
<div class="col-md-6">
<input type="text" name="postcode" id="billing_postcode" placeholder="Postcode" required>
</div>
<div id="postcoderesult" class="col-lg-12">
<div class="row">
<div class="col-md-6">
<input type="text" name="straat" placeholder="Straatnaam" readonly required>
</div>
<div class="col-md-6">
<input type="text" name="woonplaats" placeholder="Woonplaats" readonly required>
</div>
</div>
</div>
<div class="col-md-6">
<input type="password" name="password" placeholder="Wachtwoord (minimaal 6 tekens)" required>
</div>
<div class="col-md-6">
<input type="password" name="confirmpassword"placeholder="Herhaal wachtwoord" required>
</div>
<div id="registerresult">
</div>
</div>
<button type="button" name="submit" class="register-button">Account aanmaken</button>
</form>
What am I missing?

jquery each method not working as expected

I am currently working on a website and this particular section requires the user to enter their details in a form. What I am trying to achieve is the following;
If the user hits the submit button and any fields are empty, I want a span element, which is initially set to CSS display none, to show up for each respective input field which has not been filled.
However, nothing seems to be happening when I click on the button. When I go to the console, it does not display any error message.
Can someone please assist? Many thanks.
HTML:
<!-- START OF 'YOUR DETAILS' FORM-->
<section>
<div class="container">
<h3>Step 3: Your Details</h3>
<!-- SLIDE-IN DIV TO REPRESENT DAY PASS -->
<div class="row chosenmembership">
<div class="col-md-12 text-center" id="yourdetails">
<form action="" method="">
<div class="form-group">
<label for="email">Email:</label>
<input type="email" placeholder="Email Address" id="email" class="form-control your-details">
<span class="warning"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
Email is required!</span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" id="name" class="form-control your-details">
<span class="warning"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
Name is required!</span>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="tel" placeholder="Contact Number" id="number" class="form-control your-details">
<span class="warning"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
Contact Number is required!</span>
</div>
<div class="form-group">
<label for="postcode">Post Code:</label>
<input type="text" placeholder="Post Code" id="postcode" class="form-control your-details">
<span class="warning"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
Post Code is required!</span>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="tel" placeholder="DD/MM/YYYY" id="dob" class="form-control your-details">
<span class="warning"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
DOB is required!</span>
</div>
</form>
<div class="form-group">
<input type="submit" id="submit" value="CONTINUE">
</div>
</div>
</div>
</div>
</section>
<!-- END OF YOUR DETAILS FORM -->
JS / JQUERY:
$("#submit").click(function(){
var $formValues = $(".your-details");
var $warning = $(".warnings");
$($formValues).each(function(index){
if ($(this).val("")){
$($warning[index]).css("display","block");
}
})
})
When your running this code $($formValues).each(function(index){if ($(this).val("")){ console.log(this) and see in which context your function is running, the issue is that every time you write a function declaration it creates a new this context and thus the previous this is lost.
Your selectors are kind of redundant, keep the form from submission and show the warnings when any are empty seems to be your intent.
$("#submit").click(function(e) {
$(".your-details").each(function(index) {
if ($(this).val() =="") {
e.preventDefault();// no submit if not filled out
$(this).next('.warning').css("display", "block");// next sibling show
}
});
});
Thought about this for a bit and believe you might handle the form submit instead
$("form").on('submit', function(e) {
$(this).find('.warning').css("display", "none");// hide in case they fix input values
$(this).find(".your-details").each(function(index) {
if ($(this).val() =="") {
$(this).next('.warning').css("display", "block");// next sibling show
}
});
});
Alternately you might use a filter.
$("form").on('submit', function(e) {
$(this).find('.warning').css("display", "none");// hide in case they fix input values
var emptyInputs = $(this).find(".your-details")
.filter(function() {
return ($(this).val() =="");
});
if(!!emptyInputs) {
e.preventDefault();
emptyInputs.next('.warning').css("display", "block");
}
});
Except typo, there was one problem more, you are actually setting value, instead of checking it: if ($(this).val("")) If you change it, and fix typo, something like this should work. Simplified, your code could look like this:
$("#submit").click(function(){
var $formValues = $(".your-details");
$($formValues).each(function(index){
if ($(this).val()==''){
$(".warning").eq(index).css("display","block");
}
else {
$(".warning").eq(index).css("display","none");
}
})
})
Demo:
$("#submit").click(function(){
var $formValues = $(".your-details");
$($formValues).each(function(index){
if ($(this).val()==''){
$(".warning").eq(index).css("display","block");
}
else {
$(".warning").eq(index).css("display","none");
}
})
})
.warning {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- START OF 'YOUR DETAILS' FORM-->
<section>
<div class="container">
<h3>Step 3: Your Details</h3>
<!-- SLIDE-IN DIV TO REPRESENT DAY PASS -->
<div class="row chosenmembership">
<div class="col-md-12 text-center" id="yourdetails">
<form action="" method="">
<div class="form-group">
<label for="email">Email:</label>
<input type="email" placeholder="Email Address" id="email" class="form-control your-details">
<span class="warning"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
Email is required!</span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" id="name" class="form-control your-details">
<span class="warning"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
Name is required!</span>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="tel" placeholder="Contact Number" id="number" class="form-control your-details">
<span class="warning"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
Contact Number is required!</span>
</div>
<div class="form-group">
<label for="postcode">Post Code:</label>
<input type="text" placeholder="Post Code" id="postcode" class="form-control your-details">
<span class="warning"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
Post Code is required!</span>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="tel" placeholder="DD/MM/YYYY" id="dob" class="form-control your-details">
<span class="warning"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
DOB is required!</span>
</div>
</form>
<div class="form-group">
<input type="submit" id="submit" value="CONTINUE">
</div>
</div>
</div>
</div>
</section>
<!-- END OF YOUR DETAILS FORM -->
P.S. You can keep your: $($warning[index]) vars, but you should hide warnings, anyway (else block), if field is not empty.

Multi forms datas into array via Javascript

I have some forms like this:
<div class="well">
<form>
<span class="remove pull-right"><i class="fa fa-times pointer"></i></span>
<div class="form-group" style="margin:0">
<label for="image-link">Image Link</label>
<input type="text" name="image-link" value="" class="form-control" >
</div>
<div class="form-group" style="margin:0">
<label for="content">Content</label>
<textarea class="form-control" name="content" rows="10"></textarea>
</div>
<div class="form-group" style="margin:0">
<label for="author">Author</label>
<input type="text" name="author" value="" class="form-control" >
</div>
</form>
</div>
....
<div class="well">
<form>
<span class="remove pull-right"><i class="fa fa-times pointer"></i></span>
<div class="form-group" style="margin:0">
<label for="image-link">Image Link</label>
<input type="text" name="image-link" value="" class="form-control" >
</div>
<div class="form-group" style="margin:0">
<label for="content">Content</label>
<textarea class="form-control" name="content" rows="10"></textarea>
</div>
<div class="form-group" style="margin:0">
<label for="author">Author</label>
<input type="text" name="author" value="" class="form-control" >
</div>
</form>
</div>
The forms will be added more and more when I click the add button, so will have multi forms.
I want to submit multi datas into an json arrayjust looks like this:
"quotes":[
{"image":"image_link","content":"content","author:"author"}
{"image":"image_link","content":"content","author:"author"}
...
{"image":"image_link","content":"content","author:"author"}
]
which is an array will contain all of the forms' datas. And the amount of forms is not fixed. It will be changed when I click add button.
So how can I do that automatically.
Thank you so much!
You can iterate through all the form elements on the page by calling the following function:
function generateArrayData() {
var forms = document.querySelectorAll(".well form");
var quotes = [];
for(var i = 0; i < forms.length; i++) {
var form = forms[i];
quotes.push({
image: form.querySelector("input[name='image-link']").value,
content: form.querySelector("textarea").value,
author: form.querySelector("input[name='author']").value
})
}
return quotes;
}
The way this works is that querySelectorAll loads all of the form elements on the page within a div with the class .well. We then iterate through the elements from the previous query and use querySelector to pull out each individual element we'd like to extract.

How to empty ajax loaded form?

How can we empty a ajax loaded form using pure JavaScript or jQuery.
I have tried document.forms[0].reset(); and $('#new-staff-form')[0].reset(); both didn't work it returns undefined.
Update
<div class="box col-md-12 new-staff">
<form id="new-staff-form" method="post">
<div class="row">
<div class="col-md-6">
<label for="f_name">First Name</label>
<input type="text" name="f_name" placeholder="First name"/>
</div>
<div class="col-md-6">
<label for="l_name">Last Name</label>
<input type="text" name="l_name" placeholder="Last name"/>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label for="user_name">User name</label>
<input id="user_name" type="text" name="user_name" placeholder="User name"/>
</div>
<div class="col-md-6">
<button id="user-avail" class="btn btn-primary">Check available</button>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button class="btn btn-primary pull-left">Save</button>
</div>
</div>
</form>
</div>
Javascript:
$('#new-item').click(function(){ // works fine until I load new html form using ajax with same ids and class
$('#new-staff-form')[0].reset();
$('.new-staff').slideToggle(); // show new form
});
$('.edit-item').click(function(){ // ajax call this loads everything correctly
var id = $(this).data('staf_id'); //item to delete
$.ajax({
url:url_view_staff+id,
type:'get'
}).done(function(data){
edit_item_id = id;
$('.new-staff').html(data).slideDown();
}).fail(function(data){
$('#errors').html(data.responseText);
$('.valid-error').slideDown();
});
});
JavaScript:
document.getElementById("myForm").reset();
Jquery :
$('#form_id')[0].reset();
Make sure your form id is valid.
FIDDLE
$('#configreset').click(function(){
$('#configform')[0].reset();
});

Categories

Resources