hide validation error when an input receives focus - javascript

Here is the code:
- here i've declared my variables:
var first = $('#first');
var firstError = $('#firsterror'); // the errors are in span tags (if it matters)
// and so on...
first.blur(validateFirst);
last.blur(validateLast);
username.blur(validateUsername);
password.blur(validatePassword);
confpassword.blur(validateConfpassword);
month.blur(validateMonth);
day.blur(validateDay);
year.blur(validateYear);
gender.blur(validateGender);
$('#myForm').submit(function(){
if( validateFirst() & validateLast() & validateUsername() & validatePassword() & validateConfpassword() & validateMonth() & validateDay() & validateYear() & validateGender() ){
return true;
}else{
return false;
}
});
function validateFirst(){
if(first.val().length < 5){
first.addClass('error_input');
firstError.text('You left this empty!');
firstError.addClass('error');
return false;
}else{
first.removeClass('error_input');
firstError.text('');
return true;
}
};
// and so on... I would like the code to work as so: When an input recives focus the error should hide else the code should run exactly as it is.
thank you..

I think you should use jQuery validate lib to validate your form here is cdn link of jQuery validate..
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
Note that you have to include jQuery lib before that line
All you have to do is just write few lines of code as below
$('#form_id').validate({
rules : {
'el_name' : 'validation_rule' // like, required
},
messages : {
'el_name' : 'Your error message'
}
});

Try this
$('.error_input').focus(function(){
$(this).removeClass('.error_input');
});

did you try something like this already?
function removeError() {
$(this).removeClass('error_input');
$("#error"+$(this).attr("id")).text("").removeClass("error");
}
first.focus(removeError);
last.blur(removeError);
username.blur(removeError);
....

Related

Jquery: SyntaxError: function statement requires a name

Hello stackovlerflow,
function delete() {
if ($.('#deleted').value=="0") {
$.("#deleted").val('1');
$.("#deletedBtn").removeClass('btn-danger');
$.("#deletedBtn").addClass('btn-success');
$.("#deletedBtn").html("Delete user");
} else {
$.("#deleted").val('0');
$.("#deletedBtn").removeClass('btn-success');
$.("#deletedBtn").addClass('btn-danger');
$.("#deletedBtn").html("Revoke deletion");
}
}
Tis function throws me
SyntaxError: function statement requires a name functions.js:1:9
Google doesn`t help, so I hope you can help me!
Thanks alot
//Cripi
delete is a reserved word in JavaScript - see List of reserved words in JavaScript
Your code could look like this:
function fun() {
var deleted = $("#deleted");
var deletedBtn = $("#deletedBtn");
if (deleted.val() === "0") {
deleted.val('1');
deletedBtn.removeClass('btn-danger');
deletedBtn.addClass('btn-success');
deletedBtn.html("Delete user");
} else {
deleted.val('0');
deletedBtn.removeClass('btn-success');
deletedBtn.addClass('btn-danger');
deletedBtn.html("Revoke deletion");
}
}
You cannot use delete as a method name since it is reserved in javascript.
Also you might want to use a variable to avoid duplication in your code:
function deleteAction() {
$btn = $('#deleted');
if ($btn.value=="0") {
$btn.val('1');
$btn.html("Delete user");
} else {
$btn.val('0');
$btn.html("Revoke deletion");
}
$btn.toggleClass("btn-danger btn-success");
}

Better jQuery Embed Code validation (user input via textarea)

I'm working on a site where users can paste in embed codes from the likes of twitter, youtube, instagram, facebook, etc. The Embed code is validated and saved if valid.
The users can then see and edit the code and this is where some code fails validation. E.g. Twitter embed codes may contain < (aka '<') in the post name/text. When pasting in the code originally it passes validation as it contains <, but when displaying the code back to the user the browser shows < in the textarea and this is then submitted if the user clicks save. Our validation function treats this as the start of a tag and the validation fails.
Possible solution 1:
Better validation. The validation we use now looks like this It basically finds the tags (by looking for '<' etc) and checks that each open tag has a closing tag. There must be a better/standard/commonly used way:
(function($) {
$.validateEmbedCode = function(code) {
//validating
var input = code;
var tags = [];
$.each(input.split('\n'), function (i, line) {
$.each(line.match(/<[^>]*[^/]>/g) || [], function (j, tag) {
var matches = tag.match(/<\/?([a-z0-9]+)/i);
if (matches) {
tags.push({tag: tag, name: matches[1], line: i+1, closing: tag[1] == '/'});
}
});
});
if (tags.length == 0) {
return true;
}
var openTags = [];
var error = false;
var indent = 0;
for (var i = 0; i < tags.length; i++) {
var tag = tags[i];
if (tag.closing) {
// This tag is a closing tag. Decide what to do accordingly.
var closingTag = tag;
if (isSelfClosingTag(closingTag.name)) {
continue;
}
if (openTags.length == 0) {
return false;
}
var openTag = openTags[openTags.length - 1];
if (closingTag.name != openTag.name) {
return false;
} else {
openTags.pop();
}
} else {
var openTag = tag;
if (isSelfClosingTag(openTag.name)) {
continue;
}
openTags.push(openTag);
}
}
if (openTags.length > 0) {
var openTag = openTags[openTags.length - 1];
return false;
}
return true
};
}
Possible solution 2:
Encode the text containing '<' (i.e. textLine.replace(/</g, '<')) without encoding tags like <blockquote class="...>.
I've been experimenting with something like:
$(widget.find("textarea[name='code']").val()).find('*')
.each(function(){
// validate $(this).text() here. Need to get text only line by
// line as some elements look like <p>some text <a ...>text
// </a>more text etc</p>
});
Possible solution 3:
Display < as < and not < in the browser/textarea. We use icanhaz for templating (much like moustache).
Using date.code = '<' with <textarea name="code">{{{code}}}</textarea> in the template does not work, neither does {{code}}.
So I played some more and the following works, but I am still interested in suggestions for better embed code validation or better answers.
After the edit form (inc textarea) code is created using the icanhaz template (i.e. after widget = ich.editEmbedWidgetTemplate(encoded_data);) I do the following to encode instances of < etc into < etc. ' has to be encoded manually using replace.
var embedCode = '';
$( widget.find("textarea[name='code']").val() )
.filter('*')
.each(function(){
embedCode += this.outerHTML.replace(/'/g, ''');
});
widget.find("textarea[name='code']").val(embedCode);

Cannot run function

Important note so people don't get caught out (like I did): This may look like jQuery, but it is not.
Honestly, I should've known better. I use $ for stuff other than jQuery. Oh well. Lesson learned! ~Niet the Dark Absol
Code :
(HTML):
<html>
<head>
<script src="selector.js"></script>
</head>
<body>
<label id="id">A label</label>
<script>
$("label #id").clicked(function(){
alert("ASDASD");
});
</script>
</body>
</html>
(JS):
/*
NAME : SELECTOR.JS
*/
function $(attr){
// Removed space in front of the variable
while(attr.charAt(0) == " "){
attr = attr.substr(1);
if(attr == ""){
return 0;
}
}
// Completed the query
if(attr.length > 1){
return Array.prototype.slice.call(document.querySelectorAll(attr));
}else{
if(attr.length == 1){
return new Object(document.querySelector(attr));
}else{
return null;
}
}
}
Object.prototype.clicked = function(script){
if(typeof(this) == "object"){
if(this.constructor == Array){
for(var i = 0; i < this.length; i++){
this[i].onclick = script;
}
}else{
if(this.constructor == Object){
console.log("SINGLE OBJECT : " + this);
console.log("SINGLE OBJECT : ONCLICK : " + this);
this.onclick = script;
}else{
console.log("ERROR : this.constructor is not 'Object' or 'Array'.");
return null;
}
}
}else{
console.log("ERROR : typeof(this) is not 'Object'.");
return null;
}
return this;
};
When I clicked the label, I cannot get the alert box seen.
What should I do? The file name is selector.js, for the js file.
I need the function to be ran. Pls help!
I think this is the minimized code.
The space is wrong, instead of $("label #id") it needs to be $("label#id"). With the space between label and #id you're searching for an element inside a label with id="id", without the space you're searching for a label with id="id".
The function
.clicked()
you used, is not a valid jQuery function. The one you are looking for is:
$( "#target" ).click(function() {
alert( "Handler for .click() called." );
});
See here:
http://api.jquery.com/click/

Jquery Array. How to display array elements that match if statements at once?

This is my script:
<script>
$('.change_password_button').click(function() {
var error = [];
if (!$('.password').val()) {
error[0] = "Current password field is empty.";
}
if (!$('.new_password').val()) {
error[1] = "New password field is empty.";
}
if (!$('.confirm_password').val()) {
error[2] = "Confirm password field is empty.";
}
if ($('.new_password').val() != $('.confirm_password').val()) {
error[3] = "Your new password and confirm password fields do not match.";
}
for (var i = 0; i < error.length; i = i + 1) {
$('#errors').show();
$('#errors').html(error[i]);
}
});
</script>
I wanna to display all errors which occurs at once, but right now it just display one error message. Thanks in advance for your answers.
You have multiple problems.
Problem 1: First what happens to index zero if there is no error? It is undefined.
Solution: Use push, do not set an index.
Problem 2: Second, you are just setting the innerHTML in a loop so you keep overriding it.
Solution: Join the array
Problem 3: You val() checks will not work,
Solution: You need to check the length
$('.change_password_button').click(function(){
var error = [];
if (!$('.password').val().length) {
error.push("Current password field is empty.");
};
if (!$('.new_password').val().length) {
error.push("New password field is empty.");
};
if (!$('.confirm_password').val().length) {
error.push("Confirm password field is empty.");
};
if ($('.new_password').val() != $('.confirm_password').val()) {
error.push("Your new password and confirm password fields do not match.");
};
if(error.length) {
$('#errors').html( error.join("<br/>").show();
} else {
$('#errors').hide();
}
}
Try error.join('') instead of iterating and updating the element
$('.change_password_button').click(function () {
var error = [];
if (!$('.password').val()) {
error.push("Current password field is empty.");
};
if (!$('.new_password').val()) {
error.push("New password field is empty.");
};
if (!$('.confirm_password').val()) {
error.push("Confirm password field is empty.");
};
if ($('.new_password').val() != $('.confirm_password').val()) {
error.push("Your new password and confirm password fields do not match.");
};
$('#errors').show();
$('#errors').html(error.join(''));
});
If you want to use the looping then append the html instead of overriding it
var $errors = $('#errors').empty()
for (var i = 0; i < error.length; i = i + 1) {
$errors.append(error[i]);
}
$errors.show();
Rather than over-write your HTML each time, start appending:
var current = $('#errors').html();
$('#errors').html( current + " " + error[ i ] );
Appending a ul of errors may be more appropriate, but this will get you started.
To answer the question: you overwrite the HTML of the #errors element for every error, so it ends up displaying only the last error. You need to append every error message to the previous one.
You could do as tymeJV suggests, but that requires to fetch the HTML of that div every time the loop runs. jQuery already provides append functionality out of the box, so why not use that? The jQuery team put a lot of effort into it.
...
$('#errors').show(); // Notice I moved this statement. Once it is shown, you do not need to show it again.
for (var i = 0; i < error.length; i = i + 1) {
$('#errors').append(error[i]); // .append() instead of .html().
}
...
note that .html():
When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content.
so you always replace the content of #errors from error[0] to error[length-1],only with one error message at any time.
i suggest use .append():
The .append() method inserts the specified content as the last child of each element in the jQuery collection

Javascript for Zip Code validation

I'm attempting to have Javascript validate a user-entered zip code.
If it is within the list of valid zip codes, it should take them to a new page to schedule an appointment. If the zip code isn't in the listing, it should display a message that says that it isn't covered by the service area and then keep them on the page.
I have it working to where it takes them to the appointment page if it's valid, but it also takes them to the appointment page if it isn't valid.
Would you guys mind helping me figure this out?
Here is the page the Javascript is running on: http://platinumfactoryservice.com/service-area/
Below is the code:
<script type = "text/javascript">
function checkZip() {
var z = document.myform.zip;
var zv = z.value;
if (!/^\d{5}$/.test(zv)) {
alert ("Please enter a valid Zip Code");
document.myform.zip.value = "";
myfield = z; // note myfield must be a global variable
setTimeout('myfield.focus(); myfield.select();' , 10); // to fix bug in Firefox
return false;
}
var codes = [26003,26030,26031,26032,26035,26036,26037,26038,26039,26040,26041,26058,26059,26060,26062,26070,26074,26075,43713,43716,43718,43719,43747,43750,43757,43759,43768,43773,43778,43902,43905,43906,43909,43912,43913,43915,43916,43917,43927,43928,43933,43934,43935,43937,43938,43939,43940,43941,43942,43943,43947,43948,43950,43951,43952,43953,43963,43967,43971,43972,43977,43985,15004,15017,15018,15019,15021,15025,15028,15031,15034,15035,15045,15046,15047,15053,15054,15055,15056,15057,15060,15064,15071,15078,15081,15082,15088,15102,15104,15106,15108,15110,15112,15116,15120,15122,15123,15126,15127,15129,15131,15132,15133,15134,15135,15136,15137,15139,15140,15142,15143,15145,15146,15147,15148,15201,15202,15203,15204,15205,15206,15207,15208,15209,15210,15211,15212,15213,15214,15215,15216,15217,15218,15219,15220,15221,15222,15223,15224,15225,15226,15227,15228,15229,15230,15231,15232,15233,15234,15235,15236,15237,15239,15240,15241,15242,15243,15244,15250,15251,15252,15253,15254,15255,15257,15258,15259,15260,15261,15262,15264,15265,15267,15268,15270,15272,15274,15275,15276,15277,15278,15279,15281,15282,15283,15286,15289,15290,15295,15301,15312,15317,15321,15323,15339,15340,15342,15350,15361,15363,15365,15367,15376,15378,15379,15347,15330,23705,23703,23707,23708,23704,23709,23702,23701,23326,23328,23327,23322,23325,23320,23324,23323,23321,23520,23519,23541,23512,23551,23515,23529,23506,23501,23514,23521,23518,23502,23503,23505,23513,23509,23504,23508,23511,23517,23510,23507,23523,23459,23458,23450,23479,23471,23466,23467,23465,23463,23461,23451,23460,23456,23452,23455,23454,23453,23462,23464,23457,23261,23291,23260,23225,23221,23249,23222,23223,23241,23232,23224,23290,23173,23298,23273,23274,23289,23279,23282,23276,23278,23295,23219,23218,23220,23269,23286,23292,23293,23285,23284,23228,23227,23226,23229,23075,23231,23230,23294,23289,23060,23059,23075,23288,23242,23238,23250,23233,23255,23150,23058,23234,23831,23235,23237,23236,23836,23114,23112,23113,23297,23832,23120,23838,23801,23803,23804,23805,23806,23834,23111,15004,15017,15018,15019,15021,15025,15028,15031,15034,15035,15045,15046,15047,15053,15054,15055,15056,15057,15060,15064,15071,15078,15081,15082,15084,15088,15102,15104,15106,15108,15110,15112,15116,15120,15122,15123,15126,15127,15129,15131,15132,15133,15134,15135,15136,15137,15139,15140,15142,15143,15145,15146,15147,15148,15201,15202,15203,15204,15205,15206,15207,15208,15209,15210,15211,15212,15213,15214,15215,15216,15217,15218,15219,15220,15221,15222,15223,15224,15225,15226,15227,15228,15229,15230,15231,15232,15233,15234,15235,15236,15237,15239,15240,15241,15242,15243,15244,15250,15251,15252,15253,15254,15255,15257,15258,15259,15260,15261,15262,15264,15265,15267,15268,15270,15272,15274,15275,15276,15277,15278,15279,15281,15282,15283,15286,15289,15290,15295,15301,15312,15317,15321,15323,15339,15340,15342,15350,15361,15363,15365,15367,15376,15378,15379,15347,15330,43711,43717,43722,43723,43724,43725,43732,43736,43772,43778,43779,43780,43788,25504,25510,25526,25537,25541,25545,25559,25571,25701,25702,25703,25704,25705,25706,25707,25708,25709,25710,25711,25712,25713,25714,25715,25716,25717,25718,25719,25720,25721,25722,25723,25724,25725,25726,25727,25728,25729,25755,25770,25771,25772,25773,25774,25775,25776,25777,25778,25779,41101,41102,41105,41114,41129,41139,41169,41183,45619,45619,45623,45638,45645,45669,45675,45680,25011,25026,25033,25070,25082,25109,25112,25124,25143,25156,25159,25168,25177,25213,25334,25338,25357,25375,25389,25560,25569,25003,25015,25025,25035,25039,25045,25054,25061,25064,25067,25071,25075,25079,25083,25086,25102,25103,25107,25110,25126,25132,25134,25160,25162,25201,25202,25214,25301,25302,25303,25304,25305,25306,25309,25311,25312,25313,25314,25315,25317,25320,25321,25322,25323,25324,25325,25326,25327,25328,25329,25330,25331,25332,25333,25335,25336,25337,25339,25350,25356,25358,25360,25361,25362,25364,25365,25387,25392,25396,15001,15003,15005,15009,15010,15026,15027,15042,15043,15050,15052,15059,15061,15066,15074,15077,15081,16123,16136,16101,16102,16103,16105,16107,16108,16112,16115,16116,16117,16120,16121,16123,16132,16140,16141,16142,16143,16146,16148,16150,16155,16156,16157,16159,16160,16161,16172,44401,44403,44405,44406,44416,44418,44420,44422,44424,44425,44429,44430,44436,44437,44438,44440,44442,44443,44446,44451,44452,44454,44470,44471,44473,44481,44482,44483,44484,44485,44486,44488,44501,44502,44503,44504,44505,44506,44507,44509,44510,44511,44512,44513,44514,44515,44555,44619,44672,16001,16002,16003,16016,16017,16018,16020,16021,16022,16023,16024,16025,16027,16029,16030,16033,16034,16035,16037,16038,16039,16040,16041,16045,16046,16048,16050,16051,16052,16053,16055,16056,16057,16059,16061,16063,16066,15006,15007,15014,15015,15024,15030,15032,15037,15044,15049,15051,15065,15075,15076,15086,15090,15091,15101,15144,15238,44609,44701,44702,44703,44704,44705,44706,44707,44708,44709,44710,44711,44714,44718,44720,44720,44721,44730,44730,44735,44750,44767,44799,44601,44646,44647,44648,44608,44613,44614,44626,44630,44632,44640,44641,44643,44650,44652,44657,44662,44666,44669,44670,44685,44688,44689,44056,44067,44087,44203,44210,44216,44221,44222,44223,44224,44232,44232,44236,44237,44250,44260,44262,44264,44278,44286,44301,44302,44303,44304,44305,44306,44307,44308,44309,44310,44311,44313,44314,44315,44316,44317,44319,44320,44321,44325,44326,44328,44333,44334,44334,44372,44396,44398,44632,44685,44280,44256,44254,44281,44273,44258,44274,44233,44215,44235,44251,44253,44212,44282,44275,44240]; // add as many zip codes as you like, separated by commas (no comma at the end)
var found = false;
for (var i=0; i<codes.length; i++) {
if (zv == codes[i]) {
found = true;
break;
}
}
if (!found) {
alert("Sorry, the Zip Code " + zv + " is not covered by our business");
return false;
//do nothing
} else {
alert("The Zip Code " + zv + " is covered by our service team. Please press okay to go forward to schedule an appointment");
document.myform.submit();
}
}
</script>
Change onsubmit="checkZip()" to onsubmit="return checkZip()", because right now your form is always submitted.

Categories

Resources