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;.
Related
if ($('<input/>').length == 0) {
T.stop();
}
the above is how I create the timer stop function.
This is where the part of the code has been placed:
$.map(exercise.syllables, function (syllable, j) {
if (!syllable || !syllable.trim().length) {
// If it doesn't exist or is an empty string, return early without creating/appending elements
return;
}
var innerSylCol = $('<div/>', {
class: 'col-md-3 inputSyllables'
});
var sylInput = $('<input/>', {
'type': 'text',
'class': 'form-control syl-input',
'name': +c++,
'id': +idsyll++
}).on('blur', function() {
var cValue = $(this).val();
if(cValue === "") {
return;
}
if (cValue === syllable) {
correctSylls.push(cValue);
console.log(correctSylls);
}
if (exercise.syllables.length === correctSylls.length) {
$(this).closest('.syll-row').find('input.syl-input').each(function () {
$(this).replaceWith(getCorrectBtn($(this).val()))
});
S.addRight();
S.playRight();
} else if (cValue !== syllable){
// $(this).css({'color':'#e00413'});
S.playWrong();
S.addWrong();
}
});
innerSylCol.append(sylInput);
sylRow.append(innerSylCol);
});
idsyll = 0;
sylCol.append(sylRow);
exer.append(colLeft, sylCol);
exerciseArea.append(exer);
});
return exerciseArea;
if ($('<input/>').length == 0) {
T.stop();
}
}
The loop creates inputs based on words in my array, the inputs change to buttons when the inserted data is correct. I am trying to create it such that when the length of the inputs becomes 0 (so there are no input fields left, only buttons) it will stop the timer.
Two problems:
This code:
if ($('<input/>').length == 0) {
creates an input element, which is put in a jQuery wrapper, and then checks the number of elements in the wrapper. So the condition will always be false, because the length will always be 1. To search for input elements, remove the < and />: $("input")
You need to run that code in response to some condition (perhaps within the timer itself?) that might make $("input").length 0 by removing all input elements. Your quoted code is incomplete, but it doesn't seem like that check is being done later or in response to some event where inputs may have been removed.
I wrote a custom JavaScript validator that needs to run on every keyup event that is attached to ever input and runs the vacillator() for every input field.
Problem is that it only works on load.
I want to to work on every key-up event.
Here is a jsfiddle https://jsfiddle.net/vo1npqdx/717/
function display_error(elem, message) {
elem.insertAdjacentHTML('afterend', "<label class='js-error' style='color:red;' >" + message + "</label>");
}
function check_error(elem) {
error_label = elem.nextElementSibling
if (error_label && error_label.classList.contains('js-error')) {
return true;
}
}
function add_error(elem,message) {
if (!check_error(elem)){
display_error(elem, message)
}
}
function delete_error(elem) {
if (check_error(elem)){
elem.nextElementSibling.remove();
}
}
function validateForm(elem) {
alert("Checking if form is vaild")
// If input type == text
if (elem.getAttribute("type") == 'text') {
//alert("elemcent is text")
maxlength = elem.getAttribute("maxlength")
minlength = elem.getAttribute("minlength")
data_error = elem.getAttribute("data-error")
// if has attribute maxlegnth
if (minlength) {
// if value is under min length
if (elem.value.length < parseInt(minlength)) {
// add errors
add_error(elem, data_error)
//alert("above min length")
} else {
// Delete
//alert("delere errror")
delete_error(elem)
}
}
}
// if input type == number
if (elem.getAttribute("type") == 'number') {
//alert("element is text")
max = elem.getAttribute("max")
min = elem.getAttribute("min")
data_error = elem.getAttribute("data-error")
// if has attribute maxlegnth
if (min) {
// if value is under min length
if (elem.value < parseInt(min)) {
// add errors
add_error(elem, data_error)
//alert("Belove Min Number")
}
else if(elem.value > parseInt(max)){
// add errors
add_error(elem, data_error)
//alert("above Max number")
}
else {
// Delete
//alert("delere errror")
delete_error(elem)
}
}
}
}
// Desired Result
// if keyup
// for input in inputs:
// someFunc(input) that makes input tags red
var inputs = document.getElementsByClassName('form-control');
for(var i=0;i<inputs.length;i++){
elem = inputs[i]
elem.addEventListener('keyup', validateForm(elem))
}
You are calling your event handler straight away. It needs to be wrapped with a function. So this:
elem.addEventListener('keyup', validateForm(elem))
should be:
elem.addEventListener('keyup', function(event) {
// do something with event
validateForm(this);
});
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.
I've checked the related questions on stack overflow, but can't seem to find an answer to my predicament. I'm trying to use a plugin for javascript (Tag it! - Tag Editor) and I need to find a way to call one of its functions "create_choice()" EDIT: at some point after it has been initiated. Is there a way after calling :
$tagit = $("#mytags").tagit();
that I can then call something like
$tagit.create_choice('test123');
Here is a link for the example :
http://levycarneiro.com/projects/tag-it/example.html
Below is the code from the plugin if it is any help
(function($) {
$.fn.tagit = function(options) {
var el = this;
const BACKSPACE = 8;
const ENTER = 13;
const SPACE = 32;
const COMMA = 44;
// add the tagit CSS class.
el.addClass("tagit");
// create the input field.
var html_input_field = "<li class=\"tagit-new\"><input class=\"tagit-input\" type=\"text\" /></li>\n";
el.html (html_input_field);
tag_input = el.children(".tagit-new").children(".tagit-input");
$(this).click(function(e){
if (e.target.tagName == 'A') {
// Removes a tag when the little 'x' is clicked.
// Event is binded to the UL, otherwise a new tag (LI > A) wouldn't have this event attached to it.
$(e.target).parent().remove();
}
else {
// Sets the focus() to the input field, if the user clicks anywhere inside the UL.
// This is needed because the input field needs to be of a small size.
tag_input.focus();
}
});
tag_input.keypress(function(event){
if (event.which == BACKSPACE) {
if (tag_input.val() == "") {
// When backspace is pressed, the last tag is deleted.
$(el).children(".tagit-choice:last").remove();
}
}
// Comma/Space/Enter are all valid delimiters for new tags.
else if (event.which == COMMA || event.which == SPACE || event.which == ENTER) {
event.preventDefault();
var typed = tag_input.val();
typed = typed.replace(/,+$/,"");
typed = typed.trim();
if (typed != "") {
if (is_new (typed)) {
create_choice (typed);
}
// Cleaning the input.
tag_input.val("");
}
}
});
tag_input.autocomplete({
source: options.availableTags,
select: function(event,ui){
if (is_new (ui.item.value)) {
create_choice (ui.item.value);
}
// Cleaning the input.
tag_input.val("");
// Preventing the tag input to be update with the chosen value.
return false;
}
});
function is_new (value){
var is_new = true;
this.tag_input.parents("ul").children(".tagit-choice").each(function(i){
n = $(this).children("input").val();
if (value == n) {
is_new = false;
}
})
return is_new;
}
function create_choice (value){
var el = "";
el = "<li class=\"tagit-choice\">\n";
el += value + "\n";
el += "<a class=\"close\">x</a>\n";
el += "<input type=\"hidden\" style=\"display:none;\" value=\""+value+"\" name=\"item[tags][]\">\n";
el += "</li>\n";
var li_search_tags = this.tag_input.parent();
$(el).insertBefore (li_search_tags);
this.tag_input.val("");
}
};
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
};
})(jQuery);
I've created a working example at http://jsfiddle.net/nickywaites/DnkBt/ but it does require making changes to the plugin.
Change
$.fn.tagit = function(options) { ...
to
$.fn.tagit = function(options,callback) { ...
Add
if (callback && typeof callback == 'function') {
callback();
}
after
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
};
Now you can call a function of your choice right after the tagit call:
$tagit = $("#mytags").tagit(yourOptions, function(){
alert('hi')!
});
You can try to add
return this;
right after the function create_choice block. tagit will return itself and you can call make_choice or any function contained in .fn.tagit
I have created a form with malsup's Form Plugin wherein it submits on change of the inputs. I have set up my jQuery script to index drop down menus and visible inputs, and uses that index to determine whether keydown of tab should move focus to the next element or the first element, and likewise with shift+tab keydown. However, instead of moving focus to the first element from the last element on tab keydown like I would like it to, it moves focus to the second element. How can I change it to cycle focus to the actual first and last elements? Here is a live link to my form: http://www.presspound.org/calculator/ajax/sample.php. Thanks to anyone that tries to help. Here is my script:
$(document).ready(function() {
var options = {
target: '#c_main',
success: setFocus
};
$('#calculator').live('submit', function() {
$(this).ajaxSubmit(options);
return false;
});
$(this).focusin(function(event) {
var shiftDown = false;
$('input, select').each(function (i) {
$(this).data('initial', $(this).val());
});
$('input, select').keyup(function(event) {
if (event.keyCode==16) {
shiftDown = false;
$('#shiftCatch').val(shiftDown);
}
});
$('input, select').keydown(function(event) {
if (event.keyCode==16) {
shiftDown = true;
$('#shiftCatch').val(shiftDown);
}
if (event.keyCode==13) {
$('#captured').val(event.target.id);
} else if (event.keyCode==9 && shiftDown==false) {
return $(event.target).each(function() {
var fields = $(this).parents('form:eq(0),calculator').find('select, input:visible');
var index = fields.index(this);
var nextEl = fields.eq(index+1).attr('id');
var firstEl = fields.eq(0).attr('id');
var focusEl = '#'+firstEl;
if (index>-1 && (index+1)<fields.length) {
$('#captured').val(nextEl);
} else if(index+1>=fields.length) {
if ($(this).val() != $(this).data('initial')) {
$('#captured').val(firstEl);
} else {
event.preventDefault();
$(focusEl).focus();
}
}
return false;
});
} else if (event.keyCode==9 && shiftDown==true) {
return $(event.target).each(function() {
var fields = $(this).parents('form:eq(0),calculator').find('select, input:visible');
var index = fields.index(this);
var prevEl = fields.eq(index-1).attr('id');
var lastEl = fields.eq(fields.length-1).attr('id');
var focusEl = '#'+lastEl;
if (index<fields.length && (index-1)>-1) {
$('#captured').val(prevEl);
} else if (index==0) {
if ($(this).val() != $(this).data('initial')) {
$('#captured').val(lastEl);
} else {
event.preventDefault();
$(focusEl).select();
}
}
return false;
});
}
});
});
});
function setFocus() {
with (document.calculator)
var recap = document.getElementById(recaptured.value);
if (recap!=null) {
setTimeout(function() {
if (recap.getAttribute('type')=='text') {
recap.select();
} else {
recap.focus();
}
}, 100 );
}
}
Edit #1: I made a few minor changes to the code, which has brought me a little closer to my intended functionality of the script. However, I only made one change to the code pertaining to the focus: I tried to to disable the tab keydown when pressed on the last element (and also the shift+tab keydown on the first element) in an attempt to force the focus on the element I want without skipping over it like it has been doing. This is the code I added:
$(this).one('keydown', function (event) {
return !(event.keyCode==9 && shiftDown==true);
});
This kind of works. After the page loads, If the user presses tab on the last element without making a change to its value, the focus will be set to the second element. However, the second time the user presses tab on the last element without making a change to its value, and every subsequent time thereafter, the focus will be set to the first element, just as I would like it to.
Edit #2: I replaced the code in Edit #1, with code utilizing event.preventDefault(), which works better. While if a user does a shift+tab keydown when in the first element, the focus moves to the last element as it should. However, if the user continues to hold down the shift key and presses tab again, focus will be set back to the first element. And if the user continues to hold the shift key down still yet and hits tab, the focus will move back to the last element. The focus will shift back and forth between the first and last element until the user lifts the shift key. This problem does not occur when only pressing tab. Here is the new code snippet:
event.preventDefault();
$(focusEl).focus();
You have a lot of code I didn't get full overview over, so I don't know if I missed some functionality you wanted integrated, but for the tabbing/shift-tabbing through form elements, this should do the work:
var elements = $("#container :input:visible");
var n = elements.length;
elements
.keydown(function(event){
if (event.keyCode == 9) { //if tab
var currentIndex = elements.index(this);
var newIndex = event.shiftKey ? (currentIndex - 1) % n : (currentIndex + 1) % n;
var el = elements.eq(newIndex);
if (el.attr("type") == "text")
elements.eq(newIndex).select();
else
elements.eq(newIndex).focus();
event.preventDefault();
}
});
elements will be the jQuery object containing all the input fields, in my example it's all the input fields inside the div #container
Here's a demo: http://jsfiddle.net/rA3L9/
Here is the solution, which I couldn't have reached it without Simen's help. Thanks again, Simen.
$(document).ready(function() {
var options = {
target: '#c_main',
success: setFocus
};
$('#calculator').live('submit', function() {
$(this).ajaxSubmit(options);
return false;
});
$(this).focusin(function(event) {
$('#calculator :input:visible').each(function (i) {
$(this).data('initial', $(this).val());
});
return $(event.target).each(function() {
$('#c_main :input:visible').live(($.browser.opera ? 'keypress' : 'keydown'), function(event){
var elements = $("#calculator :input:visible");
var n = elements.length;
var currentIndex = elements.index(this);
if (event.keyCode == 13) { //if enter
var focusElement = elements.eq(currentIndex).attr('id');
$('#captured').val(focusElement);
} else if (event.keyCode == 9) { //if tab
var newIndex = event.shiftKey ? (currentIndex - 1) % n : (currentIndex + 1) % n;
var el = elements.eq(newIndex);
var focusElement = el.attr('id');
if ($(this).val() != $(this).data('initial')) {
$('#captured').val(focusElement);
} else if ((currentIndex==0 && event.shiftKey) || (currentIndex==n-1 && !event.shiftKey)) {
event.preventDefault();
if (el.attr('type')=='text') {
$.browser.msie ? "" : $(window).scrollTop(5000);
el.select().delay(800);
} else {
$.browser.msie ? "" : $(window).scrollTop(-5000);
el.focus().delay(800);
}
} else if (el.is('select')) {
event.preventDefault();
if (el.attr('type')=='text') {
el.select();
} else {
el.focus();
}
}
}
});
});
});
});
function setFocus() {
with (document.calculator)
var recap = document.getElementById(recaptured.value);
if (recap!=null) {
setTimeout(function() {
if (recap.getAttribute('type')=='text') {
recap.select();
} else {
recap.focus();
}
}, 1 );
}
}
I put my files available to download in my live link: http://www.presspound.org/calculator/ajax/sample.php