views:

51

answers:

3

Hi all, 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.

+1  A: 

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/

Jamiec
The OP will still need a [server side example](http://stackoverflow.com/questions/3883673/change-textbox-text-in-javascript/3883786#3883786) on how to evaluate the fields if JS is disabled.
rockinthesixstring
A: 

[Demo]

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

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

tbox2.onfocus = function() {
  tbox1.value = "";
};
galambalazs
This code works just as well as [Jamiec](http://stackoverflow.com/users/219661/jamiec) 's [answer](http://stackoverflow.com/questions/3883673/change-textbox-text-in-javascript/3883728#3883728) . Just a few extra lines ;-)
rockinthesixstring
A: 

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
    }
}
rockinthesixstring
The code is a pretty rough sketch (I'm not a C# guy) but it should give you an idea. Basically server side validation is important to prevent relying solely on a client side technology... since it can be thwarted.
rockinthesixstring