Kevin Bosman
Kevin Bosman

Reputation: 110

Only one value passing to another php page

I've been trying to set values using a textfield and then passing these values through an url to another page. I thought my method was working but it does not and I realize my mistake here.

I have a textfield like so:

  Voornaam: <h3 class="title1">Kevin</h3>
  <input type="text" id="myTextField1" />
  <input type="submit" id="byBtn" value="Change" onclick="change1()"/><br/>

And this can trigger the change1() function:

function change1(){
   var myNewTitle = document.getElementById('myTextField1').value;
   if( myNewTitle.length==0 ){
       alert('Write Some real Text please.');
   return;
   }
  document.getElementById("myLink").href="convert.php?var1=" + myNewTitle +"&var2=";
   var titles = document.getElementsByClassName('title1');
   Array.prototype.forEach.call(titles,title => {
    title.innerHTML = myNewTitle;
   });
}

As you can see it sets var1 but leaves var2 empty, var 2 should be coming from another textfield which is linked to change2() which is the entire same function except for the href line, that line is changed to this:

   document.getElementById("myLink").href="convert.php?var1=&var2=" + myNewTitle;

I understand that when I've called both functions, and change2() the last.. var 1 is ofcourse empty again. However I wish to have them both set, var1 and var2.

Could anybody perhaps tweak my code a little so that it actually keeps both of them set and not empty the other one?

Also I really do prefer seperate functions for my textfields.

Upvotes: 1

Views: 61

Answers (1)

Patrick Roberts
Patrick Roberts

Reputation: 51936

Try something like this (only uses one change button):

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}`);
    
    anchor.href = `convert.php?${querystring.join('&')}`;
  }
});
a:after {
  content: attr(href);
}
Voornaam:
<h3 class="title1">Kevin</h3>
<input type="text" id="myTextField1" />
<br/><br/>
Achternaam:
<h3 class="title2">Bosman</h3>
<input type="text" id="myTextField2" />
<br/><br/>
<input type="button" id="myBtn" value="Change" />
<br/><br/>
<a id="myLink" href="convert.php"></a>

Upvotes: 1

Related Questions