逐步复选框流程,包含选择摘要

时间:2013-02-06 11:03:35

标签: jquery wordpress

我正在尝试创建一个3步骤的过程,有人通过复选框选择他们想要的步骤1和2,然后在第三步显示这些选择的摘要。

这就是我的html设置方式:

<form id="customisesystem" method="post" action="">
  <div id="first-step">
    <div class="steps">
      <p><b>Step 1 of 3</b></p>
    </div>
    <div class="progress-buttons"></div>
    <div class="clear"></div>
    <div id="customise-area">
      <div id="customise-title">
        <p><b>1. Hardware &amp; software options</b> <span>Please choose one or more of the following</span></p>
      </div>
      <div id="customise-area">
        <?php $posts = get_field('options');
                            if( $posts ):
                            $items = 0;
                            foreach( $posts as $post): // variable must be called $post (IMPORTANT)
                                setup_postdata($post); ?>
        <div class="custom-option">
          <p><b>
            <?php the_title(); ?>
            </b></p>
          <br />
          <div> <?php echo the_content(); ?> </div>
          <?php $counter = 1; while(the_repeater_field('images')): ?>
          <?php if($counter <= 1) { ?>
          <img width="180" height="136" src="<?php the_sub_field('image'); ?>" alt="<?php the_title(); ?>" />
          <?php } ?>
          <?php $counter++; endwhile; ?>
          <p>
            <input type="checkbox" name="hardware[]" value="<?php the_title(); ?>">
            Select</p>
          <div class="clear"></div>
        </div>
        <?php $items++; endforeach;
                            wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly
                            endif; ?>
      </div>
    </div>
  </div>
  <!-- end first-step -->

  <div id="second-step">
    <div class="steps">
      <p><b>Step 2 of 3</b></p>
    </div>
    <div class="progress-buttons"></div>
    <div class="clear"></div>
    <div id="customise-area">
      <div id="customise-title">
        <p><b>2. Accessories</b> <span>Please choose one or more of the following</span></p>
      </div>
      <div id="customise-area">
        <?php $posts = get_field('accessories');
                            if( $posts ):
                            $items = 0;
                            foreach( $posts as $post): // variable must be called $post (IMPORTANT)
                                setup_postdata($post); ?>
        <?php if ($items&1) { ?>
        <div class="custom-option">
          <p><b>
            <?php the_title(); ?>
            </b></p>
          <br />
          <div> <?php echo the_content(); ?> </div>
          <?php $counter = 1; while(the_repeater_field('images')): ?>
          <?php if($counter <= 1) { ?>
          <img width="180" height="136" src="<?php the_sub_field('image'); ?>" alt="<?php the_title(); ?>" />
          <?php } ?>
          <?php $counter++; endwhile; ?>
          <p>
            <input type="checkbox" name="accessories[]" value="<?php the_title(); ?>">
            Select</p>
          <div class="clear"></div>
        </div>
        <?php } else { ?>
        <div class="custom-option">
          <p><b>
            <?php the_title(); ?>
            </b></p>
          <br />
          <div> <?php echo the_content(); ?> </div>
          <?php $counter = 1; while(the_repeater_field('images')): ?>
          <?php if($counter <= 1) { ?>
          <img width="180" height="136" src="<?php the_sub_field('image'); ?>" alt="<?php the_title(); ?>" />
          <?php } ?>
          <?php $counter++; endwhile; ?>
          <p>
            <input type="checkbox" name="accessories[]" value="<?php the_title(); ?>">
            Select</p>
          <div class="clear"></div>
        </div>
        <?php } ?>
        <?php $items++; endforeach;
                            wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly
                            endif; ?>
      </div>
    </div>
  </div>
  <!-- end second-step -->

  <div id="third-step">
    <div class="steps">
      <p><b>Step 3 of 3</b></p>
    </div>
    <div class="progress-buttons"></div>
    <div class="clear"></div>
    <div id="customise-area-3">
        <p>Summary</p>

        <div id="customise-area-3-child">
            <input type="submit" name="submit" id="submit" value="submit" />
        </div>
    </div>
  </div>
  <!-- end third-step -->

</form>

这是我踩过这个过程的问题:

var prevLink = '<a class="back" href="#">Back</a>';
var nextLink = '</a><a class="next" href="#">Next</a>';
var navHTML = '<div class="prev-next">' +
                         prevLink +
                         nextLink +
                      '</div>';
var prevLink = '<a class="back" href="#">Back</a>';
var nextLink = '</a><a class="next" href="#">Next</a>';
var navHTML = '<div class="prev-next">' +
                         prevLink +
                         nextLink +
                      '</div>';
jQuery(document).ready(function( $ ) {
            // init
            $('#customisesystem > div')
                .hide()
                .prepend(navHTML);
            $('#first-step .prev').remove();
            $('#last-step .next').remove();

            // show first step
            $('#first-step').show();

            $('a.next').click(function(){
                var whichStep = $(this).parent().parent().attr('id');

                if( whichStep == 'first-step' )
                {
                    // validate first-step
                }
                else if( whichStep == 'second-step' )
                {
                    // validate second-step
                }
                else if( whichStep == 'last-step' )
                {
                    // validate last-step
                }

                $(this).parent().parent().hide().next().show();
            });

 $('a.back').click(function(){
          var whichStep = $(this).parent().parent().attr('id');
          if(whichStep == "first-step"){
            $(".customise").hide();
            $(".entire_product").show();
          }
          else{
            $(this).parent().parent().hide().prev().show();
          }
 });
        });

这是不起作用的部分:

jQuery(document).ready(function( $ ) 
{
   var summary = $('#customise-area-3 p').get(0);

   $('input[type=checkbox][name="hardware[]"]:checked').each(function(k,v) {
    //Retrieve the value of the checkbox.
    var checkboxValue = v.val();

    //Add the checkbox value to the summary area:
    summary[0].innerHTML += checkboxValue + '<br />';
   });
});

目前,当我进行硬件选择并转到第三步时,它不会在摘要中显示任何信息。我哪里错了?

这是工作链接 - teamworksdesign.com/clients/rogue/system/dc-stimulator点击右侧的“获取报价”。这将显示步骤1,单击下一步执行步骤2,然后单击下一步执行步骤3(即摘要)。

1 个答案:

答案 0 :(得分:1)

如果“step”div全部被赋予class="step",事情变得更容易,从而允许使用jQuery(".step")选择它们,并且避免每个div都具有唯一ID。

通过在最后一步中包含执行验证的“验证”按钮来回答您的具体问题。如果最后一步有效:

  • 创建并显示摘要文本
  • 隐藏“验证”按钮,并显示“提交”按钮。

此最后一项功能可确保在验证最后一步之前无法提交表单 并且用户可以在刷新屏幕之前阅读摘要。

这是代码(带注释):

//create nav wrapper
var $nav = $('<div/>').addClass('prev-next');

//create Prev button, attach click handler and append to nav wrapper
$('<a class="prev" href="#">Back</a>').on('click', function () {
    $(this).closest(".step").hide().prev(".step").show();
}).appendTo($nav);

//create Next button, attach click handler and append to nav wrapper
$('<a class="next" href="#">Next</a>').on('click', function () {
    var $step = $(this).closest(".step");
    if (validate($step)) {
        $step.hide().next(".step").show();
    }
}).appendTo($nav);

//In one long jQuery chain ...
//* prepend nav to each step div
//* hide all steps except the first
//* convert first 'Back' link and last 'Next' link to spans.
$(".step").prepend($nav).hide()
    .filter(":first").show().find("a.prev").after('<span>Back</span>').remove().end().end()
    .filter(":last").find("a.next").after('<span>Prev</span>').remove();

//Last step doesn't have a "Next" button but does have a "Validate" button
//and a submit button, which is hidden until the last step is validated,
//thus allowing the Summary message to be shown.
//Otherwise, the summary message would appear only for a brief moment.
var $validateButton = $("#validate").on('click', function() {
    if( validate( $(".step:last") ) ) {
        //var summary = [];
        var summary = ["Test Message"];//for debugging
        $('input[type=checkbox][name="hardware[]"]:checked').each(function(i, ch) {
            summary.push($(ch).val());
        });
        $('#customise-area-3 p').html(summary.join('<br/>'));
        $(this).hide();
        $("input[name='submit']").show();
    }
});

//Unfortunately, hidden form elements are not inlcuded in the submission,
//so all steps must be shown before the form is submitted.
var $submitButton = $("input[name='submit']").on('submit', function() {
    $(".step").show();
    return true;
});

function validate($step) {
    //var valid = false;
    var valid = true;//for debugging

    //Set the last section's validate and submit buttons to their "unvalidated" states.
    $validateButton.show();
    $("input[name='submit']").hide();

    //Perform validation
    switch ($step.index(".step")) {//index-origin is zero
        case 0:
            //validate step 1 here
            //if valid, set `valid` to true 
        break;
        case 1:
            //validate step 2 here
            //if valid, set `valid` to true 
        break;
        case 2:
            //validate step 3 here
            //if valid, set `valid` to true 
        break;
    }
    return valid;//Important - determines behaviour after validate() returns.
}

这是DEMO

您将看到我对HTML进行了一些其他的小修改,特别是在最后一步添加了Validate按钮。

修改

如果最后一步仅用于显示摘要并且不需要验证,那么事情就更简单了:

//Create nav wrapper
var $nav = $('<div/>').addClass('prev-next');

//Create Prev button, attach click handler and append to nav wrapper
$('<a class="prev" href="#">Back</a>').on('click', function() {
    $(this).closest(".step").hide().prev(".step").show();
}).appendTo($nav);

//Create Next button, attach click handler and append to nav wrapper
$('<a class="next" href="#">Next</a>').on('click', function() {
    $('#summary_text').html(makeSummary());
    var $step = $(this).closest(".step");
    if (validate($step)) {
        $step.hide().next(".step").show();
    }
}).appendTo($nav);

//In one long jQuery chain ...
//* prepend nav to each step div
//* hide all steps except the first
//* convert first 'Back' link and last 'Next' link to spans.
var $steps = $(".step").prepend($nav).hide()
    .filter(":first").show().find("a.prev").after('<span>Back</span>').remove().end().end()
    .filter(":last").find("a.next").after('<span>Prev</span>').remove().end().end();

//Set step titles
$steps.each(function(i, step) {
    $(step).find(".step-title").text('Step ' + (i+1) + ' of ' + $steps.length);
});

//Unfortunately, hidden form elements are not inlcuded in the submission,
//so all steps must be shown before the form is submitted.
var $submitButton = $("input[name='submit']").on('submit', function() {
    $steps.show();
    return true;
});

function validate($step) {
    //var valid = false;
    var valid = true;//for debugging

    //Perform validation
    switch ($step.index(".step")) {//index-origin is zero
        case 0:
            //Validate step 1 here
            //if valid, set `valid` to true 
        break;
        case 1:
            //Validate step 2 here
            //if valid, set `valid` to true 
        break;
        case 2:
            //No validatation required
        break;
    }
    return valid;//Important - determines behaviour after validate() returns.
}

function makeSummary() {
    var summary = [];
    $steps.not(":last").each(function(i, step) {
        $step = $(step);
        summary.push('<h4>' + $step.data('name') + '</h4>');
        var $ch = $step.find('input[type="checkbox"]:checked');
        if(!$ch.length) {
            summary.push('<p>No items selected</p>');
        }
        else {
            $ch.each(function(i, ch) {
                summary.push('<p>' + $(ch).val() + '</p>');
            });
        }
    });
    return summary.join('');
}

DEMO

在演示中,您将找到HTML和CSS的更多mod。

注意:

  • 除非我遗漏了某些内容,否则javascript现在应该自动响应更多/更少的步骤。因此,如果客户要改变主意并希望将硬件和软件拆分为单独的步骤,则只需更改HTML即可。 (哦,是的,以及validation()功能 - 这是一个特例)。
  • 现在自动生成“Y的步骤X”文本,并且HTML中只需要<h2 class="step-title"></h2>
  • 现在在第一步和第二步div中需要data-name属性。这在摘要中使用。
  • 摘要已格式化;使用<p>元素代替<br>;包括<h4>部分标题。
  • “验证”按钮现已从最后一步中移除。
  • 各种附加/修改的CSS指令。