开发者

JQUERY SHOW/HIDE for required form fields. Hide if unchecked. Show if check but validation fails

I found this script to use in a web form. When the user clicks a checkbox, then additional required form fields will display. If the checkbox is not clicked, then the hidden form fields are not required.

It works except the problem I am having is this:

  1. click the checkbox.
  2. required form fields display
  3. the user submits the form without filling in the required fields
  4. the required form fields are hidden after the page reloads after failing validation, but the checkbox is still checked.

When #4 happens, I would instead like the fields to display after the page reloads because the checkbox is still checked instead of it being hidden.

<script>
    $(document).ready(function(){

        //Hide div w/id extra
       $("#extra").css("display","开发者_JAVA技巧none");

        // Add onclick handler to checkbox w/id checkme
       $("#delivery").click(function(){

        // If checked
        if ($("#delivery").is(":checked"))
        {
            //show the hidden div
            $("#extra").show("fast");
        }
        else
        {      
            //otherwise, hide it 
            $("#extra").hide("fast");
        }
      });

        });
</script>


If you are already using jQuery, is it not out of the question to save the reloading of the page by having jQuery validate the form before it is submitted? Seems like a better solution to make sure everything is validated prior to submission, instead of submitting, validating, and bringing back the form to the user.


This works:

$(document).ready(function(){
// Hide div w/id extra
$("#extra").hide();

// Toggle content on initial load
extraToggle($("#used_fixed_price_1"), $("#extra"));

// Add onclick handler to checkbox w/id cb
$("#used_fixed_price_1").click(function(){
extraToggle($("#used_fixed_price_1"), $("#extra"));
});
});

function extraToggle(checkbox, extra)
{
// If checked
if(checkbox.is(":checked"))
{
//show the hidden div
extra.show("fast");
}
else
{
//otherwise, hide it
extra.hide("fast");
}
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜