自定义jQuery插件返回val() [英] Custom jQuery plugin return val()

查看:135
本文介绍了自定义jQuery插件返回val()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的jquery插件,如果字段为空(文本框的水印),则将灰色"文本放入文本框.问题是,当我提交表单并且尝试获取文本框的值时,它将返回水印文本而不是空字段.

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.

水印文本等于"title"属性,所以我可以做类似的事情,但是我不想为表单中的每个文本框都这样做:

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
}

理想情况下,这将是我插件的一部分,当我调用.val()时它将返回一个空字符串 有关如何执行此操作的任何建议?

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?

推荐答案

对于我制作的自定义水印/占位符插件,我有类似的东西.我只要在onclick(您的表单的提交按钮)上处理它,然后遍历所有内容即可.

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.

更新了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();

这篇关于自定义jQuery插件返回val()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆