I’m new to jQuery, I’ve followed a few tutorials about writing fn functions and my first one worked; however when I add a second fn function the entire script stops working. I’d appreciate any feedback or solutuion to my problem. I’ve included my jQuery and also the HTML form I’m using.
At it’s current form it’s solely meant to stop the page refreshing when the user presses “Submit” however since adding “jQuery.fn.clear” it’s stopped doing this.
$(document).ready(function () {
// Length validation
jQuery.fn.validate = function (clength, value) {
if ($.trim($(this).val()).length < clength || $.trim($(this).val()) == value) {
$(this).val("You can't leave this blank!");
return false;
} else {
return false;
}
};
// Default value validation
jQuery.fn.clear = function () {
var value = $.trim($(this).val());
if (value == "You can't leave this blank" || value == "Name" || value == "Email Address"
value == "Telephone") {
$(this).val("");
}
};
$(function () {
$(".submit-button").click(function () {
$("#send-name").validate(1, "Name");
$("#send-mail").validate(6, "Email Address");
$(".spinny").fadeTo(0, 1);
$(this).attr('value', 'Validating...');
return false;
});
});
});
<form method="POST" action="">
<div class="left">
<label for="name">What's your name?</label>
<input type="text" id="send-name" name="name"
id="name" class="watermark" size="40" value="Name" />
<br />
<label for="email">Your Email</label>
<input type="text" id="send-mail" name="email" size="40"
class="watermark" Value="Email Address" />
<br />
<label for="number">Your contact number</label>
<input type="text" id="send-number" name="number"
size="40" class="watermark" value="Telephone" />
<br />
</div>
<div class="right">
<label for="message">How can I help?</label>
<textarea name="message" id="message" class="watermark"
cols="40" rows="10" title="Message"></textarea>
<br />
<Br />
<img src="_img/spinny.gif" class="spinny" />
<input type="submit" class="submit-button" value="Submit" />
</div>
</form>
You forgot
});before$(function () {.You also forgot an
||beforevalue == "Telephone"Actually, simply remove
$(function () {– there is no reason to begin a new document-ready block when you already have one!Some other suggestions to improve your code:
$(this).attr('value'is bad. Always use.val()to get/set the value of an element.jQuerymore than once. If you want your code to be compatible with$.noConflict(), change the first line like this:jQuery(document).ready(function($){