I'm using jquery placeholder text for a search placeholder. This search field doesn't have any placeholder so i added this text.
$(document).ready(function(){
$('.mfilter-search').find("input[type=text]").each(function(ev)
{
if(!$(this).val()) {
$(this).attr("placeholder", "Refine Your Search");
}
});
});
i don't know it's the best way to add a placeholder using jquery. If anyone know more simple way please add your code it will be very helpful.
You can directly set the placeholder
no need to check value
and use .each()
$('.mfilter-search input[type=text]').attr("placeholder", "Refine Your Search")
If you want to place on first then use
$('.mfilter-search input[type=text]:first').attr("placeholder", "Refine Your Search")
您可以使用value
属性简单地使用find
方法
$('.mfilter-search').find("input[type=text][!value]").attr("placeholder", "Refine Your Search");
you can add placeholder attribute directly in your html element like this
<input type="text" name="fname" placeholder="search">
or you can add a class to all your element that you need to put placeholder eg:- .placeholder
and add placeholder attribute in javascript like this.
$(".placeholder").attr("placeholder", "Type here to search");
or you can use plugins like these. http://andrewrjones.github.io/jquery-placeholder-plugin/ or https://github.com/mathiasbynens/jquery-placeholder or refer this site for different placeholder plugins. https://www.sitepoint.com/top-5-jquery-html5-placeholder-plugins/
and your code is also good. We can do that way too. hope this will work.
Try this code
$(document).ready(function(){
$('.mfilter-search').find("input[type=text]").each(function(ev)
{
var txt = $(this).data('placeholder');
$(this).attr('placeholder', txt);
});
});
对于占位符,jquery中不需要复杂的方法函数,只需使用这样的方法
<input type="text" placeholder = "Zipcode" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Zipcode'" name="zipcode" class="form-control" maxlength='10'>
try this. this is how you can add place holder
if you have two input fields
with same class name
.
<!DOCTYPE html> <html> <head> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> </head> <style type="text/css"> </style> <body> first name :<input type="text" name="firstname" class="tfield" id="field0"> last name :<input type="text" name="lastname" class="tfield" id="field1"> </body> <script type="text/javascript"> $(document).ready(function(){ var thelength = $(".tfield").length; for(var i=0;i<thelength;i++) { var theid = $("#field"+i); var thename = theid.attr("name"); alert(thename); if(thename == "firstname") { theid.attr("placeholder","name"); } } }); </script> </html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.