Welcome Guest, Not a member yet? Register   Sign In
javascript focus()
#1

[eluser]tirso[/eluser]
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

Tirso

on my view to display errors

Code:
<?php echo validation_errors(); ?>
#2

[eluser]TheFuzzy0ne[/eluser]
What if more than one field contains an error?
#3

[eluser]tirso[/eluser]
hi,

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.

Thanks

Tirso
#4

[eluser]TheFuzzy0ne[/eluser]
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:
Code:
<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?
#5

[eluser]tirso[/eluser]
hi,

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...

Thanks
#6

[eluser]Gordaen[/eluser]
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.

Code:
<?php
if (strlen(form_error('fieldname')) > 0)
{
    print 'js to focus here';
}
elseif ...
?>
#7

[eluser]TheFuzzy0ne[/eluser]
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.
#8

[eluser]slowgary[/eluser]
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:
Code:
$(document).ready(function(){
     $('.error:first').focus();
});




Theme © iAndrew 2016 - Forum software by © MyBB