Jump to content

Recommended Posts

I'm writing code to validate a form and I'd like to be able to set the position of the cursor to the field of my choice when I detect an error. I'm getting the strong impression that I have to use Javascript to set the position of the cursor via the focus() function. But how do I pass information from my PHP code to Javascript to tell it which field I want the focus on?

 

For example, let's say I've got a simple form contain Name, Email address, Subject and Message. I check for bad data in all of those fields and I want to put the cursor (or focus) on the first field that has an error. How does my PHP code tell Javascript that the first field in error is the Email Address or the Message or whatever? An example showing what happens in PHP and what happens in Javascript would be very handy if someone can point me to one or throw one together....

Output a small script that will run onload which sets the focus to the field.  Indicate the field through a PHP variable.  Eg

 

<?php
$fieldToFocus=null;
if (isset($_POST['submit'])){
   //do all your validation here
   //assign the ID of any problem field to $fieldToFocus
}
?>
<script type="text/javascript">
//This example uses jQuery.  Modify as necessary if you are using a different library (or no library).
$(function(){
   $(<?php echo json_encode('#'.$fieldToFocus); ?>).focus();
});
</script>

I'm not sure what JQuery is or even what you mean by a library in this context. How would the coding change if I was sticking strictly to Javascript and PHP?

 

I'm using a hosting server, not my own server, and I don't think they'll let me install something like JQuery....

jQuery is not something you install on the server.  It's a Javascript library that you just include using a <script> tag.  It helps remove cross-browser compatibility issues and make a bunch of stuff easier to do. 

 

http://jquery.com/

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.