0

I can not understand Javascript language properly, I am trying to write inside placeholder but it is not working, here is my code

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>val demo</title>

  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>

  <script type="text/javascript">
        $(document).ready(function() {
            $('#myInputText').keyup(function() {
             $('#myOutputText2').val('placeholder="' + $(this).val() + '"');
             $('#myDIVTag').html('<b>' + $(this).val() + '</b>');
            });
        });     
    </script>

</head>
<body>

<input id="myInputText" type="text" name="post_title" size="79" placeholder="Enter title here" />
<p>Snippet Preview: <a href="#" id="myDIVTag"></a></p>
<input name="textfield2" type="text" id="myOutputText2" size="79" />


</body>
</html>

It is work perfectly but I want this in to placeholder mode. Please help me.

Amita
  • 944
  • 1
  • 8
  • 20
Asif Uz Zaman
  • 337
  • 1
  • 14

1 Answers1

2

To change an attribute, use attr() like

$('#myOutputText2').attr('placeholder',$(this).val());

Update

Since placeholder is a native HTML DOM property of input elements, it is better to use prop()

$('#myOutputText2').prop('placeholder',$(this).val());

For further reading, see .prop() vs .attr()

Community
  • 1
  • 1
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
  • Ok sir please wait I try that – Asif Uz Zaman Jun 22 '15 at 20:14
  • This is not really correct - since a long time ago, the `.prop()` method should be used for setting DOM element properties, not `.attr()`. – Pointy Jun 22 '15 at 20:16
  • @Pointy, do you mean `prop` should be used for all attributes? I thought it was for only `checked`, `disabled`, etc.... – AmmarCSE Jun 22 '15 at 20:17
  • @AmmarCSE: OK SIR IT IS WORKING PROPERLY – Asif Uz Zaman Jun 22 '15 at 20:20
  • @AmmarCSE: THANK YOU, SIR – Asif Uz Zaman Jun 22 '15 at 20:20
  • @Pointy, this http://api.jquery.com/prop/ indicates that `prop` should be used with properties like `tagName, selectedIndex, nodeName` or boolean attributes – AmmarCSE Jun 22 '15 at 20:21
  • @AmmarCSE in my opinion `.prop()` should be used for properties that are directly exposed as properties on native DOM elements. Without jQuery, you (probably? I hope) wouldn't use `.setAttribute()` to set the value of things like that, so you should use `.prop()` in jQuery. – Pointy Jun 22 '15 at 20:21
  • @AmmarCSE note that "placeholder" is a native DOM node property (in modern browsers that support "placeholder" at all), just like "nodeName", "tagName", etc. – Pointy Jun 22 '15 at 20:22
  • @Pointy, thank you very much for clarifying this for me! – AmmarCSE Jun 22 '15 at 20:33