如何清除文本输入并在JavaScript中重新聚焦

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何清除文本输入并在JavaScript中重新聚焦相关的知识,希望对你有一定的参考价值。

在我的代码中,如果文本输入字段为空,我想禁用该按钮。工作正常。但是,当我添加代码以清除并重新聚焦输入框时,它将使按钮处于启用状态,这使用户可以通过单击按钮来创建空的div。在这里,我附上了我的整个javascript代码,请有人帮我完成我想要的这项工作。

custom_script.js

const subBtn = document.getElementById("btn");
const inptTxt = document.getElementById("text");
const contDiv = document.getElementById("container");

//check input box is empty or not and enable Colorize button
subBtn.disabled = true

inptTxt.addEventListener('input', evt => {
    const value = inptTxt.value.trim()

    if (value) {
        inptTxt.dataset.state = 'valid'
        subBtn.disabled = false
    } else {
        inptTxt.dataset.state = 'invalid'
        subBtn.disabled = true
    }
})

var xhttp = new XMLHttpRequest();

subBtn.addEventListener("click",function(){

    xhttp.onload=function() {
        var crd = document.createElement("div");
        var div = contDiv.getElementsByTagName("div");
        var crdCount = div.length;
        crd.setAttribute("id", "card" + crdCount);
        crd.innerhtml = inptTxt.value;

        //change html title with input text
        document.title = inptTxt.value;

        contDiv .appendChild(crd);
        document.getElementById("card" + crdCount).style.background = JSON.parse(this.responseText).color;  

        //getting inverse value of hex color
        const inv = (hex) => '#' + hex.match(/[a-f0-9]{2}/ig).map(e => (255 - parseInt(e, 16) | 0).toString(16).replace(/^([a-f0-9])$/, '0$1')).join('')
        const invert = () =>
        document.querySelectorAll('circle')
        .forEach(c => 
        (hex = c.getAttribute('fill')) && 
        c.setAttribute('fill', inv(hex))
        )
        var invColor = inv(JSON.parse(this.responseText).color);

        //setting the inverse value to card text
        var crdText = document.getElementById("card" + crdCount).innerHTML;
        var setColor = "<span style='color:" + invColor + "'>" + crdText + "</span>";
        document.getElementById("card" + crdCount).innerHTML = setColor;

        //clear input and refocus
        inptTxt.value = "";
        inptTxt.focus();
        inptTxt.select();
    };

    xhttp.onerror=function() {
        var crd = document.createElement("div");
        var div = contDiv.getElementsByTagName("div");
        var crdCount = div.length;
        crd.setAttribute("id", "card" + crdCount);
        crd.innerHTML = inptTxt.value;

        //change html title with input text
        document.title = inptTxt.value;

        contDiv .appendChild(crd);
        document.getElementById("card" + crdCount).style.background = "#6d4298";  

        var crdText = document.getElementById("card" + crdCount).innerHTML;
        var setColor = "<span style='color:#ffffff'>" + crdText + "</span>";
        document.getElementById("card" + crdCount).innerHTML = setColor;
    };

    xhttp.open("GET","http://api.creativehandles.com/getRandomColor");
    xhttp.send(); 

})

//submit quote using Enter key
inptTxt.addEventListener("keyup", function(event) {
    if (event.keyCode === 13) {
    event.preventDefault();
    subBtn.click();
  }
});
答案

这里是输入和按钮的简单片段。

我使用onInput事件来检测输入是否发生变化。这样做时,我只是将按钮的disable属性设置为输入是否为空的答案。

注意,我正在使用disabled属性初始化按钮,因为在开始时应将其禁用。

let button = document.getElementById('button');
let input = document.getElementById('input');

function doSomething() {}

function inputHasChanged() {
  button.disabled = input.value === '';
}
<button disabled id="button" onclick="doSomething()">click</button>
<input id="input" type="text" onInput="inputHasChanged()">
另一答案

因为通过JavaScript设置valueinput不会触发它的input事件。

您需要在设置其值后手动触发其事件。

这里是解决方案,请注意标有FIX的评论:

const subBtn = document.getElementById("btn");
const inptTxt = document.getElementById("text");
const contDiv = document.getElementById("container");

//check input box is empty or not and enable Colorize button
subBtn.disabled = true

// FIX: make a dedicated function for validation
function validateInput() {
    const value = inptTxt.value.trim()

    if (value) {
        inptTxt.dataset.state = 'valid'
        subBtn.disabled = false
    } else {
        inptTxt.dataset.state = 'invalid'
        subBtn.disabled = true
    }
}

// FIX: call the validation function when the input is changed
inptTxt.addEventListener('input', validateInput);

var xhttp = new XMLHttpRequest();

subBtn.addEventListener("click", function () {

    xhttp.onload = function () {
        var crd = document.createElement("div");
        var div = contDiv.getElementsByTagName("div");
        var crdCount = div.length;
        crd.setAttribute("id", "card" + crdCount);
        crd.innerHTML = inptTxt.value;

        //change html title with input text
        document.title = inptTxt.value;

        contDiv.appendChild(crd);
        document.getElementById("card" + crdCount).style.background = JSON.parse(this.responseText).color;

        //getting inverse value of hex color
        const inv = (hex) => '#' + hex.match(/[a-f0-9]{2}/ig).map(e => (255 - parseInt(e, 16) | 0).toString(16).replace(/^([a-f0-9])$/, '0$1')).join('')
        const invert = () =>
            document.querySelectorAll('circle')
                .forEach(c =>
                    (hex = c.getAttribute('fill')) &&
                    c.setAttribute('fill', inv(hex))
                )
        var invColor = inv(JSON.parse(this.responseText).color);

        //setting the inverse value to card text
        var crdText = document.getElementById("card" + crdCount).innerHTML;
        var setColor = "<span style='color:" + invColor + "'>" + crdText + "</span>";
        document.getElementById("card" + crdCount).innerHTML = setColor;

        //clear input and refocus
        inptTxt.value = "";
        inptTxt.focus();
        inptTxt.select();
        // FIX: call the validation function when the input is cleared
        validateInput();
    };

    xhttp.onerror = function () {
        var crd = document.createElement("div");
        var div = contDiv.getElementsByTagName("div");
        var crdCount = div.length;
        crd.setAttribute("id", "card" + crdCount);
        crd.innerHTML = inptTxt.value;

        //change html title with input text
        document.title = inptTxt.value;

        contDiv.appendChild(crd);
        document.getElementById("card" + crdCount).style.background = "#6d4298";

        var crdText = document.getElementById("card" + crdCount).innerHTML;
        var setColor = "<span style='color:#ffffff'>" + crdText + "</span>";
        document.getElementById("card" + crdCount).innerHTML = setColor;
    };

    xhttp.open("GET", "http://api.creativehandles.com/getRandomColor");
    xhttp.send();

})

//submit quote using Enter key
inptTxt.addEventListener("keyup", function (event) {
    if (event.keyCode === 13) {
        event.preventDefault();
        subBtn.click();
    }
});
另一答案

因为通过JavaScript设置valueinput不会触发它的input事件。

由于设置了事件的内容,因此您需要在设置其值后手动触发其事件。

这里是解决方案,请注意标有FIX的评论:

const subBtn = document.getElementById("btn");
const inptTxt = document.getElementById("text");
const contDiv = document.getElementById("container");

//check input box is empty or not and enable Colorize button
subBtn.disabled = true

// FIX: make a dedicated function for validation
function validateInput() {
    const value = inptTxt.value.trim()

    if (value) {
        inptTxt.dataset.state = 'valid'
        subBtn.disabled = false
    } else {
        inptTxt.dataset.state = 'invalid'
        subBtn.disabled = true
    }
}

// FIX: call the validation function when the input is changed
inptTxt.addEventListener('input', validateInput);

var xhttp = new XMLHttpRequest();

subBtn.addEventListener("click", function () {

    xhttp.onload = function () {
        var crd = document.createElement("div");
        var div = contDiv.getElementsByTagName("div");
        var crdCount = div.length;
        crd.setAttribute("id", "card" + crdCount);
        crd.innerHTML = inptTxt.value;

        //change html title with input text
        document.title = inptTxt.value;

        contDiv.appendChild(crd);
        document.getElementById("card" + crdCount).style.background = JSON.parse(this.responseText).color;

        //getting inverse value of hex color
        const inv = (hex) => '#' + hex.match(/[a-f0-9]{2}/ig).map(e => (255 - parseInt(e, 16) | 0).toString(16).replace(/^([a-f0-9])$/, '0$1')).join('')
        const invert = () =>
            document.querySelectorAll('circle')
                .forEach(c =>
                    (hex = c.getAttribute('fill')) &&
                    c.setAttribute('fill', inv(hex))
                )
        var invColor = inv(JSON.parse(this.responseText).color);

        //setting the inverse value to card text
        var crdText = document.getElementById("card" + crdCount).innerHTML;
        var setColor = "<span style='color:" + invColor + "'>" + crdText + "</span>";
        document.getElementById("card" + crdCount).innerHTML = setColor;

        //clear input and refocus
        inptTxt.value = "";
        inptTxt.focus();
        inptTxt.select();
        // FIX: call the validation function when the input is cleared
        validateInput();
    };

    xhttp.onerror = function () {
        var crd = document.createElement("div");
        var div = contDiv.getElementsByTagName("div");
        var crdCount = div.length;
        crd.setAttribute("id", "card" + crdCount);
        crd.innerHTML = inptTxt.value;

        //change html title with input text
        document.title = inptTxt.value;

        contDiv.appendChild(crd);
        document.getElementById("card" + crdCount).style.background = "#6d4298";

        var crdText = document.getElementById("card" + crdCount).innerHTML;
        var setColor = "<span style='color:#ffffff'>" + crdText + "</span>";
        document.getElementById("card" + crdCount).innerHTML = setColor;
    };

    xhttp.open("GET", "http://api.creativehandles.com/getRandomColor");
    xhttp.send();

})

//submit quote using Enter key
inptTxt.addEventListener("keyup", function (event) {
    if (event.keyCode === 13) {
        event.preventDefault();
        subBtn.click();
    }
});

以上是关于如何清除文本输入并在JavaScript中重新聚焦的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript 使用jQuery设置或清除加载,聚焦和模糊的输入值

如何在列表视图中聚焦下一个编辑文本

onblur with javascript alert 然后清除输入文本

如何使用 JavaScript 清除 HTML 文件输入?

将文本输入到另一个输入字段时清除输入字段

聚焦时如何使用 Reactjs 选择输入中的所有文本?