Unable to store form data into session storage - javascript

I just started to learn JavaScript and I was trying to let user input form data and store them into session storage but I can't seem to do so. Please shed some light on this, thank you.
JavaScript
$(function() {
$("formset").submit(function (event) {
event.preventDefault();
var name = $("#fullname").val();
var email = $("#email").val();
var phonenumber = $("#phonenumber").val();
var message = $("#message").val();
if (typeof (Storage) !== "undefined") {
sessionStorage.setItem("Fullname", name);
sessionStorage.setItem("E-mail", email);
sessionStorage.setItem("Phoneno", phonenumber);
sessionStorage.setItem("Msg", message);
}
});
});
HTML
<form id="formset" class="main_form">
<div class="row">
<div class="col-md-12 ">
<input class="contactus" placeholder="Full Name" type="text" id="fullname" required>
</div>
<div class="col-md-7">
<input class="contactus" placeholder="Email" type="tel" id="email" required>
</div>
<div class="col-md-7">
<input class="contactus" placeholder="Phone Number" type="text" id="phonenumber" required>
</div>
<div class="col-md-12">
<textarea class="contactus1" placeholder="Message" type="text" id="message" required></textarea>
</div>
<div class="col-md-12">
<button class="send_btn" type="submit" id="submitform">Send</button>
</div>
</div>
</form>

Alright, you made a very small typo in your form ID attribute that you try to call from Javascript.
If $ is not undefined in your browser inspector, you should be able to select the form by $('#formset') instead of $('formset'). Let me know if that worked. I got it working on my machine with that adjustment :-)
Another good practice to learn Javascript is to write
console.log("Script entered this <FUNCTION_NAME>");
So I solved your problem in three seconds by doing this:
$(function() {
console.log("Script finished jQuery initialization.")
$("formset").submit(function (event) {
console.log("Script entered submit event.");
event.preventDefault();
var name = $("#fullname").val();
var email = $("#email").val();
var phonenumber = $("#phonenumber").val();
var message = $("#message").val();
if (typeof (Storage) !== "undefined") {
sessionStorage.setItem("Fullname", name);
sessionStorage.setItem("E-mail", email);
sessionStorage.setItem("Phoneno", phonenumber);
sessionStorage.setItem("Msg", message);
}
});
});
With the option 'Preserve Log' on in your inspector, you see the actual submit message in the console. Else you would be redirected after the form sumbit action and your console gets cleared.
And that's how I easily discovered the mistake. I never got the "Script entered submit event." message.

Related

How can I disable the popup success message when the form is required to fill?

I am planning to display a Success message when clicked on the Submit button.
However, I would like to disable or hide the Success message whenever the form is required to fill.
So how can I do it by changing the code in script?
Please help me, I really appreciate your support!
This is my code:
<div class="contact-wrapper">
<main class="flex-container">
<section class="main-content">
<form class="contact-form" action="index.html" method="post" onsubmit="return false">
<input type="text" class="contact-form-text" placeholder="Name" id="name" required/>
<input type="email" class="contact-form-text" placeholder="Email" id="email" required/>
<input type="text" class="contact-form-text" placeholder="Title">
<textarea class="contact-form-text" placeholder="Type your message..."></textarea>
<button>Send</button>
<div class="alert">
<span class="message">Success: You Message Sent Successfully!</span>
</div>
</form>
</section>
<script>
function validateForm() {
var name = document.getElementById('name').value;
var name = document.getElementById('email').value;
}
$('button').click(function(){
$('.alert').addClass("show");
$('.alert').addClass("showAlert");
$('.alert').removeClass("hide");
setTimeout(function(){
$('.alert').addClass("hide");
$('.alert').removeClass("show");
},3000);
});
</script>
Consider hiding the message initially and display it only on successful submission
<div class="alert hide">
<span class="message">Success: You Message Sent Successfully!</span>
</div>
you should show the alert only if the form validation returns true.
function validateForm() {
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
if(name == '' || name == null || email == '' || email == null){
alert("Please Fill All Required Field");
return false;
}
return true;
}
$('button').click(function(){
if(validateForm()){
// your code for submission
// after successful submission display the alert message
$('.alert').removeClass("hide");
$('.alert').addClass("show");
$('.alert').addClass("showAlert");
}
});
I would suggest you to follow the standard format for form validation and form submission. link here

unable to get input value from <input>

I can't seem to get the input value for "name", I have tried using .value in JS but when I run the code I get undefined.
HTML code
<div class="col-1">
<label for="fname">Name</label>
</div>
<div class="col-2">
<input type="text" id="fname" placeholder="Enter name" required>
</div>
<div class="col-3">
<button onClick="gather()" id="submitButton">submit</button>
</div
JS code
var submit = document.getElementById("submitButton");
submit.addEventListener("click",gather);
function gather(){
name = document.getElementById("fname");
message = "Thank you for subscribing "+name.value+ "!";
alert(message);
}
Just use var for create variable and all work.
var submit = document.getElementById("submitButton");
submit.addEventListener("click",gather);
function gather(){
var name = document.getElementById("fname");
var message = "Thank you for subscribing "+name.value+ "!";
alert(message);
}
<div class="col-1">
<label for="fname">Name</label>
</div>
<div class="col-2">
<input type="text" id="fname" placeholder="Enter name" required>
</div>
<div class="col-3">
<button onClick="gather()" id="submitButton">submit</button>
</div>
I suggest you to see this post:
Is var necessary when declaring Javascript variables?
you can simply do .value in the same line and get the value of the element
name = document.getElementById("fname").value;
console.log(name)
You must put all your codes into window.onload. This method running your code when all elements in page loaded. And this will solve your problem.
window.onload = () => {
//some js codes
}

Validation form question bootstrap and javascript

thanks in advance for answering the question.
The goal in my form (as with many similar forms) is to check that
text field is not empty
password meets the criteria (to be honest, right now I would be happy with just anything in it)
email has text before "#", the "#" and text after "#".
depending on whether all checks are okay, to display an alert with the message.
bootstrap:
<form>
<div class="form-group">
<label for="exampleTextarea">Course/Lecturer feedback</label>
<textarea class="form-control" id="textArea" rows="3" placeholder="Please enter your feedback in this field. Your opinion matters and helps us to provide you with better serivce."></textarea>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Please enter your email address</label>
<input type="email" class="form-control" id="emailAddress" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Please enter your password</label>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary" onclick="submitData()">Submit</button>
</form>
javascript
//comment validation function
function textFieldValidate(textField){
var txtln = "";
if (txtln !=="")
return pattern.test(textField);
}
//email validation function
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
//password validation function
// at least one number, one lowercase and one uppercase letter
// at least six characters
function passwordValidate(password){
var pw = new RegExp (/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/);
return pw.test(password);
}
function submitData(){
//retrieve the values
if(textFieldValidate(textField) && isValidEmailAddress(emailAddress) && passwordValidate(password)){
//send post request
alert("Thank you for your feedback! We have sent this to KGB and you should expect a call any moment now...");
}else{
//display error message
alert("Unfortunately information that you have entered was incorrect, please check the info and and resubmit");
return;
}
}
what I get at the moment is that my page refreshes and nothing happens.
Alright, it looks like the issue was with the id in html which was called textArea and in function I called it textField.
Now... the other problem is that it doesn't really validate anything. Just the pop up appears...

Simple JQuery function will not execute after form submission

Simple JQuery function will not execute after form submission. I can see that my form values are sent but when function in reached, there is no execution. I've read several posts and removed the "submit" value from my button id and still JQuery will work. Any help direction would be greatly appreciated.
$(document).ready(function() {
//When the chat form is submitted
$("#chatform").submit(function(event) {
event.preventDefault();
//Take the values directly form the chat form//
var name = $("#uname").val();
var message = $("#message").val();
if (message != "" && name != "") {
$.post("clashofcolchatdata.php", {
message: message,
name: name
}, function(data) {
$("#chat_space").append(data);
});
} else {
alert("Data missing");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="chatform" action="">
<div id="chat_comform">
<!-- This is the blank space for the chat -->
<div id="chat_space">
</div>
<div id="chat_message">
<!--Name | Name of the user entering the message -->
<input type="text" placeholder=" Name" name="uname" id="uname" style="color:black" required/>
<br />
<!--Message | This is the chat message -->
<input type="text" placeholder=" Enter your chat message" name="message" id="message" style="color:black" required/>
<!-- This disables the button if anything on the is still invalid -->
<button type="submit" id="chat_submit" name="formsub" value="post" style="color:black">Submit</button>
</div>
</div>
</form>
change <form name="chatform">
to <form id="chatform">. You're querying by html id when you do $('#chatform') but you have not set an id on the form.

Unable to set cuctom html5 validation message

I am trying to use browser validation messaging. I am not able to define a custom message when 2 fields are NOT identical.
My situation is that i have to test when the field IS valid, so i used jquery on.blur to test, but for some reason, the message is empty.
Try entering 2 valid but different email addresses. The expected result is supposed to be "Test why not working" has a browser message.
Working jsFiddle of my situation
HTML:
<form id="newsletter_form" class="form" role="form" name="newsletter_form" method="post" action="/" autocomplete="off">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6">
<input type="email" class="form-control" name="email" id="email" value="" maxlength="250" placeholder="email" aria-required="true" required="required" />
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6">
<input type="email" class="form-control" name="confirm_email" id="confirm_email" value="" maxlength="250" placeholder="confirm email" aria-required="true" required="required" />
</div>
</div>
<input type="submit" class="btn submit btn-default" value="submmit!" />
</form>
JAVASCRIPT:
$('form #email').on('change invalid', function () {
var field = $(this).get(0);
field.setCustomValidity('');
if (!field.validity.valid) {
field.setCustomValidity("custom email invalid");
}
});
/* THIS IS MY BUGGY ONE */
$('form #confirm_email').on('blur valid', function () {
var field = $(this).get(0);
field.setCustomValidity('');
if ($("#email").val() != $("#confirm_email").val()) {
/* i tried setting the field to invalid, nothing */
//field.validity.invalid;
//alert('s');
field.setCustomValidity("test why not working");
}
});
$('form #confirm_email').on('change invalid', function () {
var field = $(this).get(0);
field.setCustomValidity('');
if (!field.validity.valid) {
field.setCustomValidity("custom error message");
}
});
I tried jquery.on(change valid .. and so on, i get the alert() bot not the changed text.
Any help will be appreciated, i am getting bored of this 'bug'?
but for some reason, the message is empty.
That is because you are explicitly setting it to be empty:
field.setCustomValidity('');
in your "custom error message" handler that is used to grump about the invalid email. That handler is executed after the 'blur valid', and will always reset what happened before. You can try it by uncommenting above line.
Any help will be appreciated
Check both reasons in the same handler:
$('form #confirm_email').on('change valid invalid', function () {
// var field = $(this).get(0); -- don't do this!!! field = this.
this.setCustomValidity('');
if (!this.validity.valid) {
this.setCustomValidity("custom message for standard errors");
} else if ($("#email").val() != this.value) {
this.setCustomValidity("test now working");
}
});
(updated demo)

Categories