按下按钮交换输入



刚接触JS,需要通过按钮交换2个非空白输入值(文本)。这是我尝试过的:

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

我的解决方案是:

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

最新更新