Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to allow only one textbox to contain a value

I have 2 textboxes that are optional, and only 1 can contain data. I need it to dynamically enable/disable the other textbox when one has something entered into it. By default they should both be enabled but then one should disable when something is entered in the other. I had this working with the code below, but now it doesn't seem to do it. Its basically checking every half-second to see if a value is entered.

setInterval(function(){
if ($("input[name=audioUri]").val().length != 0) {
    $("input[name=videoUri]").attr("disabled", "disabled");
    $("input[name=audioUri]").attr("disabled", "");
} else if ($("input[name=videoUri]").val().length != 0) {
    $("input[name=audioUri]").attr("disabled", "disabled");
    $("input[name=videoUri]").attr("disabled", "");
} else {
    $("input[name=videoUri]").attr("disabled", "");
    $("input[name=audioUri]").attr("disabled", "");     
}} , 500);

It checks to see if there are already values in the textboxes when the page loads and determines what to do from there, but when I first load up the page, both boxes are getting disabled. It's almost like they think there is something in the textboxes already. When I check the value of the boxes it is the empty string "", maybe I should check for .val() != ""?

I'm thinking there might be a better way to handle it without needing the setInterval function. Any ideas?

UPDATE: http://jsfiddle.net/7mKzy/1/

like image 794
bjo Avatar asked May 19 '26 20:05

bjo


2 Answers

You could use the event .change() on your textbox. So each time there is a change in your textbox. You call a function to enable or disable the other textbox.

$("#IdTextbox").change(function () {
        yourFunction();
    });

To check if your textbox has some data use :

if ($('#txt').val() != "") {
           doSomething();
}
like image 124
ThePaye Avatar answered May 21 '26 09:05

ThePaye


Yes, you could try keyup or keypress, which will trigger when the user starts entering text.

like image 44
harriyott Avatar answered May 21 '26 10:05

harriyott



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!