使文本框只有在提取了一些数据后才可读

Making a text box read only after some data is fetched into it

本文关键字:数据 文本 提取      更新时间:2023-09-26

我有一个文本框,旁边有一个控制按钮。点击按钮将调用另一个函数,在该函数中选择一些数据并将其写回文本框。目前,在将数据提取到文本框后,用户可以编辑我的文本框。我想让文本框只有在用户点击按钮并将数据提取到文本框后才可读,这样现在数据就出现在无法编辑的文本框中。如果用户必须更改数据,则用户必须再次单击按钮来调用函数,该函数将帮助我们在文本框中重写数据。我如何用javascript实现这一点。

你可以像这样做

HTML:

<input type="text" id="mytextbox" value="click the button below."/>
<input type="button" value="click" onclick="changeText();"/>

Javascript:

function changeText(){
   var text_box = document.getElementById('mytextbox');
    if(text_box.hasAttribute('readonly')){   
        text_box.value = "This text box is editable.";
        text_box.removeAttribute('readonly');
    }else{       
        text_box.value = "This text box is read only.";
        text_box.setAttribute('readonly', 'readonly');   
    }
}

小提琴示例:http://jsfiddle.net/b7jAy/

您可以使用jQuery .attr()函数来设置文本字段的只读状态。

$('#textfield').attr('readonly', true);
$('#textfield').attr('readonly', 'readonly');

请尝试使用JQuery。成千上万的理由使用它作为Javascript框架。以下是对您问题的回答:

添加";只读";至<输入>(jQuery)

希望能有所帮助,

为文本框指定一个id属性,比如<input id=foo>,并使用

document.getElementById('foo').readOnly = true;