So i’m trying to make a function, that sets / removes the watermark in an field, i have gotten this working, where the input html elements looks like this:
<input type="text" name="pollName" id="pollName" value="DD-MM-YYYY" onfocus="javascript: watermark(this,true,'DD-MM-YYYY')" onblur="javascript: watermark(this,false,'DD-MM-YYYY')" >
This however is painfully long, and i’m trying to move the code to javascript, where i intend to use this code:
function watermark(dom,isFocus,watermark)
{
if(isFocus)
{
if(dom.value === watermark)
{
dom.value = "";
}
}
else if(!isFocus)
{
if(dom.value === '')
{
dom.value = watermark;
}
}
}
document.ready(function(){
$('#addOption').click(addOption);
$('.dateSelector').focusin(watermark(this,1,'DD-MM-YYYY'));
$('.dateSelector').focusout(watermark(this,0,'DD-MM-YYYY'));
});
Here is the HTML in question.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>SPS: Create a new poll</title>
<link href="styles/stylePollCreator.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript" src="js/jsPollCretor.js"></script>
</head>
<body>
<div id="pollSetup">
<form action="" method="post">
<label for="pollName:">Poll name</label>
<input type="text" name="pollName" id="pollName" />
<br />
<label for="startDate">Start date: </label>
<br />
<input type="text" id="startDate" name="startDate" class="dateSelector" value="DD-MM-YYYY"/>
<label for="endDate">End date: </label>
<input type="text" id="endDate" name="endDate" class="dateSelector" value="DD-MM-YYYY"/>
<br />
<div id="pollOptions">
</div>
<input id="submitNewPoll" value="Create poll" type="submit" />
</form>
<button id="addOption">Add option</button>
</div>
</body>
</html>
The addOption function is working fine, however the watermark function seems to call once when the site first loads, and then no more :/
thankyou for your time 🙂
focusinandfocusoutexpect functions for arguments, and you are technically passingundefined, since watermark isn’t returning anything. In other words, you are passing the result ofwatermark, notwatermarkitself.So, you want to do this:
EDIT:
I agree with the comment above that you should be using the placeholder attribute. So, your input would look like this:
Keep in mind that this is a HTML5 attribute, so for old browsers, you’ll have to use a polyfill, but if you google placeholder polyfill, you’ll find a million polyfills that you can use.