javascriptjquerydom

How can we set default text like Watermark text for input element of type file


I used a function in Javascript as given below and my Html tag looks like

<input id="TestId" type="text" />

JavaScript:

$('#TestId').blur(function() {
    if ($(this).val().length == 0) {
        $(this).val('Please enter').addClass('Watermark');
    }
}).focus(function () {
    if ($(this).val() == 'Please enter') {
        $(this).val('').removeClass('Watermark');
    }
}).val('Please enter').addClass('Watermark');

I works as expected if the type of Html element is text, it's not working if type of element is file. Please help me


Solution

  • You may use a hidden file input and a placeholder element to recreate the desired effect. I have made a quick example on jsfiddle http://jsfiddle.net/WAtuj/

    Take a look at how you may trigger the file change event:

    $("span").click(function () {
        $("input:file").trigger("click");
    });
    $("input:file").change(function () {
        var fileName = $(this).val();
        $("span").text(fileName);
    });
    

    A more detailed and complex solution can be found here: http://www.onextrapixel.com/2012/12/10/how-to-create-a-custom-file-input-with-jquery-css3-and-php/

    Also an appropriate solution would be just to wrap your input field with a span element and try to create a dead simple placeholder label using :after and :before pseudoclasses