placeholder with the same label name

Asked

Viewed 59 times

-2

How do I get the placeholder to pick the same name that’s on my label ?

I’m doing it this way:

<label for="sing_pass" class="label_pass"><span class="lang" key ="Text33">Code Activation</span></label>
                          <input type="text" id="sing_pass" class="input" placeholder="Code Activation ">

I would like the placeholder to change whenever the label changes.

  • Only with Html, impossible, need Javascript for this.

2 answers

4

You can do this via Jquery, it would look something like this. Functional example: https://jsfiddle.net/fj3x7sgq/1/

<label for="sing_pass" class="label_pass">
    <span class="lang" key ="Text33">Label</span>
    <input type="text" id="sing_pass" class="input">
    </label>


   <script> 
     $(document).ready(function() {
         var place = $('.label_pass').find('.lang').text();
         $('#sing_pass').attr('placeholder', place)
       }); 
   </script> 

2


You need to use Javascript for this. As the attribute for points to the id of input, you can change the placeholder field picking up the text from label where the for of the first is equal to id of the second.

The code below will go through all label, take the value of for, search for an element that has the id equal to the value of for and apply the placeholder with the text of label:

const labels = document.querySelectorAll("label[for]")
for(let i of labels){
   let el = document.getElementById(i.getAttribute("for"));
   if(el) el.placeholder = i.textContent;
}
<label for="sing_pass" class="label_pass"><span class="lang" key ="Text33">Code Activation</span></label>
<input type="text" id="sing_pass" class="input">

<label for="teste" class="label_pass"><span class="lang" key ="Text33">Qualquer coisa</span></label>
<input type="text" id="teste" class="input">

If it’s just one element, it’s simpler:

document.getElementById("sing_pass")
.placeholder = document.querySelector("[for='sing_pass']").textContent;
<label for="sing_pass" class="label_pass"><span class="lang" key ="Text33">Code Activation</span></label>
<input type="text" id="sing_pass" class="input">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.