How to specify minlength in jquery? - javascript

If the status value is completed then comment field is required is working good.But the problem is, I want to specify comment field is required for minimum of 50 character.
The Below code: index.php
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="selectbasic">Status</label>
<div class="col-md-4">
<select id="status" name="status[]" class="form-control" >
<option value="Pending">Pending</option>
<option value="Work in process">Work in process</option>
<option value="Completed">Completed</option>
</select>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Comment</label>
<div class="col-md-4">
<input id="commentss" name="comment[]" type="text" placeholder="" class="form-control input-md" />
</div>
</div>
<div class="col-md-8 col-sm-12 col-24">
<div class="input_fields" style="color:black">
<button class="add_field btn " onclick="incrementValue()" >Add More</button>
<div>
<input type="text" name="mytextt[]" hidden="" ></div>
</div>
</div>
Javascript
<script type="text/javascript">
$(document).ready(function () {
$("#status").click(function () {
if ($("#status").val() == "Completed") {
$("#commentss").attr("required", "required");
}
else
$("#commentss").attr("required", false);
});
});
</script>

Use length to find the length of the string
if($('#commentss').val().length < 50){
alert("Please enter 50 characters atleast");
} else {
//submit
}

For this please use below code :
<script type="text/javascript">
$(document).ready(function () {
$("#status").click(function () {
var commenttext = document.getElementById('commentss').value;
if (commenttext.length < 50)
{
alert("Please Enter minimum 50 character!")
}
else
{
//Add code
}
});
});
</script>

In Jquery ...
For Dynamic Tracking ...
(You can use blur or keyup even too.)
$(function() {
//disable submit if you want to
$('#commentss').on('input', function(e) {
if(this.value.length >= 50) {
//success
} else {
//fail?
}
});
});
To Validate on Click only ...
Go with the answer of Thamaraiselvam.

Related

bootstrap 4 validation with password confirmation and submit disabled until form validated (Registration form)

In a simple form there are 3 input fields with regex pattern in each.
Two of them ('Password' and 'Confirm Password') must match. If the don't, a message "Not Matching" is displayed. If they do, "Valid" is displayed.
How can I (via the javascript) force the Bootstrap 4 validation's red border and 'X' icon to be displayed in the following case :
Entering 'aa' in the 'Password' field (it matches the regex hence the valid green border and V icon).
Entering 'aa' in the 'Confirm Password' field (it matches the regex hence the valid green border and V icon).
Now I add another character to 'Confirm Password' and it immediately displays "Not Matching", but since it's ok according to the regex - it is still green with a 'V' icon.
I need to force the red border and 'X' icon when this happens.
My code :
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<style>
input[type="submit"]:disabled {
background-color: red;
}
</style>
</head>
<body>
<div class="container mt-2">
<div class="row">
<div class="col-md-4 offset-md-4">
<form action="page2.php" id="myForm1" class="needs-validation" novalidate>
<div class="form-group">
Field1<input type="text" class="form-control" pattern="^[a-z]{2,4}$" required autofocus>
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">a to z only (2 to 4 long)</div>
</div>
<div class="form-group">
Password<input type="text" id="pwdId" class="form-control" pattern="^[a-z]{2,4}$" required>
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">a to z only (2 to 4 long)</div>
</div>
<div class="form-group">
Confirm Password<input type="text" id="cPwdId" class="form-control" pattern="^[a-z]{2,4}$" required>
<div id="cPwdValid" class="valid-feedback">Valid</div>
<div id="cPwdInvalid" class="invalid-feedback">a to z only (2 to 4 long)</div>
</div>
<div class="form-group">
<button id="submitBtn" type="submit" class="btn btn-primary submit-button" disabled>Submit</button>
</div>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
// Check if passwords match
$('#pwdId, #cPwdId').on('keyup', function () {
if ($('#pwdId').val() != '' && $('#cPwdId').val() != '' && $('#pwdId').val() == $('#cPwdId').val()) {
$("#submitBtn").attr("disabled",false);
$('#cPwdValid').show();
$('#cPwdInvalid').hide();
$('#cPwdValid').html('Valid').css('color', 'green');
} else {
$("#submitBtn").attr("disabled",true);
$('#cPwdValid').hide();
$('#cPwdInvalid').show();
$('#cPwdInvalid').html('Not Matching').css('color', 'red');
}
});
let currForm1 = document.getElementById('myForm1');
// Validate on submit:
currForm1.addEventListener('submit', function(event) {
if (currForm1.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
currForm1.classList.add('was-validated');
}, false);
// Validate on input:
currForm1.querySelectorAll('.form-control').forEach(input => {
input.addEventListener(('input'), () => {
if (input.checkValidity()) {
input.classList.remove('is-invalid')
input.classList.add('is-valid');
} else {
input.classList.remove('is-valid')
input.classList.add('is-invalid');
}
var is_valid = $('.form-control').length === $('.form-control.is-valid').length;
$("#submitBtn").attr("disabled", !is_valid);
});
});
});
</script>
Thank you!
Couldn't you toggle the is-invalid class as needed on both password inputs?
$('#pwdId, #cPwdId').on('keyup', function () {
if ($('#pwdId').val() != '' && $('#cPwdId').val() != '' && $('#pwdId').val() == $('#cPwdId').val()) {
$("#submitBtn").attr("disabled",false);
$('#cPwdValid').show();
$('#cPwdInvalid').hide();
$('#cPwdValid').html('Valid').css('color', 'green');
$('.pwds').removeClass('is-invalid')
} else {
$("#submitBtn").attr("disabled",true);
$('#cPwdValid').hide();
$('#cPwdInvalid').show();
$('#cPwdInvalid').html('Not Matching').css('color', 'red');
$('.pwds').addClass('is-invalid')
}
});
<form action="page2.php" id="myForm1" class="needs-validation" novalidate>
<div class="form-group">
Field1<input type="text" class="form-control" pattern="^[a-z]{2,4}$" required autofocus>
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">a to z only (2 to 4 long)</div>
</div>
<div class="form-group">
Password<input type="text" id="pwdId" class="form-control pwds" pattern="^[a-z]{2,4}$" required>
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">a to z only (2 to 4 long)</div>
</div>
<div class="form-group">
Confirm Password<input type="text" id="cPwdId" class="form-control pwds" pattern="^[a-z]{2,4}$" required>
<div id="cPwdValid" class="valid-feedback">Valid</div>
<div id="cPwdInvalid" class="invalid-feedback">a to z only (2 to 4 long)</div>
</div>
<div class="form-group">
<button id="submitBtn" type="submit" class="btn btn-primary submit-button" disabled>Submit</button>
</div>
</form>
Demo: https://www.codeply.com/p/AQBzIBAsZl
With help from #Zim I got started and managed to solve it.
Following is the code for a full Registration form with comparison of the 2 passwords.
Notice that the Submit button is enabled ONLY when all elements in the form are valid!
Note 1 : I tested it extensively but it might have a bug or a design flaw (please let us all know about it if you find one).
Note 2 : When it comes to Javascript and JQuery, I was born a mere 2 weeks ago, so I guess my solution is not as elegant as can possibly be (again, let us all know if you can improve it).
Here is the full code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><title>Registration</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<style>
input[type="submit"]:disabled {
background-color: red;
}
</style>
</head>
<body>
<div class="container mt-2">
<div class="row">
<div class="col-md-4 offset-md-4" style="background-color: lightblue;">
<form action="page2.php" id="myForm1" class="needs-validation" novalidate>
<h1 class="text-center">Registration</h1><hr>
<div class="form-group">
First Name<input name="myInput" id="fisrtNameId" type="text" class="form-control" pattern="^[a-z]{2,15}$" required autofocus>
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">a to z only (2 to 15 long)</div>
</div>
<div class="form-group">
Last Name<input name="myInput" id="lastNameId" type="text" class="form-control" pattern="^[a-z]{2,15}$" required>
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">a to z only (2 to 15 long)</div>
</div>
<div class="form-group">
E-mail<input type="email" name="myInput" id="emailId" class="form-control" pattern="^[a-zA-Z0–9.!#$%&’*+\/=?^_`{|}~-]+#[a-zA-Z0–9](?:[a-zA-Z0–9-]{0,61} [a-zA-Z0–9])?(?:\.[a-zA-Z0–9](?:[a-zA-Z0–9-]{0,61}[a-zA-Z0–9])?)*$" required>
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">Not a valid email address</div>
</div>
<div class="form-group">
Password<input type="text" id="pwdId" class="form-control" pattern="^[a-z]{2,6}$" required>
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">a to z only (2 to 6 long)</div>
</div>
<div class="form-group">
Confirm Password<input type="text" id="cPwdId" class="form-control myCpwdClass" pattern="^[a-z]{2,6}$" required>
<div id="cPwdValid" class="valid-feedback">Passwords Match</div>
<div id="cPwdInvalid" class="invalid-feedback">a to z only (2 to 6 long)</div>
</div>
<div class="form-group">
Description<textarea form="myForm1" name="myInput" id="descId" type="text" class="form-control" required></textarea>
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">Required</div>
</div>
<div class="form-group">
<div class="custom-control custom-checkbox">
<input type="checkbox" id="agreeId" class="custom-control-input form-control" required>
<label for="agreeId" id="agreeLabelId" class="custom-control-label">Agree to terms (terms & conditions)</label>
<div id="agreeValid" class="valid-feedback">Valid</div>
<div id="agreeInvalid" class="invalid-feedback">Needs to be checked</div>
</div>
</div>
<div class="form-group">
<button id="submitBtn" type="submit" class="btn btn-secondary" disabled>Register</button>
</div>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
// ----------- Set all elements as INVALID --------------
var myInputElements = document.querySelectorAll(".form-control");
var i;
for (i = 0; i < myInputElements.length; i++) {
myInputElements[i].classList.add('is-invalid');
myInputElements[i].classList.remove('is-valid');
}
// ------------ Check passwords similarity --------------
$('#pwdId, #cPwdId').on('keyup', function () {
if ($('#pwdId').val() != '' && $('#cPwdId').val() != '' && $('#pwdId').val() == $('#cPwdId').val() ) {
$('#cPwdValid').show();
$('#cPwdInvalid').hide();
$('#cPwdInvalid').html('Passwords Match').css('color', 'green');
$('.myCpwdClass').addClass('is-valid');
$('.myCpwdClass').removeClass('is-invalid');
$("#submitBtn").attr("disabled",false);
$('#submitBtn').addClass('btn-primary').removeClass('btn-secondary');
for (i = 0; i < myInputElements.length; i++) {
var myElement = document.getElementById(myInputElements[i].id);
if (myElement.classList.contains('is-invalid')) {
$("#submitBtn").attr("disabled",true);
$('#submitBtn').addClass('btn-secondary').removeClass('btn-primary');
break;
}
}
} else {
$('#cPwdValid').hide();
$('#cPwdInvalid').show();
$('#cPwdInvalid').html('Not Matching').css('color', 'red');
$('.myCpwdClass').removeClass('is-valid');
$('.myCpwdClass').addClass('is-invalid');
$("#submitBtn").attr("disabled",true);
$('#submitBtn').addClass('btn-secondary').removeClass('btn-primary');
}
});
// ----------------- Validate on submit -----------------
let currForm1 = document.getElementById('myForm1');
currForm1.addEventListener('submit', function(event) {
if (currForm1.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
else {
$("#submitBtn").attr("disabled",false);
$('#submitBtn').addClass('btn-primary').removeClass('btn-secondary');
currForm1.classList.add('was-validated');
}
}, false);
// ----------------- Validate on input -----------------
currForm1.querySelectorAll('.form-control').forEach(input => {
input.addEventListener(('input'), () => {
if (input.checkValidity()) {
input.classList.remove('is-invalid');
input.classList.add('is-valid');
} else {
input.classList.remove('is-valid');
input.classList.add('is-invalid');
}
var is_valid = $('.form-control').length === $('.form-control.is-valid').length;
// $("#submitBtn").attr("disabled", !is_valid);
if (is_valid) {
$("#submitBtn").attr("disabled",false);
$('#submitBtn').addClass('btn-primary').removeClass('btn-secondary');
} else {
$("#submitBtn").attr("disabled",true);
$('#submitBtn').addClass('btn-secondary').removeClass('btn-primary');
}
});
});
// ------------------------------------------------------
});
</script>
</body>
</html>

issue in Bootstrap 4 validation on select field

I'm new to jQuery and Bootstrap, I'm using jquery and Bootstrap 4 for validation of my form modal, whenever there is an error it must show the error below the corresponding fields, but in my case the select field gets overwritten by the error and select field disappears but it works fine for input field.
here have a look and if you want to have a close look on image just click on it..
As you can see the select fields get overwritten by the fieldError but it's fine for input field.
here's my jQuery validation code:
$(function(){
setCategorySelect();
$(document).on('shown.bs.modal','#manageItemsModal', function () {
$('#manageItemsModal #btnSubmit').on('click', function(){
if (validateForm()) {
messageSuccess("Very well");
} else {
messageError("Oops!!");
}
});
});
});
function validateForm() {
var validationStatus = true;
if ($('#manageItemsForm #selectedCategory').val().length == 0) {
showFieldError(('#manageItemsForm #selectedCategory'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #selectedCategory').focus() };
validationStatus = false;
}
if ($('#manageItemsForm #selectedBrandModel').val().length == 0) {
showFieldError(('#manageItemsForm #selectedBrandModel'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #selectedBrandModel').focus() };
validationStatus = false;
}
if ($('#manageItemsForm #serialNo').val().length == 0) {
showFieldError(('#manageItemsForm #serialNo'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #serialNo').focus() };
validationStatus = false;
}
if ($('#manageItemsForm #selectedVendor').val().length == 0) {
showFieldError(('#manageItemsForm #selectedVendor'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #selectedVendor').focus() };
validationStatus = false;
}
if ($('#manageItemsForm #selectedBranch').val().length == 0) {
showFieldError(('#manageItemsForm #selectedBranch'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #selectedBranch').focus() };
validationStatus = false;
}
return validationStatus;
}
function showFieldError(element, message) {
$(element).addClass('is-invalid');
$(element).next().html(message);
$(element).next().show();
}
function clearFieldError(element) {
$(element).removeClass('is-invalid');
$(element).removeAttr('required');
$(element).next().html('');
}
function setCategorySelect() {
var $categorySelect = $('#manageItemsForm #selectedCategory').selectize({
selectOnTab: true,
closeAfterSelect: true,
persist: false,
create: false,
valueField: 'id',
labelField: 'text',
options: [],
preload: true,
onInitialize : function() {
var self = this;
$.ajax({
url: '/assetCategory/search',
type: 'POST',
dataType: 'json',
data: {
searchText: '*'
},
error: function() {
callback();
},
success: function(res) {
self.addOption(res.data);
}
});
},
load: function(query, callback) {
if (query.length <= 2) return callback();
$.ajax({
url: '/assetCategory/search',
type: 'POST',
dataType: 'json',
data: {
searchText: query + "*"
},
error: function() {
callback();
},
success: function(res) {
console.log(res.data);
callback(res.data);
$categorySelect.refreshItems();
},
fail : function() {
callback();
}
});
}
});
}
here's my HTML:
<div class="modal-body">
<form id="manageItemsForm">
<input type="hidden" id="id" name="id">
<div class="row">
<div class="col-4">
<div class="form-group">
<label for="selectedCategory" class="col-form-label"><span class="text-danger">* </span>Category</label>
<select class="form-control" name="selectedCategory" id="selectedCategory"></select>
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-8">
<div class="form-group">
<label for="selectedBrandModel" class="col-form-label"><span class="text-danger">* </span>Brand & Model</label>
<select class="form-control" name="selectedBrandModel" id="selectedBrandModel"></select>
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-4">
<div class="form-group">
<label for="serialNo" class="col-form-label"><span class="text-danger">* </span>Serial No.</label>
<input type="text" class="form-control" id="serialNo" name="serialNo">
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-8">
<div class="form-group">
<label for="description" class="col-form-label">Description</label>
<input type="text" class="form-control" id="description" name="description">
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-6">
<div class="form-group">
<label for="selectedVendor" class="col-form-label"><span class="text-danger">* </span>Purchase Vendor</label>
<select class="form-control" name="selectedVendor" id="selectedVendor"></select>
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="selectedVendor" class="col-form-label"><span class="text-danger">* </span>Purchase Date</label>
<div class="input-group date" data-date-format="dd-M-yyyy">
<input type="text" class="form-control" id="purchaseDate" name="purchaseDate" />
<span class="input-group-text input-group-append input-group-addon"><i class="simple-icon-calendar"></i></span>
</div>
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="supportTillDate" class="col-form-label"><span class="text-danger">* </span>Support till date</label>
<div class="input-group date" data-date-format="dd-M-yyyy">
<input type="text" class="form-control" id="supportTillDate" name="supportTillDate" />
<span class="input-group-text input-group-append input-group-addon"><i class="simple-icon-calendar"></i></span>
</div>
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-9">
<div class="form-group">
<label for="selectedBranch" class="col-form-label"><span class="text-danger">* </span>Branch</label>
<select class="form-control" name="selectedBranch" id="selectedBranch"></select>
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-3">
<label for="purchasePrice" class="col-form-label">Purchase Price</label>
<div class="input-group">
<div class="input-group-prepend"><span class="input-group-text input-group-addon" style="padding: 0.4rem 0.75rem 0.3rem 0.75rem;">₹</span></div>
<input id="purchasePrice" name="purchasePrice" type="text" class="form-control" aria-label="Amount" style="text-align:right;">
</div>
<div class="invalid-feedback"></div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button id="btnSubmit" type="button" class="btn btn-primary">Save</button>
</div>
</div>
By the way I am using jQuery in Spring boot and everything is working fine(save, update, delete) except for validation from jQuery.
Please help!!
I can't see working code because you using some external references like selectize.
I suggest you get used to "snippets" to provide code.
Bytheway, your problem seems to be just about styles. I can't know, but my bet is you just need to provide a css style for
.select::after.error {
color:red;
}
You can inspect and copy CSS code.
The problem is in Your HTML, the nodes of your .input-group does not have allways the same structure. In some cases you have .invalid-feedback just after the input such as this HTML
<div class="form-group">
<label for="serialNo" class="col-form-label"><span class="text-danger">*
</span>Serial No.</label>
<input type="text" class="form-control" id="serialNo" name="serialNo">
<div class="invalid-feedback"></div>
</div>
For other fields the .invalid-feedback isn't after the input but outside from .form-group. take a look
<div class="input-group date" data-date-format="dd-M-yyyy">
<input type="text" class="form-control" id="purchaseDate" name="purchaseDate" />
<span class="input-group-text input-group-append input-group-addon">
<i class="simple-icon-calendar"></i>
</span>
</div>
<div class="invalid-feedback"></div>
This difference in HTML structure of the form made your showFieldError() and clearFieldError() not working allways as you expected, because $(element).next() don't catch the right DOM node for insert/remove the validation message. So in some cases clearFieldError remove the wrong HTML tag and this can make your selects disappear
function showFieldError(element, message) {
$(element).addClass('is-invalid');
$(element).next().html(message);
$(element).next().show();
}
function clearFieldError(element) {
$(element).removeClass('is-invalid');
$(element).removeAttr('required');
$(element).next().html('');
}
So you have to fix Your HTML to obtain the same structure for all fields. Put the <div class="invalid-feedback"></div> allways just below the select or input field. Otherwise you have to change the selector that you pass to showFieldError() and clearFieldError() functions according to your HTML
Otherwise a simply approach is to add a ID to divs with class .invalid-feedback, an ID which you can easily manage by his related input ID, something like
<div class="input-group date" data-date-format="dd-M-yyyy">
<input type="text" class="form-control" id="purchaseDate" name="purchaseDate" />
<span class="input-group-text input-group-append input-group-addon">
<i class="simple-icon-calendar"></i>
</span>
</div>
<div id="purchaseDate_err_mex" class="invalid-feedback"></div>
in this way you can pass the input name to your functions and them becomes
function showFieldError(input_id, message) {
$('#'+input_id).addClass('is-invalid');
$('#'+ input_id +'_err_mex').html(message).show();
}
function clearFieldError(input_id) {
$('#'+input_id).removeClass('is-invalid');
//$('#'+input_id).removeAttr('required');
/* don't need to remove required attribute from mandatory fields */
$('#'+ input_name +'_err_mex').html('').hide();
}
and the validation function
function validateForm() {
var validationStatus = true;
if ($('#selectedCategory').val().length == 0) {
showFieldError('selectedCategory', 'Must not be blank');
if (validationStatus) { $('#selectedCategory').focus() };
validationStatus = false;
}
........
return validationStatus;
}
You only check if the length of all fields is more than 0, so you can validate the entire form within a loop
function validateForm() {
var validationStatus = true;
var form_inputs = $('#manageItemsForm input, #manageItemsForm select')
$.each(form_inputs,function(){
var input_id = $(this).attr('name');
clearFieldError(input_id);
if ($.trim($(this).val()).length == 0 && $(this).is("[required]")) {
showFieldError(input_id, 'Must not be blank');
if (validationStatus) { $('#'+input_id).focus() };
validationStatus = false;
}
});
return validationStatus;
}

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>

ajax form is not working how it should

hello i been working on a form using ajax but when it comes down to validating a select box
problem 1) every time i leave the job_est value empty the form is still submitted as if it was validated
problem 2) can i use async in ajax
sorry for my writing skills
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//if submit button is clicked
$('#submit').click(function () {
//Get the data from all the fields
var name = $('input[name=name]');
var l_name = $('input[name=l_name]');
var phone = $('input[name=phone]');
var email = $('input[name=email]');
var postcode = $('input[name=postcode]');
var house_number = $('input[name=house_number]');
var street = $('input[name=street]');
var job_est = $('select[name=job_est]');
var comment = $('textarea[name=comment]');
//Simple validation to make sure user entered something
//If error found, add hightlight class to the text field
if (name.val()=='') {
name.addClass('hightlight');
return false;
} else name.removeClass('hightlight');
if (l_name.val()=='') {
l_name.addClass('hightlight');
return false;
} else l_name.removeClass('hightlight');
if (phone.val()=='') {
phone.addClass('hightlight');
return false;
} else phone.removeClass('hightlight');
if (email.val()=='') {
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');
if (postcode.val()=='') {
postcode.addClass('hightlight');
return false;
} else postcode.removeClass('hightlight');
if (house_number.val()=='') {
house_number.addClass('hightlight');
return false;
} else house_number.removeClass('hightlight');
if (street.val()=='') {
street.addClass('hightlight');
return false;
} else street.removeClass('hightlight');
if (job_est.val()=='') {
job_est.addClass('hightlight');
return false;
} else job_est.removeClass('hightlight');
if (comment.val()=='') {
comment.addClass('hightlight');
return false;
} else comment.removeClass('hightlight');
//organize the data properly
var data = 'name=' + name.val() + '&email=' + email.val() + '&phone=' +
phone.val() + '&comment=' + encodeURIComponent(comment.val());
//disabled all the text fields
$('.text').attr('disabled','true');
//show the loading sign
$('.loading').show();
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "process.php",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.done').fadeIn('slow');
//if process.php returned 0/false (send mail failed)
} else alert('Sorry, unexpected error. Please try again later.');
}
});
//cancel the submit button default behaviours
return false;
});
});
</script>
<body>
<div class="block">
<div class="done">
<b>Thank you !</b> We have received your message.
</div>
<div class="form">
<form method="post" action="process.php">
<h4><u>Basic Contact Details</u></h4>
<div style="display: inline-block;" class="element">
<label>Name</label><input type="text" name="name"/>
</div>
<div style="display: inline-block;" class="element">
<label>Last Name: </label><input type="text" name="l_name"/>
</div>
<div class="element">
<label>Phone Number</label>
<input type="text" name="phone"/>
</div>
<div class="element">
<label>Email</label>
<input type="text" name="email"/>
</div>
<div style="display: inline-block;" class="element">
<label>Postcode: </label><input type="text" name="postcode" size="10" maxlength="10">
</div>
<div style="display: inline-block;" class="element">
<label>House Number: </label><input type="text" name="house_number" size="3">
</div>
<div style="display: inline-block;" class="element">
<label>Street Name: </label><input type="text" name="street">
</div>
<div style="display: inline-block;" class="element">
<label>County:</label>
<select>
<option name="select">--SELECT--</option>
<option name="bedford">Bedford</option>
<option name="dunstable">Dunstable</option>
<option name="luton">Luton</option>
</select>
</div>
<h4><u>Job Details</u></h4>
<div class="element">
<label>You Would Like To Book A:</label>
<select name="job_est">
<option name="select">--SELECT--</options>
<option name="job">Job</option>
<option name="est">Estimation</option>
</select>
</div>
<br/>
<div class="element">
<label>Service Your Booking:</label>
<select>
<option name="select">--SELECT--</option>
<option name="gardening">Gardening</option>
<option name="landscaping">Landscaping</option>
<option name="painting">Painting & Decorating</option>
<option name="decking">Decking & Fencing</option>
</select>
</div>
<br/>
<div class="element">
<label>Any Additional Information </label>
<textarea name="comment" class="text textarea" /></textarea>
</div>
<div class="element">
<input type="submit" id="submit"/>
<div class="loading"></div>
</div>
</form>
</div>
</div>
<div class="clear"></div>
You should change selectbox's name attribute with value
<select name="job_est">
<option value="select">--SELECT--</options>
<option value="job">Job</option>
<option value="est">Estimation</option>
</select>
and in your javascript, it should be
if (job_est.val() == 'select') {
job_est.addClass('hightlight');
return false;
}

Validate form using jqueryvalidate.js and ckeditor Codeigniter

Hello. I have a form that gets validated by jqueryvalidate.js. I have a drop down menu and the menu will be different when I choose "Library Asset" because I need to choose another drop down menu that is hidden.
The problem is, when I am not choose other menu that is not showing another drop down menu..
the required rules still implemented.. so the form can't be submitted except the one that is showing another drop down menu..
Can someone help me here?
This is my code:
View(Js):
<script type="text/javascript">
function showbook()
{
var domObj1 = document.getElementById('emptybox');
var domObj2 = document.getElementById('showupbox');
if(domObj1.style.display =='none')
{
domObj1.style.display = 'block';
domObj2.style.display = 'none';
}
else
{
domObj1.style.display = 'none';
domObj2.style.display = 'block';
}
}
function closebook()
{
var domObj1 = document.getElementById('emptybox');
var domObj2 = document.getElementById('showupbox');
if(domObj1.style.display =='none')
{
domObj1.style.display = 'block';
domObj2.style.display = 'none';
}
}
function showhidebook()
{
console.log($('#CategoryAdviceSelect').val());
if($('#CategoryAdviceSelect').val() == 1)
{
showbook();
}
else{
closebook();
}
}
My validation rules:
<script>
$().ready(function() {
$("#feedback_form").validate({
ignore: "input:hidden:not(input:hidden.required)",
rules: {
CategoryAdviceSelect:"required",
Subject:"required",
Advice:"required",
BookSelect:"required"
},
messages: {
CategoryAdviceSelect:"Please select one of category advice",
Subject:"This field is required",
Advice:"This field is required",
BookSelect:"This field is required"
},
errorElement: "span",
highlight: function(element) {
$(element).parent().addClass("help-block");
},
unhighlight: function(element) {
$(element).parent().removeClass("help-block");
}
});
});
</script>
And my html view
<div class="row-fluid ">
<div class="box">
<hr>
<div class="paragraph">
<p>For enquiries about our services, write to: helpdesk#library.binus.ac.id.</p>
<p>You may also reach us at our helpdesk number 62-21-5350660. We value your feedback. Please fill in the form below, and help us improve our services.</p>
<p>Talk to me here
<a href = 'ymsgr:sendim?me_lieza93'>
<img src="http://opi.yahoo.com/online?u=me_lieza93&m=g&t=1" border=0>
</a>
</p>
</div>
<!--START FORM-->
<form id="feedback_form" name="feedback_form" action="<?php echo base_url();?>feedback/feedback/insert_to_db" method="post" class="form-horizontal" novalidate="novalidate">
<div class="control-group">
<!--FEEDBACK TYPE-->
<label class="span2 control-label" >Feedback for</label>
<div class="controls with-tooltip">
<select class="input-tooltip span5" tabindex="2" id="CategoryAdviceSelect" name="CategoryAdviceSelect" onchange="showhidebook();" >
<option value="" disabled selected>Choose Your Feedback For..</option>
<?php
for($x = 0 ; $x < count($feedback) ; $x++)
{ ?>
<option value="<?php echo $feedback[$x]['CategoryAdviceId']?>"><?php echo $feedback[$x]['CategoryAdviceName'] ?></option>
<?php
} ?>
</select>
</div>
</div>
<!--SUBJECT-->
<div class="control-group">
<label for="limiter" class="control-label">Subject</label>
<div class="controls">
<input type="text" class="span5" maxlength="50" id="Subject" name="Subject" placeholder="Type Your Feedback Subject.." />
<p class="help-block"></p>
</div>
</div>
<div id="emptybox"></div>
<!--CHOOSE BOOK-->
<div id="showupbox" style="display: none;">
<div class="control-group">
<label class="control-label">Choose Book</label>
<div class="controls">
<select class="chzn-select span5" tabindex="2" id="BookSelect" name="BookSelect">
<option value="" disabled selected>Choose Your Feedback For..</option>
<?php
for($y = 0 ; $y < count($booklist) ; $y++)
{ ?>
<option value="<?php echo $booklist[$y]['bi']?>"><?php echo $booklist[$y]['AssetTitle']?></option>
<?php
} ?>
</select>
</div>
</div>
</div>
<!--ADVICE-->
<div class="control-group">
<label for="limiter" class="control-label" >Suggestion</label>
<div class="controls">
<?php echo $this->ckeditor->editor("Advice",""); ?>;
</div>
</div>
<!--div class="alert alert-success">
<a class="close" data-dismiss="alert">×</a>
<strong>Success!</strong> Thanks for your feedback!
</div-->
<div class="bton1">
<button class="btn btn-primary round" type="submit">Submit</button>
<button class="btn btn-primary round" type="refresh">Reset</button>
</div>
</form>
</div><!--END BOX-->
Finally I can solve this..
<script>
$(document).ready(function() {
for(var name in CKEDITOR.instances) {
CKEDITOR.instances["Advice"].on("instanceReady", function() {
// Set keyup event
this.document.on("keyup", updateValue);
// Set paste event
this.document.on("paste", updateValue);
});
function updateValue() {
CKEDITOR.instances["Advice"].updateElement();
$('textarea').trigger('keyup');
}
}
$("#feedback_form").validate({
ignore: 'input:hidden:not(input:hidden.required)',
rules: {
CategoryAdviceSelect:"required",
Subject:"required",
Advice:"required",
BookSelect:{
required: function(element){
return $("#CategoryAdviceSelect").val()==1;
}
}
},
messages: {
CategoryAdviceSelect:"Please select one of category advice",
Subject:"This field is required",
Advice:"This field is required",
BookSelect:"This field is required",
},
errorElement: "span",
errorPlacement: function (error, element) {
if ($(element).attr('name') == 'Advice') {
$('#cke_Advice').after(error);
} else {
element.after(error);
}
},
highlight: function(element) {
$(element).parent().addClass("help-block");
},
unhighlight: function(element) {
$(element).parent().removeClass("help-block");
}
});
});
</script>

Categories

Resources