Prasita Mukherjee Prasita Mukherjee - 1 month ago 8
HTML Question

Update placeholder by id using jQuery

I have an input field in html which is created 'dynamically' in a function say :

'<input id="id1'+var1+'" name="id1" type="text" placeholder="Provide IP"/>'


In the same function in javascript, I'm trying to change the placeholder text by :

$("#id1"+var1).attr("placeholder",arr[i]);


It doesn't work!!The array arr also gets updated in the function
Also further options like :

$("#id1"+var1).attr("placeholder",arr[i]).blur();
$("#id1"+var1).attr("placeholder",arr[i]).placeholder();
$("#id1"+var1).attr("placeholder",arr[i]).val("").focus().blur();


doesn't work. It is retaining previous placeholder text only!! How to resolve this? I'm using Google Chrome

Answer

Your are missing to do the change after the dom is loaded. Try this:

$(document).ready(function(){
  $("#id1").attr("placeholder","IP changed"); 
})

$(document).ready(function() {
  var i = 0;
  var j = i - 1
  var myArray = ["firts text", "second text", "and so on"]
  $("#button").click(function() {
    if (i > 2) {
      i = 0;
    }
    $('input').each(function() {
      if ($(this).attr('placeholder') == "Provide IP" || $(this).attr('placeholder') == myArray[j]) {
        $(this).attr("placeholder", myArray[i]);
        return false;
      }
    })
    i++;
    j++;
    if (j > 2) {
      j = i - 1;
    }
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="id1" name="id1" type="text" placeholder="Provide IP" />
<input type="button" id="button" value="Click me" />

Comments