• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Pruebas Online
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

197
Vistas
Swap inputs on button press

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">

almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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" />

almost 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda