Javascript help required

Soldato
Joined
1 May 2003
Posts
3,207
Location
Bucks
Surely this must be straightforward...

I want to enable a button only if text has been entered into a text box. I don't want to use the onchange event as my user may not tab out of the box and may just key some text and then use the mouse to press the button, in which case the onchange event will not be triggered. I have tried onkeypress, onkeyup but these all seem to trigger before the text has been entered and therefore the text box value is still blank.

Basic JS code to enable/disable the button currently looks like:

Code:
function edit1_onkeyup(){
if(document.getElementByID('edit1').value != ''){
  document.getElementByID('button1').disabled = false
} else {
  document.getElementByID('button1').disabled = true
}

But what event will successfully trap this?

Cheers :)
 
Using jQuery this works:

First you need to add a reference to jQuery:
Code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

Then add this JavaScript block:
Code:
 <script type="text/javascript">                                         
	$(document).ready(function() {
		$("#edit1").keyup(function() {
			if($('#edit1').val() == "") {
				$("#button1").attr('disabled', 'disabled');
			} else {
				$("#button1").removeAttr("disabled");
			}
		});
	});
 </script>

Cross browser compatible too :).

Arguably a more accessible way would be to show an error message as to why it's being disabled though, or popup a message box when they click it.
 
Thanks, will try it tomorrow when back at work. I am already referencing Jquery for a trim function :)

The input box holds the name of a query to be saved and the button is a 'Save Query' button. I did simply have an alert box that told the user that no query name had been provided, but I would prefer the button to be greyed out and only enabled once a query name has been provided.

Cheers :)
 
Back
Top Bottom