Demian
Demian

Reputation: 546

Use div element's text as placeholder with jQuery

I have an odd problem/challenge. A plugin I use doesn't use real placeholders for their input fields, but instead it uses div elements below the input fields and, now it comes, they call that placeholders, very strange.

So I would like to manipulate this with some jQuery, this is for me a new level, so I have tried the first steps. What I would like to see is that the div element's text is being used as the actual placehoder of the input. I can obviously call every input with a new attribute and remove the div, but that makes 20 lines of coding for each individual input, I would like to have 1 solution. There are 2 consistent HTML structures for all input fields:

html

<div class="ps-form__field ">
    <input type="email" name="email" id="email" class="ps-input email" >
    <div class="ps-form__field-desc lbl-descript">email address</div>
</div>

<div class="ps-form__field">
    <div class="ps-form__field-inner">
        <input type="text" value="" id="profile_field_name" data-id="name" class="ps-input">
    </div>
    <div class="ps-form__field-desc lbl-descript">First name</div>
</div>

It's this class .ps-form__field-desc that I would like to see as the placeholder for the input.

my jQuery attempt

var txtph = jQuery('.ps-form__field-desc').parents().each().text();
if ( jQuery('.ps-form__field > div').length ) {
    jQuery('.ps-form__field > input').each().attr('placeholder', txtph);
    jQuery('.ps-form__field-desc').remove();
}

I am aware above has likely many mistakes, but this is for me new.

Upvotes: 0

Views: 268

Answers (1)

You could use this:

$(document).ready(function() {
  $('.ps-form__field input').attr("placeholder",function() {
    return $(this).closest(".ps-form__field").find('.lbl-descript').text()
  });
  $('.lbl-descript').remove()
});

It will select each input and set the placeholder attribute to the corrosponding .lbl-descript's text

Working demo

$(document).ready(function() {
  $('.ps-form__field input').attr("placeholder", function() {
    return $(this).closest(".ps-form__field").find('.lbl-descript').text()
  });
  $('.lbl-descript').remove()
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ps-form__field ">
  <input type="email" name="email" id="email" class="ps-input email">
  <div class="ps-form__field-desc lbl-descript">email address</div>
</div>

<div class="ps-form__field">
  <div class="ps-form__field-inner">
    <input type="text" value="" id="profile_field_name" data-id="name" class="ps-input">
  </div>
  <div class="ps-form__field-desc lbl-descript">First name</div>
</div>

Upvotes: 2

Related Questions