jquery / javascript将文本添加到输入字段中

时间:2012-11-21 04:48:30

标签: javascript jquery placeholder

我有一个使用html5占位符的输入框:

<input type="text" name="website" class="url" required placeholder="enter website">

使用jQuery或直接javascript,我想在焦点上为用户输入的数据添加一个字符串。如果该字段包含的数据多于预设字符串变量(例如http://example.com),则该字段满足我的要求。如果它只包含原始字符串('http://'),则清除输入值并显示占位符。

以下代码适用于我。

var input = $("#processor .url");
var prefix = 'http://';

input.focus(function() {
    if (input.val().indexOf(prefix) == -1) {
        input.val(prefix + input.val());
    }
}).blur(function() {
    if (input.val() == prefix) {
        input.val('');
    }
});

有没有更好的方法来为性能等写这个......,这是我真正的问题吗?

1 个答案:

答案 0 :(得分:-1)

这比看起来更容易。 我根据@Tahir Yasin的评论做了一个演示。

的CSS:

.grey { color:#aaa; }

HTML:

<input type="text" />

jQuery的:

var inputval = "";
$(document).ready(function() {
    // Define your default value to show on input
    $("input[type='text']").val("Enter your link here...");
    // Add grey color or optionally blur effect
    $("input[type='text']").addClass('grey');
    // Save your default value
    inputval = $("input[type='text']").val();
    $("input[type='text']").focusin(function() {
    // if textbox is empty or got the default value
    if ($(this).val() == "" || $(this).val() == inputval) {
        // Clear the box
        $(this).val("http://"); // Your text here..
        // Remove grey color
        $(this).removeClass('grey'); }
    }).focusout(function() {
        // if textbox is empty or just contains your value
        if ($(this).val() == "" || $(this).val() == "http://" ) {
            // Put your Default value back
            $(this).val(inputval);
            // Add grey color
            $(this).addClass('grey'); }
    });
});

小提琴:http://jsfiddle.net/BerkerYuceer/TgZ8L/

我只是喜欢在动作的everystep上使用jQuery。但是你可以看到我的代码比你的代码更少,所以你已经使用了最多的方法。

这是基于您的代码的演示: http://jsfiddle.net/BerkerYuceer/qbLyD/

你可以自己看到差异几乎相同,但显然你的代码更快。