val() returns Placeholder value instead of the actual value in IE8,9 when the field is empty
17,642
Solution 1
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())
});
Solution 2
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.
Related videos on Youtube
Author by
user1184100
Updated on November 02, 2022Comments
-
user1184100 over 1 year
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(''); } }) }); } }
-
Felix Kling almost 12 yearsAnd what's the question?
-
-
Luka almost 12 yearswhat if someone decides to write what the placeholder says?
-
Thomas almost 12 yearsThen it's replaced. Or do you think it might be something useful? As long as you choose a good placeholder text it shouldn't happen
-
Luka almost 12 yearsi just think its a problem that it can happen, its not that important to me i just think that one should always attempt to make code that cant create problems for the user and i see a potential of problems here. But again thats just my opinion and i don't really have any interest in the question.