How to access the JQuery object - javascript

How do I access the jquery object when validateName is called?
In my code below, errorDate is not a JQuery object.
Correction to variable name
$(document).ready(function() {
var errorDate = $("#errorDate");
errorDate.blur(validateName);
function validateName() {
if (errorDate.val().length == "") {
errorDate.addClass("error");
return false;
}
else {
errorDate.removeClass("error");
return true;
}
}
});

Just use $(this) instead of name.

You can
$(document).ready(function() {
var errorDate = $("#errorDate");
errorDate.blur(validateName);
function validateName() {
var $this = $(this);
if ($this.val().length == "") {
$this.addClass("error");
return false;
}
else {
$this.removeClass("error");
return true;
}
}
});
Or use errorDate instead of name since it is a closure variable
$(document).ready(function() {
var errorDate = $("#errorDate");
errorDate.blur(validateName);
function validateName() {
if (errorDate.val().length == "") {
errorDate.addClass("error");
return false;
}
else {
errorDate.removeClass("error");
return true;
}
}
});

Try this,
$(document).ready(function() {
var errorDate = $("#errorDate");
errorDate.blur(validateName);
function validateName() {
// no need to get length you can use $(this).val()==""
if ($(this).val() == "") {
$(this).addClass("error");
return false;
}
else {
$(this).removeClass("error");
return true;
}
}
});
Fiddle http://jsfiddle.net/jtWFX/

Related

how to convert functions into a JQuery plugin

I want to learn how to write Jquery plugin.This is my normal function and convert it into jquery plugin could you suggest me how to do this.
So that I can easily understand how to convert function to the plugin.
function probe_Validity(element) {
var validate = true;
$(".required-label").remove();
var warnings = {
text: "Please enter Name"
};
element.find(".required").each(function() {
var form_Data = $(this);
if (form_Data.prop("type").toLowerCase() === 'text' && form_Data.val() === '') {
form_Data.after('<div class="required-label">' + warnings.text + '</div>').addClass('required-active');
validate = false;
}
if (validate) {
return true;
} else {
return false;
}
$(function() {
$(".required").on("focus click", function() {
$(this).removeClass('required-active');
$(this).next().remove();
});
});
});
}
Take a look at this project jQuery plugin boilerplate
Consider this as a base plugin definition, look it up, follow the steps and adjust them to your needs.
It's quite easy to do you just use
jQuery.fn.theNameOfYourFunction = function() {}
then you can get the element the function is called on like this :
var element = $(this[0])
so with your function it would be :
jQuery.fn.probe_Validity = function() {
var element = $(this[0]);
var validate = true;
$(".required-label").remove();
var warnings = {
text: "Please enter Name"
};
element.find(".required").each(function() {
var form_Data = $(this);
if (form_Data.prop("type").toLowerCase() === 'text' && form_Data.val() === '') {
form_Data.after('<div class="required-label">' + warnings.text + '</div>').addClass('required-active');
validate = false;
}
if (validate) {
return true;
} else {
return false;
}
$(function() {
$(".required").on("focus click", function() {
$(this).removeClass('required-active');
$(this).next().remove();
});
});
});
};
this can be called like so :
$('#id').probe_Validity ()

How to Improve jquery function

I'm doing a validation and it's working fine, but I have so many repeat code and canĀ“t find a way to improve it. Here is:
function validate( active ){
if( active[0].id === "mod_formSteps-1" ){
var $inputs = $("#formSteps-1 :input:not(:submit)");
var value = true;
$inputs.each(function() {
if( $(this).val().length < 1 || $(this).hasClass("error")){
value = false;
}
});
return value;
}
else if( active[0].id === "mod_formSteps-2" ){
var $inputs = $("#formSteps-2 :input:not(:submit)");
var value = true;
$inputs.each(function() {
if( $(this).val().length < 1 || $(this).hasClass("error")){
value = false;
}
});
return value;
}
...
...
else{
alert("something is wrong");
}
return true;
}
Now I have four if that are the same just change the paramater "mod_formStepsN" and "#formSteps-1".
Something more like this
function validate(active) {
var numb = active.prop('id').split('-').pop(),
inputs = $("#formSteps-"+numb+" :input:not(:submit)"),
value = true;
inputs.each(function () {
if ($(this).val().length < 1 || $(this).hasClass("error")) {
value = false;
}
});
return value;
}
Why not simply:
function validate( active ){
if(active[0].id != "")
{
var $inputs = $("#"+active[0].id+":input:not(:submit)");
var value = true;
$inputs.each(function() {
if( $(this).val().length < 1 || $(this).hasClass("error")){
value = false;
}
});
return value;
}
else{
alert("something is wrong");
}
return true;
}

Validation for fields into form no for all fields

I want after click on button(Click Me), validation check just for field 2-1 and field 2-2 no for all files that has class .required (... .closest('form')...), how is it in my code?
DEMO: (in here when that you click on button it work for all field that have class .required but i want just check field into form closest('form')): http://jsfiddle.net/ZsPyy/2/
function required_valid() {
var result = true;
$('.required').each(function () {
if (!$(this).val()) {
//var cssObj=;
$(this).css("background", "#ffc4c4");
result = false;
}
$(this).keyup(function () {
$(this).css("background", "#FFFFEC");
})
});
return result;
}
$('button').live('click', function (e) {
e.preventDefault();
var passed = true;
//passed = required_selectbox() && passed;
passed = required_valid() && passed;
if (!passed) {
return false;
}
});
Try this code: http://jsfiddle.net/ZsPyy/4/
I have passed the button to the required_valid function. So we can get the btn's parent form.
function required_valid(btn) {
var result = true;
$(btn).closest("form").find('.required').each(function () {
if (!$(this).val()) {
//var cssObj=;
$(this).css("background", "#ffc4c4");
result = false;
}
$(this).keyup(function () {
$(this).css("background", "#FFFFEC");
})
});
return result;
}
$('button').live('click', function(e) {
e.preventDefault();
var passed = true;
//passed = required_selectbox() && passed;
passed = required_valid(this) && passed;
if (!passed) {
return false;
}
});
function required_valid(sbtn) {
var result = true;
$(sbtn).closest("form").children('.required').each(function () {
if (!$(this).val()) {
//var cssObj=;
$(this).css("background", "#ffc4c4");
result = false;
}
$(this).keyup(function () {
$(this).css("background", "#FFFFEC");
})
});
return result;
}
$('button').live('click', function(e) {
e.preventDefault();
var passed = true;
//passed = required_selectbox() && passed;
passed = required_valid(this) && passed;
if (!passed) {
return false;
}
});

Simplify syntax, how to avoid duplicate "if"?

I want to check a form when fields are error and disabling submit button as appropriate. I found a solution that works, but the syntax is ugly. :)
$(document).ready(function() {
$("#send").attr("disabled", "disabled");
$("#validatemail").keyup(function()
{
var email = $("#validatemail").val();
if (email != '')
{
if(isvalidmail(email))
{
// do stuff
}
else
{
// do stuff
}
}
else
{
// do stuff
}
});
$("#validatetitle").keyup(function()
{
var subject = $("#validatetitle").val();
if (subject != '')
{
if ((subject.length < 3) || (subject.length > 30))
{
// do stuff
}
else
{
// do stuff
}
}
else
{
// do stuff
}
});
$("#form_message").live('keyup', function()
{
// Duplicate is not smart!!!
var email = $("#validatemail").val(); // Duplicate
var subject = $("#validatetitle").val(); // Duplicate
if (
(isvalidmail(email)) // Duplicate
&&
(!((subject.length < 3) || (subject.length > 30))) // Duplicate
)
{
$("#send").removeAttr("disabled");
}
else
{
$("#send").attr("disabled", "disabled");
}
});
});
So how to simplify the code?
I spent several hours trying, but it did not work.
Thank you very much.
Regards,
Vincent
Try this.
$(document).ready(function() {
var isEmailValid = false;
var isSubjectValid = false;
$("#send").attr("disabled", "disabled");
$("#validatemail").keyup(function()
{
var email = $("#validatemail").val();
if (email != '')
{
if(isvalidmail(email))
{
// do stuff
isEmailValid = true;
}
else
{
// do stuff
isEmailValid = false;
}
}
else
{
// do stuff
}
});
$("#validatetitle").keyup(function()
{
var subject = $("#validatetitle").val();
if (subject != '')
{
if ((subject.length < 3) || (subject.length > 30))
{
// do stuff
isSubjectValid = true;
}
else
{
// do stuff
isSubjectValid = false;
}
}
else
{
// do stuff
}
});
$("#form_message").live('keyup', function()
{
// now just get all the set values here
$("#send").attr("disabled",(isEmailValid && isSubjectValid) ? "" : "disabled");
});
});
best way is to declare and initialize those variable globally and then use it ...and things which are being repeated in if condition place them in function and call it where you have to check those condition...
Try this:
$(document)
.ready(function () {
$("#send")
.attr("disabled", "disabled"), $("#validatemail")
.keyup(function () {
var a = $("#validatemail")
.val();
a != "" && isvalidmail(a)
}), $("#validatetitle")
.keyup(function () {
var a = $("#validatetitle")
.val();
a != "" && (3 > a.length || a.length > 30)
}), $("#form_message")
.live("keyup", function () {
var a = $("#validatemail")
.val(),
b = $("#validatetitle")
.val();
!isvalidmail(a) || 3 > b.length || b.length > 30 ? $("#send")
.attr("disabled", "disabled") : $("#send")
.removeAttr("disabled")
})
})

How can I fix this error "missing; before statement" in javascript?

How can I fix this error "missing; before statement" in javascript ?
My HTML Page :
http://etrokny.faressoft.com
My Javascript Code :
http://etrokny.faressoft.com/javascript.php
When assigning a function to a variable, you need a semicolon after the function.
Example: var func = function() { return false; };
Put a semicolon after all statements. JavaScript does it automatically for you when you "forget" one at the end of a line**, but since you used a tool to make everything fit on one line, this doesn't happen anymore.
** it should also be happening when a statement is followed by a }, but it's just bad practice to rely on it. I would always write all semicolons myself.
Actually, you know what, since it's so easy, I did it for you:
function getSelected() {
var selText;
var iframeWindow = window;
if (iframeWindow.getSelection) {
selText = iframeWindow.getSelection() + "";
} else if (iframeWindow.document.selection) {
selText = iframeWindow.document.selection.createRange().text;
}
selText = $.trim(selText);
if (selText != "") {
return selText;
} else {
return null;
}
}
$(document).ready(function () {
function scan_selectedText() {
if (getSelected() == null) {
return false;
}
if (getSelected().length < 25) {
return false;
}
$(document)[0].oncontextmenu = function () {
return false;
};
var result = true;
var selected_Text = getSelected();
selected_Text = selected_Text.replace(/ {2,}/g, ' ').replace(/\s{2,}/g, ' ');
$('#content .para').each(function () {
var accepted_text = $.trim($(this).text());
accepted_text = accepted_text.replace(/ {2,}/g, ' ').replace(/\s{2,}/g, ' ');
if (accepted_text.search(selected_Text) > -1) {
result = false;
}
});
var AllAccepted = "";
$('#content .para').each(function () {
var correntDiv = $.trim($(this).text()).replace(/ {2,}/g, ' ').replace(/\s{2,}/g, ' ');
AllAccepted = AllAccepted + correntDiv + " ";
});
if ($.trim(AllAccepted).search(selected_Text) > -1) {
return false;
}
if (!result) {
return false;
}
var body = $.trim($('body').text());
body = body.replace(/ {2,}/g, ' ').replace(/\s{2,}/g, ' ');
var bodyWithoutDivs = body;
$('#content').each(function () {
var correntDiv = new RegExp($.trim($(this).text()).replace(/ {2,}/g, ' ').replace(/\s{2,}/g, ' '), "");
bodyWithoutDivs = bodyWithoutDivs.replace(correntDiv, '');
});
if (bodyWithoutDivs.search(selected_Text) > -1) {
return false;
}
if (body == selected_Text) {
return true;
}
return true;
}
$(document).mousedown(function (key) {
if (key.button == 2) {
if (scan_selectedText() == true) {
$(document)[0].oncontextmenu = function () {
return false;
};
} else {
$(document)[0].oncontextmenu = function () {
return true;
};
}
}
});
var isCtrl = false;
$(document).keyup(function (e) {
if (e.which == 17) isCtrl = false;
}).keydown(function (e) {
if (e.which == 17) isCtrl = true;
if (e.which == 67 && isCtrl == true) {
$("#content2").animate({
opacity: 0
}, 500).animate({
opacity: 1
}, 500);
if (scan_selectedText() == true) {
return false;
} else {
return true;
}
}
});
document.onkeypress = function (evt) {
if (evt.ctrlKey == true && evt.keyCode == 67) {
$("#content2").animate({
opacity: 0
}, 500).animate({
opacity: 1
}, 500);
if (scan_selectedText() == true) {
return false;
} else {
return true;
}
}
};
$('*').bind('copy', function (key) {
if (scan_selectedText() == true) {
return false;
} else {
return true;
}
});
});
First thing, start with the raw human-written version of your javascript, you know, the unminimized non-machine-generated version
After you've fixed you've made sure it is free from syntax errors .... and you minimize it, don't make a mistake when copy/pasting

Categories