Pedrinbeep
Pedrinbeep

Reputation: 43

Change innerHTML individually from multiple text-field with same ID from multiple span

I'm trying to get the value form a multiple span and change multiple text-field. All have the same ID and Class and they should change it individually, every text-field with their span in order. I can't change the HTML, only the javascript. This JSFiddle show that for now I only can change all at the same time with the first span. Thank you:

http://jsfiddle.net/1q95yk6f/

HTML:

   <textarea class="field-element" id="iText" aria-required="true">Change TEXT 1</textarea>
<div class="iSpan">
    <span><span>Text 1</span>
    </span>
</div>

<textarea class="field-element" id="iText" aria-required="true">Change TEXT 2</textarea>
<div class="iSpan">
    <span><span>Text 2</span>
    </span>
</div>

<textarea class="field-element" id="iText" aria-required="true">Change TEXT 3</textarea>
<div class="iSpan">
    <span><span>Text 3</span>
    </span>
</div>


<br> <button type="button" onclick="Change();">Click Me!</button>

Javascript:

function Change () {
var items = document.getElementById( 'iText' );
 var divs = document.getElementsByClassName( 'iSpan' );

[].slice.call( divs ).forEach(function ( div ) {
    div.innerHTML = items.value;
});
}

Upvotes: 0

Views: 143

Answers (1)

A Haworth
A Haworth

Reputation: 36512

The problem is that each textarea has the same id so this cannot be used as a normal selector - in most browsers it will just give the first one.

One way of selecting given the code in the question is to use textarea.field-element as in this snippet - with a little extra checking that we are getting the right ones by checking that the textarea and the div are next to each other (siblings).

function Change () {
  let divs = document.getElementsByClassName( 'iSpan' );
  let textareas = document.querySelectorAll('textarea.field-element');
  let items = [];
  let k = 0;
  for (let i = 0; i < textareas.length; i++) {
    if ( divs[k] == textareas[i].nextElementSibling) { items[k] = textareas[i]; k++; }
  }
 
  if (divs.length != items.length) { alert('The number of divs does not match the number of textareas'); }
  else {
    for (let j = 0; j < divs.length; j++) {
       divs[j].innerHTML = items[j].value;
    }
  }
}
   <textarea class="field-element" id="iText" aria-required="true">Change TEXT 1</textarea>
<div class="iSpan">
    <span><span>Text 1</span>
    </span>
</div>

<textarea class="field-element" id="iText" aria-required="true">Change TEXT 2</textarea>
<div class="iSpan">
    <span><span>Text 2</span>
    </span>
</div>

<textarea class="field-element" id="iText" aria-required="true">Change TEXT 3</textarea>
<div class="iSpan">
    <span><span>Text 3</span>
    </span>
</div>


<br> <button type="button" onclick="Change();">Click Me!</button>

Upvotes: 1

Related Questions