7

I can put a placeholder through jQuery if there is a single <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 multiple <input> fields in a single page as below:

<input type="text" class="first">
<input type="text" class="second">

I wish to add a placeholder only on the first <input type="text"> that has class="first".

How can I add a placeholder to the first matching text input only?

0

5 Answers 5

3
$('input[type=text].first').attr('placeholder', 'hello' );

Here input will select all the input tag, [type=text] will select input whose type is text and then .first will select a subset with class first.

If you want to select the first input with first class then do $('input[type=text].first').first()

Sign up to request clarification or add additional context in comments.

Comments

1

I wish to add a placeholder only on the first that has class="first".

How can I add a placeholder to the first matching text input only?

Try using document.querySelector() with 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">

Comments

1
$('input[type=text].first').attr('placeholder', 'hello' );

using the class selector

Comments

1

You can try this solution:
$('input[type=text].first').attr('placeholder', 'hello' );

Comments

0

if you want an element specific script, use ID instead of CLASS for better performance.

<input type="text" class="first" id="first">

$("#first").attr('placeholder', 'hello' );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.