Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

val() returns Placeholder value instead of the actual value in IE8,9 when the field is empty

Placeholder attribute shown below works fine in firefox but if val() is called when the field is empty it returns the placeholder value instead of the actual value in the text.

JSFiddle - http://jsfiddle.net/Jrfwr/2/

<input id="tlt" type="text" placeholder="Enter Title" />

JSCode

function placeHolderFallBack() {
   if ("placeholder" in document.createElement("input")) {
       return;
   }
   else {
       $('[placeholder]').focus(function () {
           var input = $(this);
           if (input.val() == input.attr('placeholder')) {
               input.val('');
               input.removeClass('placeholder');
           }
       }).blur(function () {
           var input = $(this);
           if (input.val() == '' || input.val() == input.attr('placeholder')) {
               input.addClass('placeholder');
               input.val(input.attr('placeholder'));
           }
       }).blur();
       $('[placeholder]').parents('form').submit(function () {
           $(this).find('[placeholder]').each(function () {
               var input = $(this);
               if (input.val() == input.attr('placeholder')) {
                   input.val('');
               }
           })
       });
   }
}
like image 332
user1184100 Avatar asked Jun 26 '12 13:06

user1184100


2 Answers

You could override the val() method but I don't like doing that :D

I wrote a simple pVal() function which does the job

$.fn.pVal = function(){
    var $this = $(this),
        val = $this.eq(0).val();
    if(val == $this.attr('placeholder'))
        return '';
    else
        return val;
}
$(function(){
    alert($('input').val())
    alert($('input').pVal())
});​

http://jsfiddle.net/W7JKt/3/

like image 50
Thomas Avatar answered Oct 21 '22 06:10

Thomas


In your JSFiddle code you get the value of the textbox in a BUTTON CLICK event... and your code that checks if the current value of the textbox is equal to the placeholder executes in the FORM SUBMIT event.

So... the problem is that the BUTTON's CLICK event executes before the FORM's SUBMIT event.

This code shows an example of how to get the correct value

Hope that helps.

like image 42
Daniel Avatar answered Oct 21 '22 06:10

Daniel