开发者

Displaying text in HTML field without submitting text

I have an HTML form where I have two fields: username and password.

Now, I want th开发者_StackOverflow社区at "Username" and "Password" appear inside the fields to indicate the users what to put in. Currently I'm assigning these using the value= option, however if I submit the form, "Username" and "Password" get submitted too.

Is there a clean way how to make the text appear without including it in the submit if the submit is clicked.

Thanks! Krt_Malta


Ok, this is basically how I do it. I place the labels inside the fields, then when the page loads, I store the labels in a hidden manner using .data(). When the form gets submitted, if it contains the same thing as in .data(), then I clear it (or you could disallow submission if you want the field to be filled)

$(document).ready(function(){

    // this will make sure we always remember what the values were:
    $("form.myform input[type='text']").each(function(){
        // I like to add a class as well, so I can make the label text in a lighter color
        if ($(this).val().length > 0) {
            $(this).data('label', $(this).val()).addClass('label');
        }

    });

    // this will clear the text when the input receives focus:
    $("form.myform input[type='text']").focus(function(){
        if ($(this).data('label') == $(this).val()) {
            $(this).val('').removeClass('label');
        }
    });

    // this will make sure the fields don't get submitted like that, but won't stop 
    // the form from being submitted....
    $("form.myform").submit(function(){
        $(this).find("input[type='text']").each(function(){
        if ($(this).val() == $(this).data('label')) {
            $(this).val('');
        }
    });
});

I haven't run this or tested in a browser, but in theory this should work (I've done this before)

Also, we're not filling the box with the label text again, once it's lost focus if the user didn't edit the text....


In HTML5, this feature is provided and is called a placeholder. Otherwise you typically use a Javascript library.


Just don't include it in your php/asp script with which you submit the form.

--edit--

Just re-read your question. I think you mean that people are just coming onto the page and clicking submit while the default values are in there, yeah?

If you use validation (javascript or php/asp) to disallow submission of 'username' and 'password' for these fields they won't be allowed to submit the form without changing the values within.

Is that the kind of thing you meant?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜