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. I’m using ASP.NET with C# btw.

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Given a function in 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:

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

working example –> http://jsfiddle.net/CwWKn/

Method 2

[Demo]

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

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

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

Method 3

I +1’ed Jamiec ‘s answer, but you still have to have some logic for those who don’t have JS enabled. Maybe use the ID field as a priority if BOTH field’s are populated.

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

Method 4

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x