只有在将一些数据提取到文本框中后才能读取文本框

时间:2012-02-02 07:56:02

标签: javascript html

我旁边有一个文本框和一个控制按钮。单击该按钮将调用另一个功能,其中选择了一些数据并将其写回文本框。目前,我的文本框可由用户在数据输入后编辑。提取到文本框。我想只在用户点击按钮并将数据提取到文本框后才能读取文本框,这样现在数据就出现在无法编辑的文本框中。如果是用户必须更改数据,用户必须再次单击按钮调用该函数,这将帮助我们在文本框中写入数据。如何在javascript中完成此操作。

4 个答案:

答案 0 :(得分:7)

你可以这样做

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

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

Add "readonly" to <input > (jQuery)

希望有所帮助,

答案 3 :(得分:0)

id属性分配到文本框,例如<input id=foo>,然后使用

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