I would have 3 questions concerning the JQuery syntax:
1) The modal is not showing up. This may be an operator (&&) problem? How do I get it right? It should show up only if the thing is valid.
2) How to combine submit prevent Default with valid classes? I have used that before but never combined with JQuery. I want the modal only to show when is_email is valid and when the InputEmail, InputMessage and InputName fields were filled out.
$('#submit').click(function(submit){
if($('#InputEmail'&&'#InputMessage'&&'#InputName').val().length === 0)&& (is_email=="valid") {
$('#myModal').modal('show');
submit.preventDefault();
}
);
4) If I put the col-lg6, it will change size, however the documentation says that I have to add this:
$('.message-group').attr({
class: 'has-success'
works but if I add col-lg6 form-group name-group it will change the size. Why is this?
My syntax is:
/*JQUERY FORM EFFECTS*/
/*$('#InputName').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");}
}); Can I comment that out? */
$('#InputEmail').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");
}
});
/* Display please enter a name. */
$('#InputName').focusout(function(){
if($('#InputName').val().length === 0) {
$('.name-group .message-block').text('Please enter your name.');
$('.name-group').attr({
class: 'has-error'
}); // end attr
} else {
$('.name-group .message-block').text('');
$('.name-group').attr({
class: 'has-success'
}); //end attr
}
}); //end focus out
$('#InputMessage').focusout(function(){
if($('#InputMessage').val().length === 0) {
$('.message-group .message-block').text('Please enter your message.');
$('.message-group').attr({
class: 'has-error'
}); // end attr
} else {
$('.message-group .message-block').text('');
$('.message-group').attr({
class: 'has-success'
}); //end attr
}
}); //end focus out
$('#InputEmail').focusout(function(){
if($('#InputEmail').val().length === 0) {
$('.mail-group .email-block').text('Please enter your email.');
$('.mail-group').attr({
class: 'has-error'
}); // end attr
} else {
$('.mail-group .email-block').text('');
$('.mail-group').attr({
class: 'has-success'
}); //end attr
}
}); //end focus out
$('#submit').click(function(submit){
if($('#InputEmail'&&'#InputMessage'&&'#InputName').val().length === 0)&& (is_email=="valid") {
$('#myModal').modal('show');
submit.preventDefault();
}
);
My form:
<div class="form-group name-group">
<label for="InputName">Your Name</label>
<div class="input-group">
<input type="text" class="form-control" name="InputName" id="InputName" placeholder="Enter Name" required>
<span class="input-group-addon">
<i class="glyphicon glyphicon-ok form-control-feedback"></i>
</span>
</div>
<span class="text-block"></span>
</div>
<div class="form-group mail-group">
<label for="InputEmail">Your Email</label>
<div class="input-group">
<input type="email" class="form-control" id="InputEmail" name="InputEmail" placeholder="Enter Email" required>
<span class="input-group-addon">
<i class="glyphicon glyphicon-ok form-control-feedback"></i>
</span>
</div>
<span class="email-block"></span>
</div>
<div class="form-group message-group">
<label for="InputMessage">Message</label>
<div class="input-group"
>
<textarea name="InputMessage" id="InputMessage" class="form-control" rows="5" required></textarea>
<span class="input-group-addon"><i class="glyphicon glyphicon-ok form-control-feedback"></i></span>
</div>
<span class="message-block"></span>
</div>
<input type="submit" name="submit" id="submit" value="Submit" class="btn btn-info pull-right">
</div>
</form>
Can you show your markup for your div with the id of myModal?
Also, are you looking for a multiselect? If so here is a link to jQuery's documentation on including multiple element queries in a single selector call: http://api.jquery.com/multiple-selector/
Something more like:
if($('#InputEmail,#InputMessage,#InputName').val().length === 0)
{
alert('not filled out');
return false;
}
else return true;
Also, if that is a direct copy/paste, you are missing a closing parenthesis on your if statement:
if($('#InputEmail'&&'#InputMessage'&&'#InputName').val().length === 0)&& (is_email=="valid"))
Also, could you please clarify what you are asking in your bootstrap .css question?
Related
I am trying to do something like a verification on contact form, e.g if email does not contain "#" and "." show icon of red X and if the conditions are done show green check mark. I need answer on 2 questions: 1. How to align the icon next to the span and the 2. How to center the form in the middle of the screen? I tried with display:flex, many other floats, positions, aligns and every solution I found in the internet, but I anything had success in setting the icon between different tags and centering the form in the middle of the screen but the only one thing I came to is: link
< script type = "text/javascript" >
$(document).ready(function() {
$('.submit').click(function(event) {
console.log('Clicked button')
var name = $('.name').val()
var email = $('.email').val()
var phone = $('.phone').val()
var message = $('.message').val()
var statusElm = $('.status')
statusElm.empty()
if (email.length > 5 && email.includes('#') && email.includes('.')) {
statusElm.append('<i style="color: green; font-size:2.3em;" class="fas fa-check"></i>')
} else {
event.preventDefault()
statusElm.append('<i style="color: red; font-size:2.3em;" class="fas fa-times"></i>')
}
if (phone.length > 7 && phone.legth < 14) {
statusElm.append('<i style="color: green; font-size:2.3em;" class="fas fa-check"></i>')
} else {
event.preventDefault()
statusElm.append('<i style="color: red; font-size:2.3em;" class="fas fa-times"></i>')
}
if (message.length > 20) {
statusElm.append('<i style="color: green; font-size:2.3em;" class="fas fa-check"></i>')
} else {
event.preventDefault()
statusElm.append('<i style="color: red; font-size:2.3em;" class="fas fa-times"></i>')
}
})
}) <
/script>
<div class="mail " id="mail">
<div class="container">
<h3 class="w3l_head w3l_head1">Contact Me</h3>
<p class="w3ls_head_para w3ls_head_para1">send Me a message</p>
<div class="w3_mail_grids">
<form action="https://formspree.io/ntodorov301#gmail.com" method="POST" class="justify-content-center">
<div class="col-md-6 w3_agile_mail_grid">
<span class="input input--ichiro"><input
class="input__field input__field--ichiro" type="text" name="name"
id="input-25" placeholder=" " >
<label class="input__label input__label--ichiro" for="input-25">
<span class="input__label-content input__label-content--ichiro">Your
Name</span>
</label>
</span>
<a class="status" name="status"></a> <span class="input input--ichiro"> <input
class="input__field input__field--ichiro email" type="email" name="Email"
id="input-26" placeholder=" " > <label
class="input__label input__label--ichiro" for="input-26">
<span class="input__label-content input__label-content--ichiro">Your
Email</span>
</label>
</span> <span class="input input--ichiro"> <input
class="input__field input__field--ichiro phone" type="text" name="phone"
id="input-27" placeholder=" " > <label
class="input__label input__label--ichiro" for="input-27">
<span class="input__label-content input__label-content--ichiro">Your
Phone Number</span>
</label>
</span>
</div>
<div class="col-md-6 w3_agile_mail_grid">
<textarea class="message" name="message" placeholder="Your Message"></textarea>
<input type="submit" value="Submit" class="submit">
</div>
<div class="clearfix"></div>
</form>
</div>
</div>
</div>
The Bootstrap is alredy used on the page. Thus, I recommend you to apply validation feature of the framework instead of creation of custom CSS rules. You could use .is-valid and .is-invalid styles for the controls or constraint validation API within custom validation methods.
The following example will help you to get started. I don't want to post too much code, therefore my form contains a single control.
document.getElementById('emailField')
.addEventListener('input', function(e) {
this.classList.remove('is-valid', 'is-invalid')
if (!isValidEmail(this.value))
this.classList.add('is-invalid');
else
this.classList.add('is-valid');
}, false);
document.getElementById('myForm')
.addEventListener('submit', function(e) {
checkEmail(document.getElementById('emailField'));
if (!this.checkValidity()) {
event.preventDefault();
event.stopPropagation();
}
this.classList.add('was-validated');
}, false);
function checkEmail(control) {
if (!isValidEmail(control.value)) {
control.setCustomValidity('The e-mail is invalid.');
console.log(control.validationMessage);
} else {
control.setCustomValidity('');
}
}
function isValidEmail(email) {
return /^[\w!#$%&'*+-\/=\?^_`{|}~](\.?[\w!#$%&'*+-\/=\?^_`{|}~])*#gmail\.com$/i.test(email);
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="container">
<form id="myForm" novalidate>
<div class="form-group">
<label for="emailField">Email address</label>
<input type="email" class="form-control" id="emailField" aria-describedby="emailHelp" placeholder="Enter email">
<small class="valid-feedback">The e-mail address is valid!</small>
<small class="invalid-feedback">The e-mail address is invalid.</small>
<small id="emailHelp" class="form-text text-muted">Only Gmail is supported</small>
</div>
<button class="btn btn-primary" type="submit">Send</button>
</form>
</div>
The snippet uses .is-invalid and .is-valid classes to indicate validation result while user is inputing e-mail address. In the submit event handler the constraint validation API is used. The forms allows to send only address of Gmail. If you will try to use another domain it throws an error.
$(function() {
if (localStorage.chkbx && localStorage.chkbx != '') {
$('#modal_login_remember').attr('checked', 'checked');
$('#modal_login_email').val(localStorage.usrname);
$('#modal_login_password').val(localStorage.pass);
} else {
$('#modal_login_remember').removeAttr('checked');
$('#modal_login_email').val('');
$('#modal_login_password').val('');
}
$('#modal_login_remember').click(function() {
if ($('#modal_login_remember').is(':checked')) {
// save username and password
localStorage.usrname = $('#modal_login_email').val();
localStorage.pass = $('#modal_login_password').val();
localStorage.chkbx = $('#modal_login_remember').val();
} else {
localStorage.usrname = '';
localStorage.pass = '';
localStorage.chkbx = '';
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<p style="text-align: center"><i>Enter your email ID and password to log in to Help.</i></p>
<div id="errormsg" style="display: none; color:red;text-align: center; padding-bottom: 1.2rem;"> Invalid token or login credentials, please log in again.</div>
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-envelope"></i>
</span>
<input type="email" id="modal_login_email" name="modal_login_email" class="form-control" placeholder="Enter email" />
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-unlock-alt"></i>
</span>
<input type="password" id="modal_login_password" name="modal_login_password" class="form-control" placeholder="Password" />
</div>
</div>
<label class="custom-control custom-checkbox">
<input type="checkbox" id="modal_login_remember" class="custom-control-input" />
<span class="custom-control-indicator"></span>
<span class="custom-control-description">Remember me</span>
</label>
<div class="modal-footer">
<input type="button" onclick="login(document.getElementById('modal_login_email').value,document.getElementById('modal_login_password').value);" class="btn btn-primary" value="Login" style="background-color: #19659d; border-color: #19659d;" />
</div>
If a user click on remember checkbox at the time of login, the details should to be saved in localstorage. If user tries to login again user details should autocomplete (if user types few letter of his name, name and password should autocomplete). There is no api for it, so i need to do it from front-end.
The value are getting stored in localstorage but the autocomplete is not working ho to approach it.
You can use this code, and you can define the local storage as an object it's would be nic to have.
$(function() {
if (localStorage.chkbx && localStorage.getItem(chkbx) !=='') {
$('#modal_login_remember').attr('checked', 'checked');
$('#modal_login_email').val(localStorage.getItem(usrname));
$('#modal_login_password').val(localStorage.getItem(pass));
} else {
$('#modal_login_remember').removeAttr('checked');
$('#modal_login_email').val('');
$('#modal_login_password').val('');
}
$('#modal_login_remember').click(function() {
if ($('#modal_login_remember').is(':checked')) {
// save username and password
localStorage.setItem('usrname',$('#modal_login_email').val());
localStorage.setItem('pass',$('#modal_login_password').val());
localStorage.setItem('chkbx', $('#modal_login_remember').val());
} else {
localStorage.setItem('usrname', '');
localStorage.setItem('pass', '');
localStorage.setItem('chkbx', '');
}
});
});
I have a 'contact us' form on our website, people fill out name, email, and message and hit send. Currently the form won't submit if I have the email validation in my code.
Here is HTML form code:
<form role="form" id="feedbackForm">
<div class="form-group">
<label class="control-label" for="name">Full Name *</label>
<div class="input-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Your Name" required/>
<span class="input-group-addon"><i class="glyphicon glyphicon-unchecked form-control-feedback"></i></span>
</div>
<span class="help-block" style="display: none;">Please enter your name.</span>
</div>
<div class="form-group">
<label class="control-label" for="email">Email Address *</label>
<div class="input-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Enter Your Email" required/>
<span class="input-group-addon"><i class="glyphicon glyphicon-unchecked form-control-feedback"></i></span>
</div>
<span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>
</div>
<div class="form-group">
<label class="control-label" for="reason">Contact Reason *</label>
<select name="reason" class="form-control" required>
<option value="General Inquiry">General Inquiry</option>
<option value="Schedule Appointment">Schedule Appointment</option>
<option value="Report Issue">Report Issue</option>
<option value="Provide Feedback">Provide Feedback</option>
</select>
</div>
<div class="form-group">
<label class="control-label" for="message">Message *</label>
<div class="input-group">
<textarea rows="5" class="form-control" id="message" name="message" placeholder="Enter Your Message" required></textarea>
<span class="input-group-addon"><i class="glyphicon glyphicon-unchecked form-control-feedback"></i></span>
</div>
<span class="help-block" style="display: none;">Please enter a message.</span>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="mykey"></div>
<span class="help-block" style="display: none;">Please check that you are not a robot.</span>
<button type="submit" id="feedbackSubmit" class="btn btn-success btn-lg" data-loading-text="Sending..." style="display: block; margin-top: 10px;">Send Feedback
</button>
</div>
</form>
and here's the jquery code:
(function () {
//using regular expressions, validate email
var contactFormUtils = {
isValidEmail: function (email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
},
//if no form errors, remove or hide error messages
clearErrors: function () {
$('#emailAlert').remove();
$('#feedbackForm .help-block').hide();
$('#feedbackForm .form-group').removeClass('has-error');
},
//upon form clear remove the checked class and replace with unchecked class. Also reset Google ReCaptcha
clearForm: function () {
$('#feedbackForm .glyphicon').removeClass('glyphicon-check').addClass('glyphicon-unchecked').css({color: ''});
$('#feedbackForm input,textarea').val("");
grecaptcha.reset();
},
//when error, show error messages and track that error exists
addError: function ($input) {
var parentFormGroup = $input.parents('.form-group');
parentFormGroup.children('.help-block').show();
parentFormGroup.addClass('has-error');
},
addAjaxMessage: function(msg, isError) {
$("#feedbackSubmit").after('<div id="emailAlert" class="alert alert-' + (isError ? 'danger' : 'success') + '" style="margin-top: 5px;">' + $('<div/>').text(msg).html() + '</div>');
}
};
$(document).ready(function() {
$("#feedbackSubmit").click(function() {
var $btn = $(this);
$btn.button('loading');
contactFormUtils.clearErrors();
//do a little client-side validation -- check that each field has a value and e-mail field is in proper format
//use bootstrap validator (https://github.com/1000hz/bootstrap-validator) if provided, otherwise a bit of custom validation
var $form = $("#feedbackForm"),
hasErrors = false;
if ($form.validator) {
hasErrors = $form.validator('validate').hasErrors;
} else {
$('#feedbackForm input,#feedbackForm textarea').not('.optional').each(function() {
var $this = $(this);
if (($this.is(':checkbox') && !$this.is(':checked')) || !$this.val()) {
hasErrors = true;
contactFormUtils.addError($(this));
}
});
var $email = $('#email');
if (!contactFormUtils.isValidEmail($email.val())) {
hasErrors = true;
contactFormUtils.addError($email);
}
}
//if there are any errors return without sending e-mail
if (hasErrors) {
$btn.button('reset');
return false;
}
//send the feedback e-mail
$.ajax({
type: "POST",
url: "php/sendmail.php",
data: $form.serialize(),
success: function(data) {
contactFormUtils.addAjaxMessage(data.message, false);
contactFormUtils.clearForm();
},
error: function(response) {
contactFormUtils.addAjaxMessage(response.responseJSON.message, true);
},
complete: function() {
$btn.button('reset');
}
});
return false;
});
$('#feedbackForm input, #feedbackForm textarea').change(function () {
var checkBox = $(this).siblings('span.input-group-addon').children('.glyphicon');
if ($(this).val()) {
checkBox.removeClass('glyphicon-unchecked').addClass('glyphicon-check').css({color: 'green'});
} else {
checkBox.removeClass('glyphicon-check').addClass('glyphicon-unchecked').css({color: ''});
}
});
});
})();
When I remove this bit of code that validates if the email is in correct format then the form sends to my email right away.
var $email = $('#email');
if (!contactFormUtils.isValidEmail($email.val())) {
hasErrors = true;
contactFormUtils.addError($email);
}
Which in turn leads to this bit, I believe :
if (hasErrors) {
$btn.button('reset');
return false;
}
if I comment out 'return false;' then it sends the form
I can't find what part of the email validation prevents the form from submitting?
Maybe you have another element with id="email" somewhere.
Maybe try:
$('#feedbackForm input[type=email]').each(function() {
if (!contactFormUtils.isValidEmail(this.val())) {
hasErrors = true;
contactFormUtils.addError(this);
console.log("ERROR: Invalid email: "+this.val()+" in input "+this.attr("name"));
}
})
Regarding to this answer my following code should work:
<form data-toggle="validator">
<div class="form-group has-feedback">
<label for="exampleInputText">Name</label>
<input type="text" class="form-control" id="exampleInputText" placeholder="text" data-odd>
<span class="glyphicon form-control-feedback" aria-hidden="true"></span>
<div class="help-block with-errors"></div>
</form>
<script type="text/javascript">
$('form').validator({
custom: {
'odd': function($el) { return false }
},
errors: {
'odd': 'error message'
}
})
</script>
But it does not work - why?
You should remove
data-toggle="validator"
from the form tag, and update the input with id exampleInputText as follows (i.e. adding ="odd" to data-odd):
data-odd="odd"
Example here: https://jsfiddle.net/mdt86/9r06waph/10/
I do need to create a form. In that form I need to enable form element one by one. That mean, If an user entered valid data to first element then I want to autofocus next element and so on.
NOTE: When page is load I want to keep all the elements disable except first element.
This is HTML of my form.
<form role="form" class="banner" method="post" action="">
<div class="form-group">
<div class="icon-addon addon-md">
<input type="text" name="name" placeholder="Your Name" class="form-control first-name sequence" autocomplete="off" required>
<label for="name" class="glyphicon glyphicon-user" data-toggle="tooltip" data-placement="left" title="Enter Your Name"></label>
</div>
</div>
<div class="form-group">
<div class="icon-addon addon-md">
<input type="email" name="email" placeholder="Your Email" class="form-control email_address sequence" autocomplete="off" disabled required>
<label for="email" class="glyphicon glyphicon-envelope" rel="tooltip" title="Enter Your Email"></label>
<span class="email-error"></span>
</div>
</div>
<div class="form-group">
<div class="icon-addon addon-md">
<input type="text" name="phone" placeholder="Your Phone Number Eg: xx-xxx-xxx" class="form-control phone-number sequence" autocomplete="off" disabled required>
<label for="email" class="glyphicon glyphicon-phone" rel="tooltip" title="Enter Your Phone Number"></label>
</div>
</div>
<div class="element-left">
<div class="form-group">
<div class="icon-addon addon-md">
<input type="text" name="charter-date" placeholder="Pick Up Date" class="form-control datepicker sequence" autocomplete="off">
<label for="date" class="glyphicon glyphicon-calendar" rel="tooltip" title="Prefered Charter Date"></label>
</div>
</div>
</div>
<div class="element-right">
<div class="form-group">
<div class="icon-addon addon-md">
<input type="text" name="charter-time" placeholder="Pick Up Time" class="form-control timepicker sequence" autocomplete="off">
<label for="time" class="glyphicon glyphicon-time" rel="tooltip" title="Time of Charter"></label>
</div>
</div>
</div>
<p class="form-actions">
<button type="submit" name="submit" class="btn btn-default btn-block">
<span class="btn-orange-inner">Send</span>
</button>
</p>
</form>
This is how I tried it in jQuery:
// form validation
function fakeValidator(event) {
var flag = false;
var $element = $(event.target);
var values = $element.val();
if (values.length >= 3) {
if($element.hasClass('email_address')) {
if(validemail(values)){
flag = true ;
}else{
flag =false;
}
}
flag =true;
} else {
flag =false;
}
if(flag){
//alert('hi');
$element.addClass('valid');
enableNextElement(event);
} else{
alert('hi el');
$element.removeClass('valid');
//$element.addAttr('disabled');
}
}
function validemail(value){
var emailReg ="/^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/";
}
function enableNextElement(event) {
var $element = $(event.target);
if ($element.hasClass('valid')) {
$element.closest('.form-group')
.next('.form-group')
.find('.sequence')
.removeAttr('disabled');
}
}
$('.sequence').on('blur keyup', fakeValidator);
But my problem is, if I entered an invalid email next element is enabling. But I want to enable next element if its a valid email in email field.
Can anybody tell me what is wrong with this?
Thank you.
2 things:
You should return true or false from your email validation function i.e. validemail
Your regex is stored as string, and hence you cannot apply test function on it. Remove wrapping it in " "
Above mentioned changes will give you desired result.
function validemail(value){
var emailReg =/^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; //regex
return emailReg.test(value); //use test which returns true or false
}
UPDATE
DEMO
It will still enable the phonenumber because you have validation written in such a way.
Your Validation:
if (values.length >= 3) {
//this is ok for name
if($element.hasClass('email_address')) {
if(validemail(values)){
flag = true;
}else{
flag =false;//even though flag is false here
}
}
flag =true; //when it comes to this line it again makes it to true
//and for email along with length>3, valid email address has also to be validated
} else {
flag =false;
}
My workaround
if (values.length >= 3) {
flag =true; //set this first
if($element.hasClass('email_address')) {//then perform other validations
if(validemail(values)){
flag = true ;
}else{
flag =false;
}
}
} else {
flag =false;
}