IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

jQuery Discussion :

Validation avec checkbox JQuery


Sujet :

jQuery

  1. #1
    Membre du Club
    Homme Profil pro
    Auditeur informatique
    Inscrit en
    Septembre 2015
    Messages
    35
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : Auditeur informatique

    Informations forums :
    Inscription : Septembre 2015
    Messages : 35
    Points : 42
    Points
    42
    Par défaut Validation avec checkbox JQuery
    Bonjour tous le monde, je viens vers vous, car je suis bloqué, je m'explique:
    j'ai téléchargé Twitter Bootstrap Wizard qui permet de changer de contenu dynamiquement. Il est possible par exemple de mettre une condition comme le faite de remplir un input texte avant de passer à l'étape suivante.

    exemple:
    à l'étape 2, obligation de remplir le input texte.
    http://vadimg.com/twitter-bootstrap-...lidation.html#


    j'ai repris ce même code pour ne garder que 3 étapes et j'ai également mis une checkbox à l'étape 1. Je souhaite que l'internaute soit obligé de cocher la checkbox pour passer à l'étape 2.

    Vous trouverez ci-dessous mon code modifié, mais qui ne fonctionne pas.
    Le code d'origine est disponible ici: http://vadimg.com/twitter-bootstrap-...lidation.html#


    Code html : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    <div id="rootwizard">
        <div class="navbar">
          <div class="navbar-inner">
            <div class="container">
        <ul>
            <li><a href="#tab1" data-toggle="tab">First</a></li>
            <li><a href="#tab2" data-toggle="tab">Second</a></li>
            <li><a href="#tab3" data-toggle="tab">Third</a></li>
        </ul>
         </div>
          </div>
        </div>
        <div id="bar" class="progress">
          <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>
        </div>
        <div class="tab-content">
            <div class="tab-pane" id="tab1">
                <input id="checkBox" name="acceptTerms" type="checkbox" class="required"> <label for="acceptTerms-2">I agree with the Terms and Conditions.</label>
            </div>
            <div class="tab-pane" id="tab2">
                <p>
                    <input type='select' name='name' id='name' placeholder='Enter Your Name'>
                  </p> 
            </div>
            <div class="tab-pane" id="tab3">
            </div>
     
            <ul class="pager wizard">
                <li class="previous first" style="display:none;"><a href="#">First</a></li>
                <li class="previous"><a href="#">Previous</a></li>
                <li class="next last" style="display:none;"><a href="#">Last</a></li>
                <li class="next"><a href="#">Next</a></li>
                <li class="finish"><a href="http://www.google.fr">Finish</a></li>
            </ul>
        </div>
    </div>


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    $(document).ready(function() {
    ****$('#rootwizard').bootstrapWizard({onNext: function(tab, navigation, index) {
    ************if(index==1) {
    ****************// Make sure we entered the name
    ****************if(!$('input[#checkBox]').is(':checked') ) {
    ********************alert('You must checked first');
    ********************return false;
    ****************}
    ************}
    *
    ************if(index==2) {
    ****************// Make sure we entered the name
    ****************if(!$('#name').val()) {
    ********************alert('You must enter your name');
    ********************$('#name').focus();
    ********************return false;
    ****************}
    ************}
    *
    ************// Set the name for the next tab
    ************$('#tab3').html('Hello, ' + $('#name').val());
    *
    *************
    *
    ********}, onTabShow: function(tab, navigation, index) {
    ************var $total = navigation.find('li').length;
    ************var $current = index+1;
    ************var $percent = ($current/$total) * 100;
    ************$('#rootwizard .progress-bar').css({width:$percent+'%'});
    ********}});
    });

  2. #2
    Rédacteur/Modérateur

    Avatar de SpaceFrog
    Homme Profil pro
    Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Bidouilleur SharePoint
    Inscrit en
    Mars 2002
    Messages
    39 637
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 74
    Localisation : Royaume-Uni

    Informations professionnelles :
    Activité : Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Bidouilleur SharePoint
    Secteur : Industrie

    Informations forums :
    Inscription : Mars 2002
    Messages : 39 637
    Points : 66 661
    Points
    66 661
    Billets dans le blog
    1
    Par défaut
    Rassures nous, les *** ne sont pas dans ton code ... ?

    Le but est d'applique le plugin sur des éléments ajoutés dynamiquement ?
    A quel moment appliques tu le plugin sur les nouveau éléments ?
    Ma page Developpez - Mon Blog Developpez
    Président du CCMPTP (Comité Contre le Mot "Problème" dans les Titres de Posts)
    Deux règles du succès: 1) Ne communiquez jamais à quelqu'un tout votre savoir...
    Votre post est résolu ? Alors n'oubliez pas le Tag

    Venez sur le Chat de Développez !

  3. #3
    Membre du Club
    Homme Profil pro
    Auditeur informatique
    Inscrit en
    Septembre 2015
    Messages
    35
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : Auditeur informatique

    Informations forums :
    Inscription : Septembre 2015
    Messages : 35
    Points : 42
    Points
    42
    Par défaut
    Non il n'y a pas les ***, je ne sais pas pourquoi ils sont la :p

    Le but est de mettre plusieurs checkbox dans l'étape 1.
    Pour passer à l'étape 2 il me faut 2 conditions:
    - Cocher au moins 1 checkbox;
    - Ne peut cocher q'une checkbox maximum.


    et pour ta deuxième question je n'ai pas bien comprit désolé :/

  4. #4
    Rédacteur

    Avatar de danielhagnoul
    Homme Profil pro
    Étudiant perpétuel
    Inscrit en
    Février 2009
    Messages
    6 389
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 73
    Localisation : Belgique

    Informations professionnelles :
    Activité : Étudiant perpétuel
    Secteur : Enseignement

    Informations forums :
    Inscription : Février 2009
    Messages : 6 389
    Points : 22 933
    Points
    22 933
    Billets dans le blog
    125
    Par défaut
    $('input[#checkBox]') ==> $('#checkBox').

    J'ai testé, le code de ma page de test :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    <!DOCTYPE html>
    <html lang="fr" dir="ltr">
    <head>
      <meta http-equiv="cache-control" content="public, max-age=60">
      <meta charset="utf-8">
      <meta name="viewport" content="initial-scale=1.0">
      <meta name="author" content="Daniel Hagnoul">
      <title>Test</title>
      <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
      <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/sunny/jquery-ui.min.css">
      <style>
     
      </style>
    </head>
    <body>
     
      <div id="rootwizard">
        <div class="navbar">
          <div class="navbar-inner">
            <div class="container">
              <ul>
                <li>
                  <a href="#tab1" data-toggle="tab">First</a>
                </li>
                <li>
                  <a href="#tab2" data-toggle="tab">Second</a>
                </li>
                <li>
                  <a href="#tab3" data-toggle="tab">Third</a>
                </li>
              </ul>
            </div>
          </div>
        </div>
        <div id="bar" class="progress progress-striped active">
          <div class="bar"></div>
        </div>
        <div class="tab-content">
          <div class="tab-pane" id="tab1">
            <input type='text' name='name' id='name' placeholder='Enter Your Name'>
          </div>
          <div class="tab-pane" id="tab2">
            <input id="checkBox" name="acceptTerms" type="checkbox" class="required">
            <label for="acceptTerms-2">I agree with the Terms and Conditions.</label>
          </div>
          <div class="tab-pane" id="tab3">
            3
          </div>
          <div class="tab-pane" id="tab4">
            4
          </div>
          <div class="tab-pane" id="tab5">
            5
          </div>
          <div class="tab-pane" id="tab6">
            6
          </div>
          <div class="tab-pane" id="tab7">
            7
          </div>
          <ul class="pager wizard">
            <li class="previous first" style="display:none;"><a href="#">First</a></li>
            <li class="previous"><a href="#">Previous</a></li>
            <li class="next last" style="display:none;"><a href="#">Last</a></li>
            <li class="next"><a href="#">Next</a></li>
          </ul>
        </div>	
      </div>
     
      <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
      <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
      <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
      <script>
        /*!
         * jQuery twitter bootstrap wizard plugin
         * Examples and documentation at: http://github.com/VinceG/twitter-bootstrap-wizard
         * version 1.0
         * Requires jQuery v1.3.2 or later
         * Supports Bootstrap 2.2.x, 2.3.x, 3.0
         * Dual licensed under the MIT and GPL licenses:
         * http://www.opensource.org/licenses/mit-license.php
         * http://www.gnu.org/licenses/gpl.html
         * Authors: Vadim Vincent Gabriel (http://vadimg.com), Jason Gill (www.gilluminate.com)
         */
        (function(e){var n=function(d,k){d=e(d);var a=this,g=[],c=e.extend({},e.fn.bootstrapWizard.defaults,k),f=null,b=null;this.rebindClick=function(h,a){h.unbind("click",a).bind("click",a)};this.fixNavigationButtons=function(){f.length||(b.find("a:first").tab("show"),f=b.find('li:has([data-toggle="tab"]):first'));e(c.previousSelector,d).toggleClass("disabled",a.firstIndex()>=a.currentIndex());e(c.nextSelector,d).toggleClass("disabled",a.currentIndex()>=a.navigationLength());e(c.backSelector,d).toggleClass("disabled",
        0==g.length);a.rebindClick(e(c.nextSelector,d),a.next);a.rebindClick(e(c.previousSelector,d),a.previous);a.rebindClick(e(c.lastSelector,d),a.last);a.rebindClick(e(c.firstSelector,d),a.first);a.rebindClick(e(c.backSelector,d),a.back);if(c.onTabShow&&"function"===typeof c.onTabShow&&!1===c.onTabShow(f,b,a.currentIndex()))return!1};this.next=function(h){if(d.hasClass("last")||c.onNext&&"function"===typeof c.onNext&&!1===c.onNext(f,b,a.nextIndex()))return!1;h=a.currentIndex();$index=a.nextIndex();$index>
        a.navigationLength()||(g.push(h),b.find('li:has([data-toggle="tab"]):eq('+$index+") a").tab("show"))};this.previous=function(h){if(d.hasClass("first")||c.onPrevious&&"function"===typeof c.onPrevious&&!1===c.onPrevious(f,b,a.previousIndex()))return!1;h=a.currentIndex();$index=a.previousIndex();0>$index||(g.push(h),b.find('li:has([data-toggle="tab"]):eq('+$index+") a").tab("show"))};this.first=function(h){if(c.onFirst&&"function"===typeof c.onFirst&&!1===c.onFirst(f,b,a.firstIndex())||d.hasClass("disabled"))return!1;
        g.push(a.currentIndex());b.find('li:has([data-toggle="tab"]):eq(0) a').tab("show")};this.last=function(h){if(c.onLast&&"function"===typeof c.onLast&&!1===c.onLast(f,b,a.lastIndex())||d.hasClass("disabled"))return!1;g.push(a.currentIndex());b.find('li:has([data-toggle="tab"]):eq('+a.navigationLength()+") a").tab("show")};this.back=function(){if(0==g.length)return null;var a=g.pop();if(c.onBack&&"function"===typeof c.onBack&&!1===c.onBack(f,b,a))return g.push(a),!1;d.find('li:has([data-toggle="tab"]):eq('+
        a+") a").tab("show")};this.currentIndex=function(){return b.find('li:has([data-toggle="tab"])').index(f)};this.firstIndex=function(){return 0};this.lastIndex=function(){return a.navigationLength()};this.getIndex=function(a){return b.find('li:has([data-toggle="tab"])').index(a)};this.nextIndex=function(){return b.find('li:has([data-toggle="tab"])').index(f)+1};this.previousIndex=function(){return b.find('li:has([data-toggle="tab"])').index(f)-1};this.navigationLength=function(){return b.find('li:has([data-toggle="tab"])').length-
        1};this.activeTab=function(){return f};this.nextTab=function(){return b.find('li:has([data-toggle="tab"]):eq('+(a.currentIndex()+1)+")").length?b.find('li:has([data-toggle="tab"]):eq('+(a.currentIndex()+1)+")"):null};this.previousTab=function(){return 0>=a.currentIndex()?null:b.find('li:has([data-toggle="tab"]):eq('+parseInt(a.currentIndex()-1)+")")};this.show=function(b){b=isNaN(b)?d.find('li:has([data-toggle="tab"]) a[href=#'+b+"]"):d.find('li:has([data-toggle="tab"]):eq('+b+") a");0<b.length&&
        (g.push(a.currentIndex()),b.tab("show"))};this.disable=function(a){b.find('li:has([data-toggle="tab"]):eq('+a+")").addClass("disabled")};this.enable=function(a){b.find('li:has([data-toggle="tab"]):eq('+a+")").removeClass("disabled")};this.hide=function(a){b.find('li:has([data-toggle="tab"]):eq('+a+")").hide()};this.display=function(a){b.find('li:has([data-toggle="tab"]):eq('+a+")").show()};this.remove=function(a){var c="undefined"!=typeof a[1]?a[1]:!1;a=b.find('li:has([data-toggle="tab"]):eq('+a[0]+
        ")");c&&(c=a.find("a").attr("href"),e(c).remove());a.remove()};var l=function(d){var g=b.find('li:has([data-toggle="tab"])');d=g.index(e(d.currentTarget).parent('li:has([data-toggle="tab"])'));g=e(g[d]);if(c.onTabClick&&"function"===typeof c.onTabClick&&!1===c.onTabClick(f,b,a.currentIndex(),d,g))return!1},m=function(d){$element=e(d.target).parent();d=b.find('li:has([data-toggle="tab"])').index($element);if($element.hasClass("disabled")||c.onTabChange&&"function"===typeof c.onTabChange&&!1===c.onTabChange(f,
        b,a.currentIndex(),d))return!1;f=$element;a.fixNavigationButtons()};this.resetWizard=function(){e('a[data-toggle="tab"]',b).off("click",l);e('a[data-toggle="tab"]',b).off("shown shown.bs.tab",m);b=d.find("ul:first",d);f=b.find('li:has([data-toggle="tab"]).active',d);e('a[data-toggle="tab"]',b).on("click",l);e('a[data-toggle="tab"]',b).on("shown shown.bs.tab",m);a.fixNavigationButtons()};b=d.find("ul:first",d);f=b.find('li:has([data-toggle="tab"]).active',d);b.hasClass(c.tabClass)||b.addClass(c.tabClass);
        if(c.onInit&&"function"===typeof c.onInit)c.onInit(f,b,0);if(c.onShow&&"function"===typeof c.onShow)c.onShow(f,b,a.nextIndex());e('a[data-toggle="tab"]',b).on("click",l);e('a[data-toggle="tab"]',b).on("shown shown.bs.tab",m)};e.fn.bootstrapWizard=function(d){if("string"==typeof d){var k=Array.prototype.slice.call(arguments,1);1===k.length&&k.toString();return this.data("bootstrapWizard")[d](k)}return this.each(function(a){a=e(this);if(!a.data("bootstrapWizard")){var g=new n(a,d);a.data("bootstrapWizard",
        g);g.fixNavigationButtons()}})};e.fn.bootstrapWizard.defaults={tabClass:"nav nav-pills",nextSelector:".wizard li.next",previousSelector:".wizard li.previous",firstSelector:".wizard li.first",lastSelector:".wizard li.last",backSelector:".wizard li.back",onShow:null,onInit:null,onNext:null,onPrevious:null,onLast:null,onFirst:null,onBack:null,onTabChange:null,onTabClick:null,onTabShow:null}})(jQuery);
      </script>
      <script>
        "use strict";
     
        $( function(){ // forme abrégée de $(document).ready( function( ){
     
          $( '#rootwizard' ).bootstrapWizard({
            "onNext" : function( tab, navigation, index ){
     
              if ( index == 1 ){
     
                if ( ! $( '#name' ).val() ){
                  alert( 'You must enter your name' );
                  $('#name').focus();
                  return false;
                }
     
                $( '#tab3' ).html( '<p>Hello, ' + $('#name').val() + '</p>' );
              }
     
              if ( index == 2 ){
     
                console.log( $( "#checkBox" ).val() );
     
                if ( ! $( "#checkBox" ).is( ":checked" ) ){
                  alert( "Vous devez accepter les conditions" );
                  $( "#checkBox" ).focus();
                  return false;
                }
     
                $( '#tab3' ).append( '<p>Votre inscription est enregistrée.</p>' );
     
              }
     
     
            },
            "onTabClick" : function( tab, navigation, index ){
              return false; // disabled, sinon wizard ne fonctionne pas
            },
            "onTabShow" : function( tab, navigation, index ){
              var
                total = navigation.find( 'li' ).length,
                current = index + 1,
                percent = ( current / total ) * 100;
     
              $('#rootwizard').find('.bar').css({
                "background-color" : "#149bdf",
                "height" : "0.8em",
                "width" : percent + '%'
              });
            }
          });
     
        });
     
        $( window ).load( function(){
     
        });
      </script>
    </body>
    </html>

    Blog

    Sans l'analyse et la conception, la programmation est l'art d'ajouter des bogues à un fichier texte vide.
    (Louis Srygley : Without requirements or design, programming is the art of adding bugs to an empty text file.)

Discussions similaires

  1. [AJAX] jQuery validate avec Ajax
    Par Décibel dans le forum jQuery
    Réponses: 1
    Dernier message: 18/05/2014, 19h05
  2. Réponses: 4
    Dernier message: 30/08/2012, 13h29
  3. [PHP 5.0] Réafficher des checkbox après validation avec un foreach
    Par Gregk84 dans le forum Langage
    Réponses: 6
    Dernier message: 01/08/2012, 00h09
  4. Pb validation formulaire avec checkbox
    Par wolfe dans le forum Général JavaScript
    Réponses: 2
    Dernier message: 08/12/2005, 08h50
  5. [C#] TreeView avec CheckBox "indeterminate"
    Par padumeur dans le forum Windows Forms
    Réponses: 3
    Dernier message: 27/01/2005, 20h53

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo