Sagi_Avinash_Varma Sagi_Avinash_Varma - 1 year ago 65
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

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

function placeholder(x) {
if (x=="1") {
if (document.getElementById("search_field").value=="") {
else {

<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>

Answer Source

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:



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


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...';