Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

focus on required field in bootstrap tabs

Afternoon, I am using PHP, HTML5 and Bootstrap. I have built a form which is seperated across 5 tabs and within this form are several required fields. All input fields that are required are 'text' and also marked with required="required" aria-required="true".

On submit the html5 validation catches the errors if on the current tab, however I would like to use a bit of jquery to focus back on the correct tab and input field that has not been filled in and display an alert box. Im not sure if this is possible..

Either that, if its easier to check that tabs required fields on tab change..

There is only 1 form on the page.

Many Thanks

** edit ** I have after tinkering around created an alert function for the required fields but it still will not change the tab to focus on the required field. 'productbutton' is the id of my submit button for the whole form. 'product_form' is the id of my form.

$('#productbutton').click(function(){
var error = 0;
var msg = 'An Error Has Occured.\n\nRequired Fields missed are :\n';
$(':input[required]', '#product_form').each(function(){
    $(this).css('border','2px solid green');
    if($(this).val() == ''){
        msg += '\n' + $(this).attr('id') + ' Is A Required Field..';
        $(this).css('border','2px solid red');
        if(error == 0){ $(this).focus(); }
        error = 1;
    }
});
if(error == 1) {
    alert(msg);
    return false;
} else {
    return true;
}
});

Basically if error = 1 it will popup an error msg with the input id that have been missed. it then fails to submit the form with a return false. It does focus on the missed field and place a red border around field. But it does not focus on the tab.. Otherwise it will submit the form.

like image 938
South Coast Web Avatar asked Nov 28 '22 02:11

South Coast Web


1 Answers

I'd the same problem and I solve it this way:

<script>
$('#submitButton').click(function () {
    $('input:invalid').each(function () {
        // Find the tab-pane that this element is inside, and get the id
        var $closest = $(this).closest('.tab-pane');
        var id = $closest.attr('id');

        // Find the link that corresponds to the pane and have it show
        $('.nav a[href="#' + id + '"]').tab('show');

        // Only want to do it once
        return false;
    });
});
</script>

When you click on submit button (yo need to ID it) it looks for invalid input fields, get the closest .tab-paneid and show it.

Hope you help!

like image 112
Paco Orozco Avatar answered Dec 11 '22 02:12

Paco Orozco