Sagi_Avinash_Varma Sagi_Avinash_Varma - 4 months ago 20
Javascript Question

Function with input not working

I have written a function for placeholder functionality of an input field. It works if I write the on/off functions separately, but it's not working when keeping an input variable and

if
construct. Please help regarding what's wrong in syntax or logic.

function placeholder(x) {
if (x=="1") {
if (document.getElementById("search_field").value=="") {
document.getElementById("placeholder").style.display="inline";
}
}
else {
document.getElementById("placeholder").style.display="none";
document.getElementById("search_field").focus();
}
}





<input id="search_field" type="text" value="" onfocus="placeholder(0);" onblur="placeholder(1);">
<span id="field_def" onclick="placeholder(0);" >
<img src="mag.jpg">
<p id="placeholder">Search</p>
</span>

Answer

You can just use the placeholder attribute. It is accepted by all major modern browsers and will save you from adding extra HTML tags and JavaScript code.

<input type="text" name="someName" placeholder="Some Text">


Following is the alternative for old browsers where placeholder is not recognized:

DEMO

HTML:

<input id="search_field" type="text" value="Enter keywords..." onfocus="ph(1);" onblur="ph(0);" onclick="ph(1);">

JavaScript:

function ph(x) {
    var txtSearch = document.getElementById("search_field");
    if (x == 1) {
        if (txtSearch.value == "Enter keywords...") {
            txtSearch.value = '';
        }
    }
    else {
        if (txtSearch.value == "") {
            txtSearch.value = 'Enter keywords...';
        }
    }
}
Comments