• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
javascript focus()

hi to all

I was using ci form_validation for my forms. My question is how to use the javascript focus() on the field that has an error during the validation. What I am currently having now is to display the error message.

thanks in advance


on my view to display errors

<?php echo validation_errors(); ?>

What if more than one field contains an error?


Thanks for your immediate replied, I want to have a focus with the first field with error. How to achieve this. I did this but using xajax framework. I am new in ci.



Although I've never done this myself before, I see no reason why you shouldn't be able to use jQuery (or similar), to focus the first element in your form that contains the class "error" or whatever you're using to highlight the erroneous input controls. Assigning a class is a fairly simple operation. You can use the ternary operator:
<input type="text" name="my_input" value="<?php echo set_value('my_input'); ?>"<?php echo (form_error('my_input')) ? ' class="error"' : ''; ?> />

Does this help at all?


thanks for your response. I tried this but it didn't focus on my field. As far as I know javascript code will need to have a focus on a field.

Any help there...


If the form isn't too big, you could check the various fields for errors and then print the JavaScript for focusing on that field at the end of your view.

if (strlen(form_error('fieldname')) > 0)
    print 'js to focus here';
elseif ...

I think you misunderstood my suggestion. I simply demonstrated how to add a class to a form control. It's up to you to create some JavaScript to highlight the first instance of the class. If you've tried it, please post the code you used.

I've done the same thing with a form that I recently made. Tirso, do you use any sort of JavaScript framework? Using TheFuzzyOne's PHP example, you would do something like this with jQuery:

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.