jQuery click events stopping works - javascript

I have a problem. jQuery('#FinishTest').click() works, but it stops when you select all the answers. The error does not appear in the console.
my code
jQuery('#FinishTest').click(function() {
var names = {};
jQuery(':radio').each(function() {
names[jQuery(this).attr('name')] = true;
});
var count = 0;
jQuery.each(names, function() {
count++;
});
if (jQuery(':radio:checked').length > 3) {
if (jQuery(':radio:checked').length < count) {
if (confirm("Henüz cevaplanmamış sorularınız var. Testi bitirmek istediğinizden eminmisiniz ?")) {
finishtest();
} else {
jQuery('#FinishTest').bind('click');
return;
}
}
} else {
alert('Testi bitirebilmek için en az 2 soru cevaplamalısınız.');
}
});

That happen because of the following condition in your code :
if( jQuery(':radio:checked').length < count )
When you select all the answers you will end up by jQuery(':radio:checked').length equals six 6 and the count variable value will be also 6 so the condition will never evaluates to true.
Try to add equal to you condition = so it will be inferior or equal <= :
if( jQuery(':radio:checked').length <= count ){
//Your logic here
}
Hope this helps.
Changed and solved problem.
if (jQuery(':radio:checked').length > 3) {
if (jQuery(':radio:checked').length < count) {
if (confirm("Henüz cevaplanmamış sorularınız var. Testi bitirmek istediğinizden eminmisiniz ?")) {
finishtest();
}
} else {
finishtest();
}
} else {
alert('Testi bitirebilmek için en az 2 soru cevaplamalısınız.');
}

There is no error in your code. Just only condition is wrong in if statement.
I have tested on my browser(chrome) with debug.
enter image description here
I hope it will be help you.

Related

Jquery validation code for not allowed only blank space in textbox

i m looking for code in which for not allowed only blank space... for e.g i have one textbox and i have tried this
$(document).ready(function()
{
$("#mybutton").live('click',function()
{
var txt_family_name=$("#mytextbox").val();
if(txt_family_name =="" || txt_family_name ==null)
{
alert("null");
}
else
{
alert("not null");
}
});
});
this above code i have tried and its not working. so pls help me on that.. on one of my button i m calling this above code
Example : space....with any text -- output should be not null
: space space.... any space without any other text -- output should be null
you can use the length attribute and the trim method to remove the trailing spaces, if any:
$("#mybutton").on('click',function()
{
var length = $.trim($("#mytextbox").val()).length;
if(length == 0)
{
alert("null");
}
else
{
alert("not null");
}
});
See the updated code it's working
$(document).ready(function()
{
$("#clickme").on('click',function()
{
var txt_family_name=$.trim($("#mytextbox").val());
if(txt_family_name ==="" || txt_family_name ===null)
{
alert("null");
}
else
{
alert("not null");
}
});
});
Jquery Validation : require method only check the length of the input. So it allow the blank space.The solution will be the simple change the one line code in it.
required: function( value, element, param ) {
// Check if dependency is met
if ( !this.depend( param, element ) ) {
return "dependency-mismatch";
}
if ( element.nodeName.toLowerCase() === "select" ) {
// Could be an array for select-multiple or a string, both are fine this way
var val = $( element ).val();
return val && val.length > 0;
}
if ( this.checkable( element ) ) {
return this.getLength( value, element ) > 0;
}
return value.length > 0;
}
in above code change value.length to $.trim(value).length
so simply remove the blank space
you can use regexp.
$(document).ready(function() {
$("#mybutton").bind('click', function() {
var txt_family_name = $("#mytextbox").val();
if (txt_family_name.replace(/\s/g, '') == "") {
alert("null");
} else {
alert("not null");
}
});
});
//To add method to remove blankspaces
$.validator.addMethod("blankSpace", function(value) {
return value.indexOf(" ") < 0 && value != "";
});

jquery form validation without click -> when ok show div

is it possible to do this automatically. mean when i type text and click on the second textfield autocheck the first one. then when both ok show the div2 and so on.
here is some code
var step1 = function() {
var first = $("#f_name").val();
var last = $("#l_name").val();
var error = false;
if (first == "") {
$("#f_name").next().text("*ErrorMsg");
error = true;
} else {
$("#f_name").next().text("");
}
if (last == "") {
$("#l_name").next().text("*ErrorMsg");
error = true;
} else {
$("#l_name").next().text("");
}
if (error == false) {
$("#send").submit();
$('#div1').show('slow');
} else {
returnfalse;
}
}
var step2 = function() {
var email1 = $("#e_mail").val();
var adress1 = $("#adress").val();
var error2 = false;
if (email1 == "") {
$("#e_mail").next().text("*ErrorMsg");
error2 = true;
} else {
$("#e_mail").next().text("");
}
if (adress1 == "") {
$("#adress").next().text("*ErrorMsg");
error2 = true;
} else {
$("#adress").next().text("");
}
if (error2 == false) {
$("#send2").submit();
$('#div2').show('slow');
} else {
returnfalse;
}
}
$(document).ready(function() {
$('#div1').hide();
$('#div2').hide();
$("#send").click(step1);
$("#send2").click(step2);
});
hope anyone can help me. and sorry for my bad english :)
greatings
The way that I would do it is:
Assign a variable, something like numSteps and set its initial value to 1
onFocus and onBlur, run a function that steps through each field, based on numSteps
If any fields are empty (or however you want to validate them), set error = true
if !error numSteps++
Make all elements up to numSteps visible
Hope this helps
Very crude example, but demonstrates what I was referring to:
http://jsfiddle.net/aSRaN/

Return through all functions

Is it possible to return through multiple functions?
I have a jQuery on click function with a $.each loop in it. In the $.each loop I test for various conditions, and if not met display an alert message and then return. Here is a cut down version of my code:
$(document).on('click', '.add-to-basket, #add-to-basket', function(e) {
var data = {
id: $(this).data('id'),
quantity: 1
};
if($('#quant').length > 0) {
data.quantity = $('#quant').val();
}
var i = 0;
var j = 0;
if($('.product-option').length > 0) {
$('.product-option').each(function(index, element) {
if($(this).is('select')) {
//check to see if this is a required select, and return if a selection has not been made.
if($(this).data("force") == 1 && $(this).val() == 0) {
AlertDialogue($(this).data("title") + " requires a selection before you can add this product to your basket.", "Required Option");
return;
}
data.opts[i++] = $(this).val();
} else if($(this).is('input[type="checkbox"]:checked')) {
data.opts[i++] = $(this).val();
//check to see if this is a required group of checkboxes, and if so at least one has been checked. If not return.
} else if($(this).is('input[type="checkbox"]')) {
if($(this).data("force") == 1 && $('input[name="' + $(this).prop("name") + '"]:checked').length == 0) {
AlertDialogue($(this).data("title") + " requires at least one option to be checked before you can add this product to your basket.", "Required Option");
return;
}
} else if($(this).is('input[type="radio"]:checked')) {
data.opts[i++] = $(this).val();
} else if($(this).is('textarea')) {
//Check to see if this is a required textarea, and if so make sure there is some text in it.
if($(this).data("force") == 1 && $.trim($(this).val()).length == 0) {
AlertDialogue($(this).data("title") + " requires text before you can add this product to your basket.", "Required Option");
return;
}
if($(this).val().length > 0) {
data.text[j].id = $(this).data("id");
data.text[j++].val = $(this).val();
}
}
});
}
//submit product to the cart
});
However the return will only break that loop of the $.each loop, and start the next loop. I would like to not only break the $.each loop, but return from the on click function entirely.
Is this possible?
If so, how can I achieve this?
To exit from $.each you should return false
To exit from event handler function you should use return
As per your requirement you can do little like below,
var break = false;
$('.product-option').each(function(index, element) {
// rest of code
if(condition) {
break = true;
return false; // this will break out of each loop
}
});
if(break) {
return; // return from event handler if break == true;
}
// rest of code
Check out the docs for jQuery.each():
We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same
as a continue statement in a for loop; it will skip immediately to
the next iteration.
Essentially, use return false; instead of just return;.

How do I fix two bugs for my jQuery form Validation code?

My code basically adds a class error if field is invalid and if the field is valid, the error class is removed and form is submitted normally.
I am having trouble figuring out two small bugs for the form validation code I created.
Bugs listed below:
1) If you enter the correct content within one field, and click submit, the length of the error class does not update on first submit click. It takes two submit clicks for the length to update. (view console.log)
2) If you change the content of the input field and click submit (all works well, error class is removed) BUT if you decide to delete your updated text & leave the field blank, the error class does not get re-applied.
Would be great if I can get some assistance solving this.
Please let me know if anything is unclear.
Thanks in advance:
JSFIDDLE
$('form.requiredFields').submit(function(e) {
var req = $(this).find('.req'),
validateEmail = function(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
};
req.each(function() {
var $this = $(this),
defaultVal = $this.prop('defaultValue'); //cache default val
//checks for validation errors
if ( ( $this.hasClass('email') && !validateEmail( $this.val() ) ) ||
( defaultVal === $this.val() || $this.val() === '' || $this.val().length < 3 )
)
{
$this.addClass('error');
} else {
$this.removeClass('error req');
}
});
console.log(req.length);
if ( req.length === 0 ) {
return true;
} else {
return false;
}
});
Like dc5 said for #2 don't remove the req class.
And for #1 - You're looking for errors (.req) before it is removed.
See this working fiddle. It is an example how your code work but maybe you can find a cleaner solution.
$('form.requiredFields').submit(function(e) {
var req = $(this).find('.req'), errorCheck = 0,
validateEmail = function(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
};
req.each(function() {
var $this = $(this),
defaultVal = $this.prop('defaultValue'); //cache default val
//checks for validation errors
if ( ( $this.hasClass('email') && !validateEmail( $this.val() ) ) ||
( defaultVal === $this.val() || $this.val() === '' || $this.val().length < 3 )
)
{
$this.addClass('error');
} else {
$this.removeClass('error');
}
});
errorCheck = $(this).find('.error');
console.log(errorCheck.length);
if ( errorCheck.length === 0 ) {
return true;
} else {
return false;
}
});
for #2, You are moving the 'req' class as well as the 'error' class when clearing the error. The next time through the call, the input is no longer found through your selector $(this).find('.req')
For #1 - I don't understand the problem as you have described it.
I made it easier for you, actually your code is a mess,
here is a fiddle:
Jsfiddle validate Demo
CODE:
$('#submit_form').click(function() {
var flag = 0;
var count = 0,
total = $(".req").length;
var validateEmail = function(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
$('.req').each(function(){
count++;
if($(this).attr('id')=='email') {
if(!validateEmail($(this).val())){ $(this).addClass('error'); flag = 1; }
else { $(this).removeClass('error'); } }
if($(this).attr('id')=='name') {
if($(this).val().length < 3){ $(this).addClass('error'); flag = 1; }
else { $(this).removeClass('error'); } }
if($(this).attr('id')=='com') {
if($(this).val().length < 3&&$(this).val()!=''){ $(this).addClass('error'); flag = 1; }
else { $(this).removeClass('error'); } }
if ( total==count&&flag<1) { alert('submit'); }
});
});
Validation rules:
name - must be bigger then 2.
email - true on pattern match function.
comment - if typed, must be bigger the 2 chars (just to understand how can it be done).
If this example is not clear or you need more help don't hesitate... I'm bored.

Dynamic if/else statement with jQuery and textarea

So I'm trying to style a <textarea> tag to highlight when it has more than one character typed in. (For a contact form). When someone is filling out the form, the fields will all highlight green to let them know its valid. I'm very new to JS and jQuery in general but I'm pretty sure this is supossed to work. I can use the $('#message').addClass('valid') by itself and it will apply the class, but when I add the if/else statement, nothing works. Here is the script
\\ Begin Highlight Code
var $messageval = $('#message').val()
if ($messageval.length != 0 ){
$('#message').addClass('valid');
}
else ($messageval.length = 0 ){
$('#message').removeClass('valid');
}
});
I've been googling for hours and I can't find anything to dynamically add and remove classes based on a text length variable.
Thanks
You are missing else if
if ($messageval.length != 0 ){
$(this).addClass('valid');
}
else if($messageval.length == 0 ){ //<-- Here
$('#message').removeClass('valid');
}
Basically you can just have
if ($messageval.length != 0 ){
$('#message').addClass('valid');
}
else { //<-- Here
$('#message').removeClass('valid');
}
I guess this is what you are looking for:-
$(function(){
$('#message').on('keyup', function () {
var $messageval = $.trim($(this).val()); //$.trim here to avoid whitespace preventing validation.
if ($messageval.length != 0) {
$(this).addClass('valid'); //this here represent the textarea dom element, and $(this) is the jquery wrapper.
} else {
$(this).removeClass('valid');
}
});
});
Fiddle
$(document).ready(function(){
$("#message").keyup(function(){
var messageval = $('#message').val();
if (messageval.length > 1) {
$('#message').addClass('valid');
} else {
$('#message').removeClass('valid');
}
});
});
change your code to this
$(document).ready(function(){
$('#message').trigger('change');//if you initially want to check the textarea
$('#message').on('change', function(){
var $messageval = $(this).val();
if ($messageval.length != 0 ){
if (!$(this).hasClass("valid")) {
$(this).addClass("valid");
}
}
else ($messageval.length == 0 ){
if ($(this).hasClass("valid")) {
$(this).removeClass("valid");
}
}
});
});
Cheers!

Categories

Resources