HenryCan Posted January 20, 2013 Share Posted January 20, 2013 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.... Quote Link to comment https://forums.phpfreaks.com/topic/273406-communication-between-php-and-javascript/ Share on other sites More sharing options...
kicken Posted January 20, 2013 Share Posted January 20, 2013 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> Quote Link to comment https://forums.phpfreaks.com/topic/273406-communication-between-php-and-javascript/#findComment-1407168 Share on other sites More sharing options...
HenryCan Posted January 21, 2013 Author Share Posted January 21, 2013 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.... Quote Link to comment https://forums.phpfreaks.com/topic/273406-communication-between-php-and-javascript/#findComment-1407173 Share on other sites More sharing options...
kicken Posted January 21, 2013 Share Posted January 21, 2013 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/ Quote Link to comment https://forums.phpfreaks.com/topic/273406-communication-between-php-and-javascript/#findComment-1407177 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.