Kevin Bosman
Kevin Bosman

Reputation: 110

Only one class value changing

I currently use a textfield to change text inside my html.

My textfield:

  Voornaam:
  <h3 class="title1">Kevin</h3>
  <input type="text" id="myTextField1" />
  <br/><br/>

When done typing text, press the button:

  <input type="button" id="myBtn" value="Change" />

Which triggers this function:

document.querySelector('#myBtn').addEventListener('click', function change() {
  function isInvalid(input) {
    return input.value.length == 0;
  }

  var titles = [...document.querySelectorAll('[class^="title"]')];
  var inputs = [...document.querySelectorAll('[id^="myTextField"]')];
  var anchor = document.querySelector('#myLink');

  if (inputs.some(isInvalid)) {
    alert('Write some real text please.');

    anchor.href = 'convert.php';
  } else {
    var querystring = inputs.map((input, index) => `var${index + 1}=${titles[index].textContent = input.value}`);
//    $('.title'+index).html(input.value);

    anchor.href = `convert.php?${querystring.join('&')}`;
  }
});

The value above the textfield:

<h3 class="title1">Kevin</h3>

does change and this is good, however it requires to be changed somewhere else aswell. And this one does not seem to change.. The other one that should be changed is:

  <p class="title1">Test.</p><p class="title2">Achternaam</p>

class title one should also be changed here although that does not happen.

Could anybody tell me what I'm doing wrong?

Upvotes: 0

Views: 61

Answers (1)

Nico Van Belle
Nico Van Belle

Reputation: 5146

From the code you have provided, the mistake you make is that you have an array of 1 input elements: #myTextField1

You loop this array of 1 via map to change the the title array (an array of 3 or so from what I can tell). But the thing is, because the input array only has index 0, you will also only change the first element of the titles array.

Now that I completely understand the code, here is a possible fix. You basically want to do the title selector once you know the index of the elements you are searching for.

  var inputs = [...document.querySelectorAll('[id^="myTextField"]')];
  var querystring = inputs.map((input) => {
      // Remove all leading non-digits to get the number
      var number = input.id.replace( /^\D+/g, '');

      var titles = [...document.querySelectorAll('.title'+ number)];
      titles.forEach((title) => title.innerHTML = input.value);
      return `var${number}=${input.value}`;
  });

Also, instead of depending on the clean luck of the indexes given to you by the querySelectorAll (when element with id 'myTextField1' is not the first to be found in the DOM, you are screwed), I now take the number from the id string value instead => variable number.

Check here for a working fiddle example.

Upvotes: 1

Related Questions