Place placeholder using jQuery / Javascript
I can put a placeholder through jQuery if there is one <input> on the page:
<input type="text"/> $(document).ready(function() { placeholders(); function placeholders() { $('input[type=text]').each(function() { $(this).attr('placeholder', 'hello' ); }); } }); However, I have several <input> fields on the same page, as shown below:
<input type="text" class="first"> <input type="text" class="second"> I want to add a placeholder only to the first <input type="text"> , which has class="first" .
How to add placeholder only to the first matching input text?
I want to add a placeholder only on the first that has class = "first".
How can I add placeholder only to the first matching text input?
Try using document.querySelector() with the selector "input[type=text][class=first]" , setAttribute()
function placeholders() { document.querySelector("input[type=text][class=first]") .setAttribute("placeholder", "hello"); } $(document).ready(placeholders); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <input type="text" class="first"> <input type="text" class="second"> $('input[type=text].first').attr('placeholder', 'hello' ); Here, input will select all the input tag , [type=text] will select an input whose type is text, and then .first will select a subset with the first class.
If you want to select the first input with the first class, then do $('input[type=text].first').first()
$('input[type=text].first').attr('placeholder', 'hello' ); using class selector
You can try this solution:$('input[type=text].first').attr('placeholder', 'hello' );
if you need a specific script element, use ID instead of CLASS for better performance.
<input type="text" class="first" id="first"> $("#first").attr('placeholder', 'hello' );