Hi

I am trying to use jQuery to fire some javascript when a textbox is in focus, but it is not working.

Starting simply (after the more complex code was not working) i try to trigger an alert() when the user focusses in the textbox.

I have used drupal_add_js() to add the function, and it shows as expected in the head when rendered:

<script type="text/javascript">$("#edit-submitted-enter-your-details-below-name").focus(function(){
   alert("Event fired");
 });</script>

the textbox in question is:

<input type="text" maxlength="100" name="submitted[enter_your_details_below][name]" id="edit-submitted-enter-your-details-below-name"  size="50" value="name" class="form-text required" />

When i focus on the textbox nothing happens, no errors in firefox error consol or anything.

Can someone who has more experience with jQuery help me here?

TIA

Tracey

Comments

BoarK’s picture

Tracey,

You have to bind to the document.ready event in order to get your jquery code executed.

In Drupal this is done like so,

if (Drupal.jsEnabled) {
$(document).ready(function() {
$("#edit-submitted-enter-your-details-below-name").focus(function(){
alert("Event fired");
});
});
}

Cheers.

Nathan Tran.

UnicornSong’s picture

crumbs thank you, i hadnt noticed that had fallen off.
Anyway I got the event firing using the alert stub, however now my inner code is not working.

The operation of this is so:
the inputs have grey text on page load, indicating the value of the info to enter eg "name"
When the user clicks the input, i want the default value "name" to dissappear, leaving a blank box to type into.
When the user starts typing, the text should be black.

here is the code:

<?php
drupal_add_js (
  	'$(document).ready(function(){
    		$("#edit-submitted-enter-your-details-below-name").click(function(){
			$("#edit-submitted-enter-your-details-below-name").className = "inputclicked";
			$("#edit-submitted-enter-your-details-below-name").value = "";
      			})
    		});'     
  ,'inline'
);
?>
.inputclicked
{
	color: #000;
}

But these two lines are not working:

$("#edit-submitted-enter-your-details-below-name").className = "inputclicked";
$("#edit-submitted-enter-your-details-below-name").value = "";

Neither a php guru, nor a javascript guru. why is this code not affecting the input?

BoarK’s picture

Don't sweat it.

There's a jQuery plugin that offers this exact functionality. It is called Overlabel.

Nathan Tran.

hutch’s picture

I'm not sure if this is what you are looking for or which version of Drupal, but if you grab one of these you might be able to adapt. Add them to your theme and edit to suit

for D6
http://download.midwales.net/pub/lin/drupal/6.x/jquery_defaultvalue/

for D5
http://download.midwales.net/pub/lin/drupal/5.x/jquery_defaultvalue/

-----------------
Bob Hutchinson
Midwales dot com
-----------------

-----------------
Bob Hutchinson
Arwystli Networks
-----------------