JavaScript - Bootstrap Validator - javascript

I am using this plugin: Plugin Link
I am trying to validate, if at least one checkbox out of a checkbox group has been selected. The plugin doesn't support such a functionality. Therefore i googled, and found this, by the plugin author himself: Discussion Link and a working implementation here: Example
I tried implementing it and failed. This is what i have so far:
<div class="col-lg-9">
<?php
// Input form for choosing complaints
foreach (Complaints::getComplaints() as $complaint) {
?>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]"
data-error="Try selecting at least one...">
<?= Helper::sanitize($complaint->getName()) ?>
</label>
<div class="help-block with-errors"></div>
</div>
</div>
<?php
}
?>
</div>
Plus this is the copied JS Function, that should do the magic...:
<script>
$('[data-toggle="validator"]').validator({
custom: {
chkgrp: function ($el) {
console.log("Some debug output, if it is triggered at all" + $el);
var name = $el.data("chkgrp");
var $checkboxes = $el.closest("form").find('input[name="' + name + '"]');
return $checkboxes.is(":checked");
}
},
errors: {
chkgrp: "Choose atleast one!"
}
}).on("change.bs.validator", "[data-chkgrp]", function (e) {
var $el = $(e.target);
console.log("Does is even work? " + $el);
var name = $el.data("chkgrp");
var $checkboxes = $el.closest("form").find('input[name="' + name + '"]');
$checkboxes.not(":checked").trigger("input");
});
So yeeh. Nothing happens, if i try to run this. None of my debug output is printed in the console. Nothing. The form itself also consists out of some password fields and text fields, the checkbox group - generated in the foreach loop - is just one part of it. The validator works for the text and password fields, but does exactly nothing for the checkbox group. Any ideas?
Thanks! :)

I just tried to make it neat.
please checkout the solution:
Reference: http://1000hz.github.io/bootstrap-validator/
$('#form').validator().on('submit', function (e) {
var validate = false;
$("input[type='checkbox']").each(function(index,e){
if($(e).is(':checked'))
validate = true;
});
if(validate){
//valid
$('.with-errors').html(' ');
} else {
$('.with-errors').html('not valid');
}
//if (e.isDefaultPrevented()) {
// handle the invalid form...
//} else {
// everything looks good!
//}
})
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="http://1000hz.github.io/bootstrap-validator/dist/validator.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form role="form" data-toggle="validator" id="form" action="" method="POST">
<div class="col-lg-9">
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]" data-error="Try selecting at least one...">
Teste1
</label>
<div class="help-block "></div>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]" data-error="Try selecting at least one...">
Teste2
</label>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]" data-error="Try selecting at least one...">
Teste3
</label>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<button type="submit" >Validade</button>
</form>

Related

Submit form not working when using jQuery

I have a form and when the user clicks submit, I would like the form to hide and a thank you message to appear. Unfortunately with the code I have, it's not working and I can't figure out why. I think it might be something with the jQuery so I'd like to try and re-write this function using vanilla JS, but I'm not sure how.
It is the last part of the function, the if (empty.length), hide form, show thank you message that is causing me problems. Everything else is working fine, so its this function I would like to try and write in JavaScript, or try another way using jquery to make it work. The problem is it doesn't work in my code, but when I open this in a jsfiddle, it doesnt just hide the form it opens a new page and I get an error. I don't want the user to be directed to a new page, I just want the form to close and thank-you message to appear. I am very new to this so I apologize if my code is messy.
UPDATE: I really think the issue here is the jQuery, can I write this in plain JS and would that fix it?
var $subscribe = $('#click-subscribe');
var $subscribeContent = $('#subscribe-content');
var $subscribeClose = $('#subscription-close');
$subscribeContent.hide();
$subscribe.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
$subscribeClose.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
})
var $form = $('#signup-form'),
$signupForm = $('.form-show'),
$formReplace = $('#thank-you');
$formReplace.hide();
$form.on('submit', function() {
var empty = $(this).find("input, select, textarea").filter(function() {
return this.value === "";
});
if (empty.length <= 0) {
$signupForm.hide();
$formReplace.show();
} else {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click-subscribe">Show / hide form</button>
<div id="subscribe-content">
<div class="subscription-signup">
<div class="subscription-close" id="subscription-close"></div>
<div class="email-signup">
<p class="cat-title subscription-text">lorem ipsum</p>
<p class="subscription-text">lorem ipsum</p>
<p class="subscription-text">lorem ipsum</p>
<div class="subscription-form">
<form id="signup-form" class="form-show" name="signup-form" method="post" action="${URLUtils.url('Newsletter-SubscribeMobile')}">
<div class="form-row salutation header">
<label for="salutation">Title</label>
<div class="chzn-row valid salutation">
<select id="title" name="title" class="chzn-global-select input-select optional required">
<option value="">--</option>
<option value="Mr">Mr.</option>
<option value="Mrs">Mrs.</option>
<option value="Ms">Ms.</option>
<option value="Miss">Miss</option>
</select>
</div>
</div>
<div class="form-row required">
<label for="firstname">
<span aria-required="true">First Name</span>
<span class="required-indicator">*</span>
</label>
<input class="input-text required" id="firstname" type="text" name="firstname" value="" maxlength="500" autocomplete="off">
</div>
<div class="form-row required">
<label for="lastname">
<span aria-required="true">Surname</span>
<span class="required-indicator">*</span>
</label>
<input class="input-text required" id="lastname" type="text" name="lastname" value="" maxlength="500" autocomplete="off">
</div>
<div class="form-row required">
<label for="signup-email" style="display:none;">Email</label>
<input class="header-signup-email" type="text" id="signup-email-header" name="signup-email" value="" placeholder="Email" />
</div>
<div class="form-row text-center">
<input type="submit" name="signup-submit" id="signup-submit" class="subscribe-submit" value="Submit" />
</div>
</form>
<div id="thank-you">
<p>Thanks for subscribing!</p>
</div>
</div>
</div>
</div>
</div>
I think some other javascript/jQuery code are making issues to run the codes, for simple solution make your code as plugin and called it like following.
create new js file called validation.js
(function($){
$.fn.validation = function(){
var $subscribe = $('#click-subscribe');
var $subscribeContent = $('#subscribe-content');
var $subscribeClose = $('#subscription-close');
$subscribeContent.hide();
$subscribe.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
$subscribeClose.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
var $form = $('#signup-form'), $signupForm = $('.form-show'), $formReplace = $('#thank-you'); $formReplace.hide();
this.on('submit', function(e){
var empty = $(this).find("input, select, textarea").filter(function() {
return this.value === "";
});
if(empty.length == 0){
$signupForm.hide();
$formReplace.show();
}
e.preventDefault();
});
};
})(jQuery);
Now, call the validation.js at the head like below
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="validation.js"></script>
<script type="text/javascript">
$(function(){
$('#signup-form').validation();
});
</script>

submit a form and prevent from refreshing it

i'm working on a email sending function on a project. here when i fill the form and after sending it the web site page getting refresh and showing white background page. i need to prevent that from the refreshing and submit the form. here i'l attach the codes and can someone tell me the answer for this question.
HTML code for form
<form class="form-vertical" onsubmit="return sendEmail();" id="tell_a_friend_form" method="post" action="index.php?route=product/product/tellaFriendEmail" enctype="multipart/form-data">
<div class="form-group ">
<label class="control-label ">Your Name <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="senders_name" name="sender_name" value="" class="form-control input-lg required" >
</div>
</div>
<div id="notify2" class="">
<div id="notification-text2" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label ">Your Email <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="sender_email_ID" name="sender_email" value="" class="form-control input-lg" >
</div>
</div>
<div id="notify1" class="">
<div id="notification-text1" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label">Your Friends' Email <span >* </span></label>
<p class="lineStyle">Enter one or more email addresses, separated by a comma.</p>
<div class="form-group-default">
<input type="text" value="" id="receiver_email" class="form-control required" name="receivers_email" >
</div>
</div>
<div id="notify" class="">
<div id="notification-text" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div >
<label domainsclass="control-label ">Add a personal message below (Optional) <br></label>
<div class="form-group-default">
<textarea type="text" id="tell_a_friend_message" name="tell_a_friend_message" class="form-control" rows="10" col="100" style=" width: 330px; height: 100px;"></textarea>
</div>
</div>
<div id="notify3" class="">
<div id="notification-text3" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<input type="hidden" name="product_url" id="product_url_field" value="">
<div class="p-t-15 p-b-20 pull-right">
<button id="send_mail_button" class="btn btn-rounded btn-rounded-fl-gold text-uppercase" name="submit" onclick="return sendEmail();" >Send</button>
<button id="cancel_email_form" class="btn btn-rounded btn-rounded-gold text-uppercase btn-margin-left" data-dismiss="modal" aria-hidden="true" >Cancel</button>
</div>
javascript code:
<script>
function sendEmail() {
document.getElementById('product_url_field').value = window.location.href
var emailpattern = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var receivers_email = $("#receiver_email").val();
var sender_email = $("#sender_email_ID").val();
var sender_name = $("#senders_name").val();
var email_pathname = window.location.pathname;
var product_url = window.location.href;
if (receivers_email == '') {
$('#notify').removeClass().addClass("alert-danger");
$('#notification-text').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text').show();
setTimeout(function() {
$('#notification-text').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(receivers_email);
}
if(sender_name == ''){
$('#notify2').removeClass().addClass("alert-danger");
$('#notification-text2').empty().html("please fill the name");
$('#notification-text2').show();
setTimeout(function() {
$('#notification-text2').fadeOut('slow');
}, 10000);
return false;
}
if (sender_email == '') {
$('#notify1').removeClass().addClass("alert-danger");
$('#notification-text1').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text1').show();
setTimeout(function() {
$('#notification-text1').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(sender_email);
}
$('#notify3').removeClass().addClass("alert-success");
$('#sender_email').val('');
$('#notification-text3').empty().html("Email has sent successfully");
$('#notification-text3').show();
setTimeout(function() {
$('#notification-text3').fadeOut('slow');
}, 10000);
return true;
}
</script>
Controller php class:
public function tellaFriendEmail(){
if (isset($_POST['submit'])) {
$receiver_email = $_POST['receivers_email'];
$name = $_POST['sender_name'];
$email = $_POST['sender_email'];
$message = $_POST['tell_a_friend_message'];
$products_url = $_POST['product_url'];
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
$mail->setTo($receiver_email);
$mail->setFrom($this->config->get('config_email'));
$mail->setSender("Waltersbay");
$mail->setSubject($name.' '.'wants you to checkout this product from waltersbay.com');
if ($message !=''){
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'.'<br/> Thank you, <br/> ');
}
else{
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'/*.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'*/.'<br/> Thank you, <br/> ');
}
$mail->send();
}
else{
header('location : tella_friend.tpl');
}
}
}
Put a hidden input in your form. before submitting in your js, fill it with a new key according to time.
in your php file check if key is duplicate or not? or even if its filled?
Because js fill this input after clicking the submit button, every time you submit your form you have a new key! If you refresh the form, you're gonna send the previous value again.
For your problem then best practice recommended is to use jquery ajax requests.
Firstly if you pretend to use "submit" element then do following,
$(".form-vertical").submit(function(e) {
e.preventDefault();
//send ajax with your form data. Ample examples on SO already.
$.ajax(.....);
});
Other option we would recommend is to avoid using 'submit' behavior at first place for requirement you have.
1. Use button elements instead of submit element.
2. Attach click event on button. i.e. in your case 'send'.
3. On click, send ajax as described above. This will avoid doing things like onsubmit="return sendEmail();" you had to do.
4. Also following is not required as well,
$(".form-vertical").submit(function(e) {
e.preventDefault();
as it will be done as follows,
$("button#buttonId").click(function(e) {
// your ajax call.....
}

Issue in jquery validator popup message

I want to create some popup that will tell user when he doesn't enter name, lastname, number or email.
HTML :
<div class="form-group">
<label class="label-block" for="cname" data-new-placeholder="What is your name?">Ime</label>
<input name="firstName" minlength="3" type="text" required class="texbox">
</div>
<div class="form-group">
<label class="label-block" for="cemail">Email</label>
<input name="ctct" type="email" required="required" required class="texbox">
</div>
</div>
<div class=" col-md-6">
<div class="form-group">
<label class="label-block">Prezime</label>
<input name="lastName" type="text" required class="texbox">
</div>
<div class="form-group">
<label class="label-block">Telefon</label>
<input name="number" type="digits" required class="texbox">
</div>
</div>
JS :
<script src="scripts/jquery.validationEngine-en.js" type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function () {
$("#configuration-form").validate({
messages: {
name: {
required: "Error!"
}
}
});
});
</script>
<script>
$("#commentForm").validate();
</script>
That is my code in html and css... I managed to make my textbox turns red when the email is not ok. how to create that popup text.
It looks like you are using Twitter Bootstrap, and they have a popover feature or alert message that you can use: Bootstrap - popovers
HTML :-
Validation for Email.
<input type="text" id="email">
<input type="submit" onclick="validateEmail()" >
JavaScript Code :-
function validateEmail() {
var emailText = document.getElementById('email').value;
var pattern = /^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*#[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$/;
if (pattern.test(emailText)) {
return true;
} else {
alert('Bad email address: ' + emailText);
document.getElementById("email").style.backgroundColor = "Red";
return false;
}
}
Working Demo for Email Validation.
I hope it will help you.

AngularJs radio button dirty validation not working

I have two fields , for email the validation is working fine , but for radio button no error is been shown .. i am not getting this , why this is happening . i ma using angular-1.0.8.min.js
//js code
var app = angular.module("App", []);
app.controller('signupController', ['$scope', function($scope) {
$scope.selectedGender = '';
$scope.gender = [{'name':'Male', 'id':1}, {'name':'Female', 'id':2}];
$scope.submitted = true;
$scope.signupForm = function() {
if ($scope.signup_form.$valid) {
// Submit as normal
} else {
$scope.signup_form.submitted = true;
}
}
}]);
//html code
<!DOCTYPE html>
<html >
<meta charset="utf-8">
<meta content="width=device-width" name="viewport">
<body ng-app="validationExampleApp">
<div align="center" style="width: 500px; ">
<form ng-controller="signupController" name="signup_form" novalidate ng-submit="signupForm()">
<fieldset>
<legend>Signup</legend>
<div class="row">
<div class="large-12 columns">
<label>Your email</label>
<input type="email"
placeholder="Email"
name="email"
ng-model="signup.email"
ng-minlength=3 ng-maxlength=20 required />
<div class="error"
ng-show="signup_form.email.$dirty && signup_form.email.$invalid && signup_form.submitted ">
<small class="error"
ng-show="signup_form.email.$error.required">
Your email is required.
</small>
<small class="error"
ng-show="signup_form.email.$error.email">
That is not a valid email. Please input a valid email.
</small>
</div>
</div>
</div>
<div ng-repeat="(key, val) in gender">
<input type="radio" ng-model="signup.selectedGender" name="radiob" id="{{val.id}}" value="{{val.id}}" ng-click required /> {{val.name}}
</div>
<div class="error"
ng-show="signup_form.radiob.$dirty && signup_form.radiob.$invalid && signup_form.submitted ">
<small class="error" ng-show="signup_form.radiob.$error.required">
Your email is required.
</small>
</div>
<button type="submit" class="button radius">Submit</button>
</fieldset>
</form>
</div>
</body></html>
It's hard to tell for sure because the code provided is invalid but you are probably hitting the angular js bug where it doesn't mark the radio button as valid until all radio buttons have been selected.
See this question
This is fixed in version 1.2.0-rc.3. I've created a Plunker demo here with some code changes to mimic what I think you are trying to do.

How to Validation that User should enter any of two field

form html
<form action="" method="post" name="add_new_report" id="add_new_report" enctype="multipart/form-data" onsubmit="return AddNewReport(this)">
<div class="field">
<div class="field_180">Cheque</div>
<div class="field_30">:</div>
<div class="field_220">
<input type="text" name="cheque" id="cheque" onChange="updatesum()" />
</div>
<div class="clear"></div>
</div>
<div class="field">
<div class="field_180">Cash</div>
<div class="field_30">:</div>
<div class="field_220">
<input type="text" name="cash" id="cash" onChange="updatesum()" />
</div>
<div class="clear"></div>
</div>
<div class="field">
<div class="field_210"> </div>
<div class="field_222">
<input type="submit" id="Submit" name="Submit" value="Submit" />
</div>
<div class="clear"></div>
</div>
</form>
in this form user should enter either cheque or cash Field how is it possible ? i don't want to be both are mandatory.
If you absolutely do not care about IE <9 you could use something like the following. (otherwise replace the code not working in IE, with some that does)
function oneShouldHaveData(ids) {
var elements = [];
//convert ids to elements (map no IE<9)
elements = ids.map(function (id) {
return document.querySelector('#' + id);
});
//returns true if any element matches expression (some no IE <9)
return elements.some(function (element) {
//could be validation for anything (greater 0 etc.)
return !!element.value;
});
}
//just submit setup :)
document.querySelector('#add_new_report').addEventListener('submit', function () {
console.log(oneShouldHaveData(['cheque', 'cash']));
});
http://jsfiddle.net/LXprX/1/
Simply add this function to your header:
<script>
function validateForm()
{
var x=document.forms["add_new_report"]["cheque"].value;
var y=document.forms["add_new_report"]["cash"].value;
if ((x==null || x=="") && (y==null || y==""))
{
alert("At least one entry should be filled");
return false;
}
else
return true
}
</script>
and change the following field:
onsubmit="if(validateForm()) return AddNewReport(this)"
You can also include AddNewReport in validateForm function and only return validate(this) function.

Categories

Resources