I'm working on a dynamic form where based on a visitors selection of radio buttons certain <div> text and additional fields are shown or hidden. I would like to make some of these additional fields required but only if they are shown. (I tried making them required even when they are hidden and then the form won't submit because it won't pass validation and the user can't do anything about it... stupid me! :-))

Anyway, here's the script I'm using, thanks to some help from another Daniweb user, and I'm not sure how to tweak it to get it to require fields only if they are visible.

$(document).ready(function(){
        //Hide these fields initially
        $("#dad_address").hide();
        $("#mom_address").hide();

    $('#bothparents').click(function() {
    $("#dad_address").toggle(this.checked);
    $("#dad_address").hide();
    $("#mom_address").hide();
    });
    $('#dadaddress').click(function() {
    $("#dad_address").toggle(this.checked);
    $("#mom_address").hide();
    });
    $('#momaddress').click(function() {
    $("#mom_address").toggle(this.checked);
    $("#dad_address").hide();
    });
});

Thanks in advance!

Fcvolunteer

Member Avatar for stbuchok

check out the :visible selector for jQuery.

I tried this $("#606").validate({ignore:":not(:visible)"}); but it didn't work. What am I doing wrong?

Pardon my ignorance

I also tried this:

$('#606').validate({ ignore: ':hidden' });

which also didn't work. Any ideas what I'm doing wrong? I'm sure it's obvious I'm just totally in the dark when it comes to javascript.

Thanks!

Member Avatar for stbuchok

Why can't you do something like:
$('#606:visible').validate();

Thanks @stbuchok for your suggestion and your patience. I tried that, but for some reason it's not working, I'm getting a validation error. Not sure what I'm doing wrong but I'm sure it's something simple ;-/.

Here's the page url http://www.friendshipcirclenc.org/show-hide-test/

and here's the script I'm using:

$(document).ready(function(){
        //Hide these fields initially
        $("#dad_address").hide();
        $("#mom_address").hide();

    $('#bothparents').click(function() {
    $("#dad_address").toggle(this.checked);
    $("#dad_address").hide();
    $("#mom_address").hide();
    });
    $('#dadaddress').click(function() {
    $("#dad_address").toggle(this.checked);
    $("#mom_address").hide();
    });
    $('#momaddress').click(function() {
    $("#mom_address").toggle(this.checked);
    $("#dad_address").hide();
    });

$('#591:visible').validate();
});

In the code I posted here originally the id was "606" but in the test page I'm using the id is 591 so don't be surprised if you notice the change in id.

i can't click the send button in your test page... why?

@ome2012 should work in chrome and firefox now. thanks!

try not to include the data that is hidden....

@ome2012 not sure what you mean. Are you suggesting that I not have hidden text in this form, i.e. this shouldn't be a dynamic form? That would defeat the entire purpose of the help you gave me initially and is not really an option, I need this to work with hidden fields.

If you mean I should just temporarily remove the hidden text to see if it works with out that, I tried making the hidden data not required and the validation worked fine.

If you mean something else, please clarify cuz I'm not understanding.

Thanks for your help and patience!

try to make a condition that only visible fields can be validated....

If you are using the jQuery validate plugin then it will not try to validate fields that are disabled. Therefore, you can disable all fields when hiding them and the form will submit.

I haven't tested the following but something like this appears to be what you're trying to do:

// toggleFields (mini) plugin to toggle element
// visiblity and disable/enable the fields within it
$.fn.toggleFields = function(condition) {
    return this.each(function(i, el) {
        el = $(el);
        condition = (condition != null) ? condition : !el.is(':visible');
        el[condition ? 'show' : 'hide']().find(':input').attr('disabled', !condition);
    });
};

$(document).ready(function(){
    var dadAddr = $('#dad_address'),
        momAddr = $('#mom_address'),
        dadTrigger = $('#dadaddress'),
        momTrigger = $('#momaddress'),
        bothTrigger = $('#bothparents');

    // hide and disable fields
    dadAddr.toggleFields(false);
    momAddr.toggleFields(false);

    bothTrigger.click(function() {
        dadAddr.toggleFields(this.checked);
        momAddr.toggleFields(this.checked);
    });

    dadTrigger.click(function() {
        dadAddr.toggleFields(this.checked);
        momAddr.toggleFields(false);
    });

    momTrigger.click(function() {
        momAddr.toggleFields(this.checked);
        dadAddr.toggleFields(false);
    });
});

I just tried it in jsFiddle with a slightly improved version of the toggleFields method (I made it re-use the existing jQuery .toggle()): http://jsfiddle.net/kC5gk/

Works a charm :)

@ome2012 that's exactly what I'm trying to do but I'm not well versed in javascript and for some reason (probably a simple one) the scripts I found online and edited to reflect my form just wouldn't work. If you have something specific in mind please let me know.

@JJenZz I will try it out and let you know, thanks!

@JJenZz I tried it after making the changes to the "togetherTrigger" (what you called the "bothTrigger") based on what I needed it to do. For some reason I'm still getting a validation error and it's not submitting the form. Any ideas? Here's a link to a test page I set up Click Here

// toggleFields (mini) plugin to toggle element
// visiblity and disable/enable the fields within it
$.fn.toggleFields = function(condition) {
    return this.each(function(i, el) {
        el = $(el);
        condition = (condition != null) ? condition : !el.is(':visible');
        el[condition ? 'show' : 'hide']().find(':input').attr('disabled', !condition);
    });
};
$(document).ready(function(){
    var dadAddr = $('#dad_address'),
        momAddr = $('#mom_address'),
        dadTrigger = $('#dadaddress'),
        momTrigger = $('#momaddress'),
        togetherTrigger = $('#bothparents');
    // hide and disable fields
    dadAddr.toggleFields(false);
    momAddr.toggleFields(false);
    togetherTrigger.click(function() {
        dadAddr.toggleFields(false);
        momAddr.toggleFields(false);
    });
    dadTrigger.click(function() {
        dadAddr.toggleFields(this.checked);
        momAddr.toggleFields(false);
    });
    momTrigger.click(function() {
        momAddr.toggleFields(this.checked);
        dadAddr.toggleFields(false);
    });

    $('form').validate();
});

That validation message is not part of the jQuery validation. That is server side validation that is being sent in the response from the ajax request that submits the form so the above code is working.

The server-side validation needs modifying at /show-hide-test to allow empty/missing address fields if the parentaddress parameter is equal to "Both parents live at this address". You could change the parentaddress radio button values to be 0 for the bothparents radio and 1 for the mumaddress and dadaddress radios. That way, on the server you can check if parentaddress > 0 then validate fields.

Either way, the point is, it's the server side validation that needs fixing here... not the jQuery.

Hope that makes sense :)

@JJenZz Thanks! that makes perfect sense. Only problem is, I don't know how to code that I'm a total newbie with javascript :-(. What would I change or add to the code you gave me? and if it's not supposed to be added to that code, where should I be putting it?

Thanks!

Doesn't sound like it did make perfect sense, haha.

The point I was making is that it's not a JavaScript problem so you don't need to code JavaScript to fix it. The server-side code is what needs changing (either PHP or .NET or similar - whichever is being used)...

gotcha, thanks :-)

@JJenZz
Just to close the loop, thanks for the code help but actually the solution to my problem was in fact solved with Javascript and had nothing to do with php like you suggested (though it took me a long and wild goose chase to figure that out and lots of head banging on the way ;-) )

I finally disected the peice of code below which someone posted on the plugin support forum and through trial and error I got it to work for me.

$(document).ready(function(){
                $('.hide').hide();
                $('.hide input').val('n/a'); //give the text box a value when it is hidden so it passes the required field validation.
                    //Show the text field only when the third option is chosen - this doesn't
                    $('.dropdown').change(function() {
                        if ($(this).val() == "Other") {
                            $(this).parent().parent().next('p').find('input').val(''); //give an empty string as its value before sliding it down so it will not pass the required field validation.
                            $(this).parent().parent().next('p').slideDown('fast');
                    }
                        else {
                            $(this).parent().parent().next('p').slideUp('fast');
                            $(this).parent().parent().next('p').find('input').val('n/a'); //give back its value so it passes validation
                    }
                    });
            });

How strange... could have sworn I saw the form submit first before the errors came back (the page reloaded) which lead me to assume it was a server-side thing.

Ah well, glad to hear you have it fixed :)

I want search a records from database using select box in jquery

@Priyanka786 I suggest you start a new thread since this one has been marked as solved few people will look at it and your question is talking about something else.

Good Luck!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.