Adding placeholder attribute using Jquery
Asked Answered
A

4

29

I have a simple problem. I just want to add a placeholder on an input. Here's the code:

HTML:
<input type="text" name="link" class="hidden">

JQuery:
var link = document.querySelector('.link');
    link.style.display='block';
    link.classList.remove('hidden');
    if(val === 1)  // for a movie
        link.classList.add('placeholder="Add Movie Title. ."');
    else  // for an external link
        link.classList.add('placeholder="Add External Link . ."');

As you can see, the placeholder doesn't work because the syntax is wrong. I searched related solutions to my problem but they use a different method like this

$("").attr("placeholder", "Type here to search");});

but I need something that is similar to what I used with adding style, but I'm not sure if there's other way to do it. Is there a similar way?

Araminta answered 31/7, 2014 at 2:5 Comment(1)
The first code is pure JavaScript, the second is with jQuery.Tussis
C
61

You just need this:

$(".hidden").attr("placeholder", "Type here to search");

classList is used for manipulating classes and not attributes.

Caustic answered 31/7, 2014 at 2:8 Comment(1)
so there's no other way to use the var link to put a placeholder?something like link.attr?Araminta
T
15

This line of code might not work in IE 8 because of native support problems.

$(".hidden").attr("placeholder", "Type here to search");

You can try importing a JQuery placeholder plugin for this task. Simply import it to your libraries and initiate from the sample code below.

$('input, textarea').placeholder();
Twandatwang answered 31/7, 2014 at 3:52 Comment(0)
B
4

Try something like the following if you want to use pure JavaScript:

document.getElementsByName('link')[0].placeholder='Type here to search';
Behoove answered 31/7, 2014 at 2:14 Comment(0)
M
0

you just need to put this

($('#{{ form.email.id_for_label }}').attr("placeholder","Work email address"));
($('#{{ form.password1.id_for_label }}').attr("placeholder","Password"));
Macpherson answered 18/5, 2020 at 7:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.