I want to check if any element in a class meets certain conditions.
Example.
$(document).on('click','.modalInner_form_nav', function(){
var input = $(this).parents('.modalInner_form').find('.validate_g');
//$(input).each(function(index, element) {
if ($(input).val() == ''){
$(input).css('border', '#BB0000 1px solid');
return false;
}
else {
/////////go to next///////////
if ($(this).parents('.modalInner_form').is(':last-child')){
}
else {
$(this).parents('.modalInner_form').slideUp();
$(this).parents('.modalInner_form').next('.modalInner_form').slideDown();
}
////////////
}
});
This returns false if all input fields are empty, but if one in this class is not empty, it returns true.
The problem is you have a inner function so
$(document).on('click', '.modalInner_form_nav', function () {
var $form = $(this).parents('.modalInner_form');
var $input = $form.find('.validate_g');
var valid = true;
$input.each(function (index, element) {
var $this = $(this)
if ($this.val() == '') {
valid = false;
$this.css('border', '#BB0000 1px solid');
}
});
if (valid) {
if ($form.is(':last-child')) {
//do something else
} else {
$form.slideUp();
$form.next('.modalInner_form').slideDown();
}
}
});
Not really sure what your question is, but here is a way to improve your code.
Save $(this).parents('.modalInner_form') in a variable instead of constantly repeating this same line of code. Then you can replace all those method calls with the variable and just call whatever functions you want on the variable.
var varName = $(this).parents('.modalInner_form');
varName.find('.validate_g');
...
if(varName.is(':last-child')){
...
Related
How to call first function inside second function with "this" as a selector in the first function that is called in second function. Here is the code:
const _ERROR_MESSAGE = function(thisElement){ thisElement.after('<p class="error">'+thisElement.data("error-message")+'</p>') };
let _removeHtml = function(thisElement){ thisElement.next(".error").remove(); };
function validate(event){
event.preventDefault();
$("form input[data-required]").each(function(index){
if($(this).val().length <= 0){
if($(this).next().hasClass("error") == false){
_ERROR_MESSAGE($(this));
}
}
else{
_removeHtml($(this));
}
});
}
Is it possible to remove $(this) argument from function _ERROR_MESSAGE($(this)) and _removeHtml($(this)) and have it in their respective function definition and still work?
Any help is greatly appreciated!
You can use the call method and "this" as a local variable in the first function for more efficient code.
var $_this = $(this);
In your own way:
const _ERROR_MESSAGE = function(){ this.after('<p class="error">'+this.data("error-message")+'</p>') };
let _removeHtml = function(){ this.next(".error").remove(); };
function validate(event){
event.preventDefault();
$("form input[data-required]").each(function(index){
var $_this = $(this);
if($_this.val().length <= 0){
if($_this.next().hasClass("error") == false){
_ERROR_MESSAGE.call($_this);
}
}
else{
_removeHtml.call($_this);
}
});
}
If you want more efficient code and within the same function
function validate(event){
event.preventDefault();
//Validate each form input
$("form input[data-required]").each(function(index){
var $_this = $(this);
var $_error = $_this.next(".error");
if($_this.val().length == 0) {
if($_error.length == 0)
$_this.after('<p class="error">'+$_this.data("error-message")+'</p>');
} else
$_error.remove();
});
}
$('#submitbtn').on("click", function() {
$('.message-box').val();
var message = $(".message-box").val();
$('#visible-comment').html(message);
$('.message-box').hide();
return false;
});
I want the above code in an if/else condition that if the value of .message-box is an empty string to change the border color of .message-box to red.
Could someone please guide me in the right direction?
I've tried the following, which changes the border red, but doesn't fire the rest of the code.
$('#submitbtn').on("click", function() {
if ($(".message-box").val("")) {
$(".message-box").css("border","2px solid red");
} else {
$('.message-box').val();
var message = $(".message-box").val();
$('#visible-comment').html(message);
$('.message-box').hide();
return false;
}
});
sample here : https://jsfiddle.net/wf69c7uu/2/
The idea would be to check for your conditions, and then simply add or remove the class based on the evaluation of the expression.
Here is a working demo
The code would look like the following:
$('#submitbtn').on("click", function() {
$('.message-box').val();
var message = $(".message-box").val();
if (message === '') {
$('.message-box').addClass("invalid");
}
else {
$('.message-box').removeClass("invalid");
$('#visible-comment').html(message);
$('.message-box').hide();
}
return false;
});
Or, optionally, you can check the input in "real-time" as the user types like so:
$('#submitbtn').on("click", function() {
$('.message-box').val();
var message = $(".message-box").val();
if (!$(".message-box").hasClass("invalid")) {
$('#visible-comment').html(message);
$('.message-box').hide();
}
return false;
});
$(".message-box").on("input propertychange", function () {
var $this = $(this);
if (!$this.hasClass("invalid") && $this.val() === '') {
$this.addClass("invalid");
}
else if ($this.hasClass("invalid") && $this.val() !== '') {
$this.removeClass("invalid");
}
});
Slightly changed the code which you posted on jsfiddle:
Added an if else block.
Added $('.message-box').css("border", "4px solid red"); to set the border color of the textarea when it's empty.
$(function () {
$('#submitbtn').on("click", function () {
var message = $(".message-box").val();
if (message == "") {
$('.message-box').css("border", "4px solid red");
}
else {
$('#visible-comment').html(message);
$('.message-box').hide();
return false;
}
});
});
Add e.preventDefault function so that your POST action will not be triggered.
Add if/else statement to check if your message box was empty.
$('#submitbtn').on("click", function(e) {
e.preventDefault();
$('.message-box').val();
var message = $(".message-box").val();
if(message == ""){
$(".message-box").css("border","2px solid red");
}else{
$('#visible-comment').html(message);
$('.message-box').hide();
}
});
Hi i have a JavaScript validation code for a dynamically adding text boxes, it's showing alert when text boxes having empty values and not stopping there
$(document).on('click', '#med_submit', function () {
$(".medicine_name").each(function (i) {
var id = this.id;
var value = $("#" + id).val();
if (value.trim() == "") {
alert('Medicine name should not be empty');
return false;
}
});
$(".medicine_quantity").each(function (i) {
var id = this.id;
var value = $("#" + id).val();
if (value.trim() == "") {
alert('Quantity name should not be empty');
return false;
}
});
});
this is my script, in medicine_name each function there is any one medicine_name class textbox is empty then it shows alert message also it's going to the next medicine_quantity each function and show that alert too, here i am using return false after athe alert then how this happening, please help me
Just set a flag when you show an alert, and bail early if the flag is set.
$(document).on('click', '#med_submit', function() {
var alertShown = false;
$(".medicine_name").each(function(i) {
var id = this.id;
var value = $("#" + id).val();
if (value.trim() == "") {
alert('Medicine name should not be empty');
alertShown = true;
return false;
}
});
if (alertShown) return;
$(".medicine_quantity").each(function(i) {
var id = this.id;
var value = $("#" + id).val();
if (value.trim() == "") {
alert('Quantity name should not be empty');
return false;
}
});
});
Why doesn't return false; work?
The reason it isn't enough to return false; inside the .each() callback function is that all that does is stop processing the rest of the matched elements in the jQuery set.
From the jQuery docs:
You can stop the loop from within the callback function by returning false.
In other words, all it does is make the .each() call finish sooner than it normally would.
Regardless of when it finishes, though, the next line of code to execute after the first .each() call in your code is the second .each() call. It has no knowledge of what happened with the first .each() call, so it will start with the first matched element and call the supplied function for it, and then proceed with the rest of the matched elements unless the function returns false, when it will stop.
var blank_found = false;
$(".medicine_name").each(function (i){
var id=this.id;
var value=$("#"+id).val();
if(value.trim()==""){
blank_found=true;
alert('Medicine name should not be empty');
return false;
}
});
if (blank_found){
return false;
}
$(".medicine_quantity").each(function (i){
var id=this.id;
var value=$("#"+id).val();
if(value.trim()==""){
alert('Quantity name should not be empty');
return false;
}
});
You can use this one..
$(document).on('click','#med_submit',function(){
var isempty=false;
$(".medicine_name").each(function (i)
{
var id=this.id;
var value=$("#"+id).val();
if(value.trim()==""){isempty=true; alert('Medicine name should not be empty'); return false;}
});
$(".medicine_quantity").each(function (i)
{
var id=this.id;
var value=$("#"+id).val();
if(value.trim()==""){ isempty=true; alert('Quantity name should not be empty'); return false;}
});
if ( isempty==true ) {
return false;
}
});
I am using jQuery to validate some fields in a form, and seem to be having an issue with one field in particular (#inputTel).
If an incorrect format is entered, an error message pops up underneath, which is fine, but the problem is once the correct format is entered the message does not disappear.
Here's a jsFiddle with the complete demo.
This is the section in question:
//Tel Validate
function is_valid_tel() {
$this = $("#inputTel");
var pattern = new RegExp("^\d{11}$");
if (pattern.test($this.val())) { // valid
if ($this.closest(".control-group").hasClass("error")) $this.closest(".control-group").removeClass("error");
$this.siblings(".help-inline").css("display", "none");
return true;
} else { // error
if (!$this.closest(".control-group").hasClass("error")) $this.closest(".control-group").addClass("error");
$this.siblings(".help-inline").css("display", "block");
return false;
}
}
Every other field works as expected except this one. My jQuery skills are limited so I'm unsure of how to solve this.
Problem in your code:
Replace var pattern = new RegExp("^\d{11}$"); with var pattern = new RegExp(/^\d{11}$/);
Updated code
//Tel Validate
function is_valid_tel() {
$this = $("#inputTel");
var pattern = new RegExp(/^\d{11}$/);// Update this line
if (pattern.test($this.val())) { // valid
if ($this.closest(".control-group").hasClass("error")) $this.closest(".control-group").removeClass("error");
$this.siblings(".help-inline").css("display", "none");
return true;
} else { // error
if (!$this.closest(".control-group").hasClass("error")) $this.closest(".control-group").addClass("error");
$this.siblings(".help-inline").css("display", "block");
return false;
}
}
Check the fiddle http://jsfiddle.net/rfg8H/
You could also use something like below, less cubersome:
$(function() {
function validateTheForm() {
var ok = true;
$(".input-medium").each(function() {
if($(this).val() == "") //use regex actually here
{
$(this).next().css("display","inline");
ok = false;
}
else {
$(this).next().css("display","none");
}
});
return ok;
}
$(".btn").click(function() {
$("form").submit(validateTheForm());
$("form").submit();
});
});
Okay,
Another novice type question.
I have this array within the head section on my website and want to use it inline JavaScript:
var MyVariable = {"chkboxid":"chkbox"}
chkboxid is a id of a checkbox input.
Now, while validating the checkbox input on form submit, neither this works
$("form#myform").submit(function () {
if ($(MyVariable.chkboxid).is(":checked")) {
} else {
alert(CommentsPlus.nochkboxmsg);
return false;
}
Nor This (check the double quote at the variable)
$("form#myform").submit(function () {
if ($("MyVariable.chkboxid").is(":checked")) {
} else {
alert(CommentsPlus.nochkboxmsg);
return false;
}
However, if I hardcode the checkbox input id, it works. I mean "input#chkbox" in place of MyVariable.chkboxid.
$("form#myform").submit(function () {
if ($("input#chkbox").is(":checked")) {
} else {
alert(CommentsPlus.nochkboxmsg);
return false;
}
How can I use that variable instead of hard coding the input id?
You are missing the "#" before the ID:
$("form#myform").submit(function () {
var element = $("#" + MyVariable.chkboxid)
if (element.is(":checked")) {
} else {
alert(CommentsPlus.nochkboxmsg);
return false;
}
}
Note however that chkboxid is the key, the actual ID of the checkbox should be the value:
var MyVariable = {"chkboxid": "real_id_here"}
please check below code.hope it will work
$("form#myform").submit(function () {
if ($("#chkboxid").is("checked")) {alert("checked");
} else {
alert("not checked");
}
});
thanks,Ripa Saha