问题
I created a simple jquery plugin that puts 'greyed out' text into a textbox if the field is blank (watermark for textboxes). The problem is when i submit the form and i'm trying to get the value of the text box, it's returning the watermark text instead of an empty field.
The watermark text is equal to the "title" attribute, so i could do something like this, but i'd hate to do this for EVERY textbox in my form:
if ($("#textboxid").val() == $("#textboxid").attr("title")) {
//default, return empty string
} else {
//user entered this
}
Ideally, this would be part of my plugin and it would return an empty string when i call .val() Any suggestions on how to do this?
回答1:
I have something like this for my custom made watermark/placeholder plugin i've made. I just handle it onclick (the submit button for your form) and then loop through everything.
Updated jsFiddle DEMO
(function ($, window, document, undefined) {
$.fn.myCustomVal = function () {
return $(this).each(function () {
var _self = $(this),
_watermark = _self.attr('title');
_self.attr('data-watermark', 'on');
_self.val(_self.attr('title'));
_self.on('focus', function () {
$(this).val('');
});
_self.on('blur', function () {
$(this).val(_watermark);
});
});
};
$(function () {
// change this class here to whatever you want
$('.btnSubmit').on('click', function () {
$('input:text[data-watermark]').each(function () {
if ($(this).val() == $(this).attr("title")) {
$(this).val('');
}
});
// now validate / submit / whatnot
alert('submitted!');
});
});
}(jQuery, window, document));
// ************************
// Initiate plugin
$('input:text').myCustomVal();
回答2:
Try an approach like this: http://jsfiddle.net/aVhMh/3/
The logic is also not very general: your plugin would be not useful if the user WANTS to input the exact watermark value. I know it's a very unlikely case but it would be more elegant to account that.
$("input[type=text]").addClass("watermark");
$("input[type=text]").each(function() {
$(this).val($(this).attr("title"));
});
$("input[type=text]").on("focus", function() {
if ($(this).hasClass("watermark")) {
$(this).removeClass("watermark").val("");
}
});
$("input[type=text]").on("blur", function() {
if ($(this).val() == "") {
$(this).val($(this).attr("title")).addClass("watermark");
}
});
$("form").on("submit", function() {
$("input[type=text].watermark").val("");
$(this).submit();
});
回答3:
I accepted mcpDesigns answer because it got me on the right path, but wasn't quite what I was looking for. I ended up adding the following to the plugin to create a function called "ActualVal()" that returned the correct value:
$.fn.ActualVal = function () {
if (this.val() == this.attr(opts.attrName)) {
return "";
} else {
return this.val();
}
}
So when instead of getting the value using val(), i get the value by using .ActualVal(). Much cleaner and dynamic than coding around specific buttons =)
Thanks guys!
来源:https://stackoverflow.com/questions/11891568/custom-jquery-plugin-return-val