Home > Net >  Swap inputs on button press
Swap inputs on button press

Time:04-25

New to JS, need to swap the 2 non-whitespace input values (text) with each other via button. This is what I've tried:

function switcher() {
  var f = document.getElementById('inp').value;
  var s = document.getElementById('inp2').value;
  [f, s] = [s, f];
  if (f === '' || f === ' ', s === '' || s === ' ') {
    alert("fill a blank!");
  } else if (f !== '' || f !== ' ', s !== '' || s !== ' ') {
    f = s;
    s = f;
  }
}
<input type="text" id="inp" value="" size="50">
<input type="button" id="btn" value="Поменять местами" onclick="switcher()">
<input type="text" id="inp2" value="" size="50">

CodePudding user response:

Here would be my solution:

function switcher() {
  const input1 = document.getElementById('input1');
  const input2 = document.getElementById('input2');
  const text1 = input1.value
  const text2 = input2.value
  if (isStringEmpty(text1) || isStringEmpty(text2)) return alert("fill a blank!")
  input1.value = text2
  input2.value = text1
}

function isStringEmpty(string) {
  return !string.trim().length
}
<input required type="text" id="input1" value="" size="50" />
<input type="button" id="btn" value="Поменять местами" onclick="switcher()" />
<input required type="text" id="input2" value="" size="50" />

  • Related