按页面验证动态创建的单选按钮组

时间:2017-01-22 10:05:40

标签: javascript php jquery html

我有一个多页面的表格来定制某种产品。单选按钮是根据数据库中的值动态生成的。我想要发生的是,如果所需的单选按钮组没有选定的值,则阻止表单转移到下一页。我尝试过JQuery验证插件:

$('#customize-form').validate({ // initialize plugin
            ignore:":not(:visible)",            
            rules: {
                shape: { required:true },
                size: { required:true },
                tier: { required:true },
                flavors: { required:true },
            }
        });

现在这部分显示下一页。除了有效()似乎总是返回true并进入下一页这一事实之外,它的工作原理很完美。

// Next button click action
        btnnext.click(function(){
            if(current < widget.length){
                // Check validation
                if($("#customize-form").valid())
                {
                    widget.show();
                    widget.not(':eq('+(current++)+')').hide();
                }
        }
            hideButtons(current); //hides buttons which are not needed such as the submit button if it's not the end of the form
        })

以下是我动态生成单选按钮的方法:

 <div id=step1 class='options step'>
        <section class=section-title>Shape</section>
        <?php
        include('connect_db.php');

        $query = $dbc->prepare("SELECT * FROM product_shape_t");
        $query->execute();
        $result = $query->get_result();
        $total = mysqli_num_rows($result);

        while($row = mysqli_fetch_array($result, MYSQL_ASSOC)){
            echo '<ul class="radios">';
            echo '<li>';
            echo '<input type="radio" name="shape" id="'.$row['ShapeName'].'">';
            echo '<label for="'.$row['ShapeName'].'">'.$row['ShapeName'].'</label>';
            echo '</li>';
            echo '</ul>';
        }
        ?>
 </div>

这是完整的html:

<html>
<head>
</head>
<body>
    <form method=POST id=customize-form action ="">
        <div id=step1 class='options step'>
            <?php
            include('connect_db.php');

            $query = $dbc->prepare("SELECT MAX(CustomizedProductID) as 'Max ID' FROM customized_products_t");
            $query->execute();
            $result = $query->get_result();
            $total = mysqli_num_rows($result);
            while($row = mysqli_fetch_array($result, MYSQL_ASSOC)){
                $custom_id = $row['Max ID'] + 1;
                echo "<label class=custom_id style='display:none'>".$custom_id."</label>";
            }               
            ?>

            <section class=section-title>Shape</section>
            <?php
            include('connect_db.php');

            $query = $dbc->prepare("SELECT * FROM product_shape_t");
            $query->execute();
            $result = $query->get_result();
            $total = mysqli_num_rows($result);

            while($row = mysqli_fetch_array($result, MYSQL_ASSOC)){
                echo '<ul class="radios">';
                echo '<li>';
                echo '<input type="radio" name="shape" id="'.$row['ShapeName'].'">';
                echo '<label for="'.$row['ShapeName'].'">'.$row['ShapeName'].'</label>';
                echo '</li>';
                echo '</ul>';
            }
            ?>

            <section class=section-title>Size</section>
            <?php
            include('connect_db.php');

            $query = $dbc->prepare("SELECT * FROM product_size_t");
            $query->execute();
            $result = $query->get_result();
            $total = mysqli_num_rows($result);

            while($row = mysqli_fetch_array($result, MYSQL_ASSOC)){
                echo '<ul class="radios">';
                echo '<li>';
                echo '<input type="radio" name="size" id="'.$row['SizeName'].'">';
                echo '<label for="'.$row['SizeName'].'">'.$row['SizeName'].'</label><br />';
                echo '<label for="'.$row['SizeDesc'].'">'.$row['SizeDesc'].'</label>';
                echo '</li>';
                echo '</ul>';
            }
            ?>

            <section class=section-title>Tier</section>
            <?php
            include('connect_db.php');

            $query = $dbc->prepare("SELECT * FROM product_tier_t");
            $query->execute();
            $result = $query->get_result();
            $total = mysqli_num_rows($result);

            while($row = mysqli_fetch_array($result, MYSQL_ASSOC)){
                echo '<ul class="radios">';
                echo '<li>';
                echo '<input type="radio" name="tier" id="'.$row['TierName'].'">';
                echo '<label for="'.$row['TierName'].'">'.$row['TierName'].'</label><br />';
                echo '</li>';
                echo '</ul>';
            }
            ?>
        </div>

        <div id=step2 class='options step'>
            <section class=section-title>Flavor</section>
            <?php
            include('connect_db.php');

            $query = $dbc->prepare("SELECT * FROM product_flavor_t");
            $query->execute();
            $result = $query->get_result();
            $total = mysqli_num_rows($result);

            while($row = mysqli_fetch_array($result, MYSQL_ASSOC)){
                echo '<ul class="radios">';
                echo '<li>';
                echo '<input type="checkbox" name="flavors" id="'.$row['FlavorName'].'">';
                echo '<label for="'.$row['FlavorName'].'">'.$row['FlavorName'].'</label><br />';
                echo '</li>';
                echo '</ul>';
            }
            ?>
            <section class=section-title>Sides (Optional)</section>
            <?php
            include('connect_db.php');

            $query = $dbc->prepare("SELECT g.IngredientID, g.IngredientsName FROM ingredients_t g JOIN inventory_t i ON g.IngredientID = i.IngredientsID JOIN ingredient_type_t t ON t.IngTypeID = i.IngredientTypeID WHERE t.IngTypeName='sides'");
            $query->execute();
            $result = $query->get_result();
            $total = mysqli_num_rows($result);

            while($row = mysqli_fetch_array($result, MYSQL_ASSOC)){
                echo '<ul class="radios">';
                echo '<li>';
                echo '<input type="checkbox" name="ingredients" id="'.$row['IngredientsName'].'">';
                echo '<label for="'.$row['IngredientsName'].'">'.$row['IngredientsName'].'</label><br />';
                echo '</li>';
                echo '</ul>';
            }
            ?>
            <section class=section-title>Template (Optional)</section>
            <?php include('get_templates.php');?>
        </div>

        <div id=step3 class='options step'>
            <section class=section-title>Image (Optional)</section>
            <div class=image-display><img src="" width="100" style="display:none;" /></div>
            <?php
            echo '<form method=post enctype=multipart/form-data>
                    <section style="margin-bottom:10px">
                        <label class="paragraph-font2 full-width">Attach an image:</label>
                    </section>
                    <section style="margin-bottom:15px">
                        <input class="paragraph-font2 full-width" type=file name=uploaded_img id=uploaded_img accept="image/*">
                </form>';
            ?>
        </div>

        <div id=step4 class='options step'>
            <section class=section-title>Writings (Optional)</section>
            <?php
            echo '<form method=post>
                    <section class=add-notes>
                        <textarea id=writings class="lightfields-base lighttxtarea-regular" maxlength="250" placeholder="Do we have to write something on the cake?"></textarea>
                    </section>
                </form>';
            ?>
            <div class=separator-div></div>
            <section class=section-title>Additional notes (Optional)</section>
            <?php
            echo '<form method=post>
                    <section class=add-notes>
                        <textarea id=additional class="lightfields-base lighttxtarea-medium" maxlength="999"></textarea>
                    </section>
                </form>';
            ?>
        </div>

        <div id=step5 class='options step'>
            <section class=section-title>Check your cake</section>
            <div id=final_image class=final-image-display><img src="" width="100" style="display:none;" /></div>
            <div class=details>
                <label><span class=desc>Shape: </span><span id=shape></span></label>
                <label><span class=desc>Size: </span><span id=size></span></label>
                <label><span class=desc>Flavor: </span><span id=flavor></span></label>
                <label><span class=desc>Sides/Mix-ins: </span><span id=sides></span></label>
                <label><span class=desc>Writings: </span><span id=write></span></label>
                <label><span class=desc>Additional notes: </span><span id=add_notes></span></label>
            </div>
        </div>

        <div class=button-separator>
            <label>
            <button class='btn btn-info action next'>Next <span class='glyphicon glyphicon-arrow-right'></span></button>
            </label>
            <label>
            <button class='btn btn-info action submit'>Add to cart <span class='glyphicon glyphicon-arrow-right'></span></button>
            </label>
            <label>
            <button class='btn btn-info action back'><span class='glyphicon glyphicon-arrow-left'></span> Back</button>
            </label>
        </div>
    </form>
</body>
</html>
<script>
    $(document).ready(function(){
        var current = 1;

        widget      = $(".step");
        btnnext     = $(".next");
        btnback     = $(".back"); 
        btnsubmit   = $(".submit");

        // Init buttons and UI
        widget.not(':eq(0)').hide();
        hideButtons(current);

        $('#customize-form').validate({ // initialize plugin
            ignore:":not(:visible)",            
            rules: {
                shape: { required:true },
                size: { required:true },
                tier: { required:true },
                flavors: { required:true },
            }
        });

        // Next button click action
        btnnext.click(function(){
            if(current < widget.length){
                // Check validation
                if($("#customize-form").valid())
                {
                    widget.show();
                    widget.not(':eq('+(current++)+')').hide();
                    $('#step'+(current-1)).removeClass('active');
                    $('#step'+(current-1)).addClass('complete');
                    $('#step'+current).removeClass('disabled');
                    $('#step'+current).addClass('active');

                    //This part gets the values chosen to be displayed on page 5
                    /*if(current == 5)
                    {                   
                        var shape = $('input[type=radio][name=shape]:checked').attr('id');
                        var size = $('input[type=radio][name=size]:checked').attr('id');
                        var tier = $('input[type=radio][name=tier]:checked').attr('id');
                        var flavors = [];

                        $("input[name=flavors]:checked").each(function()
                        {
                            flavors.push($(this).attr('id'));
                        });

                        var sides = [];

                        $("input[name=ingredients]:checked").each(function()
                        {
                            sides.push($(this).attr('id'));
                        });

                        var writings = $(this).find('#writings').val();
                        var additional = $(this).find('#additional').val();

                        document.getElementById("shape").innerHTML=shape;   
                        document.getElementById("size").innerHTML=size; 

                        var flav;
                        for (var i=0; i<flavors.length; i++) {
                            flav += flavors[i];
                        }

                        document.getElementById("flavor").innerHTML=flavors;
                        document.getElementById("sides").innerHTML=sides;   
                        document.getElementById("write").innerHTML=writings;    
                        document.getElementById("add_notes").innerHTML=additional;  
                    }*/
                }
        }
            hideButtons(current);
        })

        // Back button click action
        btnback.click(function(){
            if(current > 1){
                current = current - 2;
                if(current < widget.length){
                    widget.show();
                    widget.not(':eq('+(current++)+')').hide();
                    //This part adjusts the steps bar
                    /*$('#step'+current).removeClass('complete');
                    $('#step'+current).addClass('active');
                    $('#step'+(current+1)).removeClass('active');
                    $('#step'+(current+1)).addClass('disabled');*/
                }
            }
            hideButtons(current);
        })

        btnsubmit.click(function(){
            if($("#customize-form").valid())
            {
                var id = $(this).find('.custom_id').text();
                var quantity = 1;

                window.location.href = "add_custom_to_cart.php?id=" + id + "&quantity=" + quantity;
                return false;
            }
        })

        $('#uploaded_img').change( function(event) {
            $(".image-display img").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));
            var image_name = $(this).attr('src',URL.createObjectURL(event.target.files[0]));
            document.getElementById('final_image').src = image_name;
        });

        $('.select-template').on('click', function(e){
            var temp_id = $('.temp_id').text();
            $.ajax({
                type: 'POST',
                url: 'add_selected_temp.php',
                data: {
                    template: temp_id
                }
            }); 
        });

        $().maxlength();
    });

    // Hide buttons according to the current step
    hideButtons = function(current){
        var limit = parseInt(widget.length); 

        $(".action").hide();

        if(current < limit) btnnext.show();
        if(current > 1) btnback.show();
        if (current == limit) { 
            btnnext.hide(); 
            btnsubmit.show();
        }
    }
</script>

我做错了什么或者我应该使用替代解决方案吗?谢谢。

1 个答案:

答案 0 :(得分:0)

我通过自定义验证解决了这个问题。我的标记似乎存在问题,这就是为什么JQuery验证插件不适用的原因。这是我的自定义验证。

      btnnext.click(function(){
            if(current < widget.length){
                // Check validation
                var empty = true;
                if(current == 1)
                {
                    if($("input[name='shape']:checked").val() &&
                        $("input[name='tier']:checked").val() &&
                        $("input[name='tier']:checked").val())
                    {
                        empty = false;
                    }
                }

                if(current == 2)
                {
                    if($("input[name='flavors']:checked").val())
                    {
                        empty = false;
                    }
                }

                if(current == 3)
                {
                    if(document.getElementById("uploaded_img").files.length != 0)
                    {
                        empty = false;
                    }
                }

                if(current == 4)
                {
                    if($("#writings").val())
                    {
                        empty = false;
                    }
                }

                if(current == 5)
                {       
                        empty = false;  
                }

                if(!empty)
                {
                    widget.show();
                    widget.not(':eq('+(current++)+')').hide();

                    //only gets values to be display on page 5 please ignore
                    /*if(current == 5)
                    {               
                        var shape = $('input[type=radio][name=shape]:checked').attr('id');
                        var size = $('input[type=radio][name=size]:checked').attr('id');
                        var tier = $('input[type=radio][name=tier]:checked').attr('id');
                        var flavors = [];

                        $("input[name=flavors]:checked").each(function()
                        {
                            flavors.push($(this).attr('id'));
                        });

                        var sides = [];

                        $("input[name=ingredients]:checked").each(function()
                        {
                            sides.push($(this).attr('id'));
                        });

                        var writings = $("#writings").val()
                        var additional =$("#additional").val();

                        document.getElementById("shape").innerHTML=shape;   
                        document.getElementById("size").innerHTML=size; 

                        var flav;
                        for (var i=0; i<flavors.length; i++) {
                            flav += flavors[i];
                        }

                        document.getElementById("flavor").innerHTML=flavors;
                        document.getElementById("sides").innerHTML=sides;   
                        document.getElementById("write").innerHTML=writings;    
                        document.getElementById("add_notes").innerHTML=additional;  
                    }*/
                }
            }
            hideButtons(current);
        })

我想感谢OffirPe'er提供所有帮助,并提出可能的标记冲突。

相关问题