简体   繁体   English

更改JavaScript中的文本框文本

[英]Change textbox text in JavaScript

I'm allowing a user to use either one of two textboxes to search a database - one is an ID field, and one is a freetext field. 我允许用户使用两个文本框之一来搜索数据库-一个是ID字段,一个是自由文本字段。 I'm using ASP.NET with C# btw. 我正在C#btw中使用ASP.NET。

Anyway, all I need to do is have it so when a user clicks on one of the text boxes, the other text box text is simply deleted, so the other text box is blank. 无论如何,我要做的就是拥有它,因此当用户单击其中一个文本框时,其他文本框的文本将被简单删除,因此另一个文本框为空白。

How would I do this? 我该怎么做? I'm guessing JavaScript is the solution. 我猜想JavaScript是解决方案。

Given a function in javascript: 在javascript中提供了一个功能:

function clearOther(which){
 document.getElementById(which).value='';
}

this can then be called when you focus on one textbox, passing the id of the other: 当您专注于一个文本框,并传递另一个文本框的ID时,可以调用此方法:

<input type="text" id="box1" onfocus="clearOther('box2')" />
<input type="text" id="box2" onfocus="clearOther('box1')"  />

working example --> http://jsfiddle.net/CwWKn/ 工作示例-> http://jsfiddle.net/CwWKn/

//Page A
<input type='text' id='tb'>
 var returnedValue = showModalDialog('page2.aspx', window);

//Page B
<input type='text' onkeypress='update(this);'>

function update(Sender) {
var input = window.dialogArguments.document.getElementById("tb");
input.value = Sender.value
}

[ Demo ] [ 演示 ]

var tbox1 = document.getElementById('tbox1');
var tbox2 = document.getElementById('tbox2');

tbox1.onfocus = function() {
  tbox2.value = "";
};

tbox2.onfocus = function() {
  tbox1.value = "";
};

I +1'ed Jamiec 's answer , but you still have to have some logic for those who don't have JS enabled. 我为Jamiec答案 +1了,但对于那些未启用JS的用户,您仍然需要具备一些逻辑。 Maybe use the ID field as a priority if BOTH field's are populated. 如果同时填充了两个字段,则可以将ID字段用作优先级。

if ((!box1.IsNullOrEmpty) & (!box2.IsNullOrEmpty)) {
    // Evaluate box1 (since box1 is the ID field)
} else {
    if ((!box1.IsNullOrEmpty)) {
        // Evaluate box1
    } else {
        // Evaluate box2
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM