0

I've got a Wordpress page and i'm running some jQuery to show and hide 2 input fields when someone clicks a checkbox. The problem is that this code runs perfectly on my Homepage but when i try to do the same thing (using the exact same html structure & jquery) on a subpage, it no longer works. It's not that the file doesn't get loaded because 1 part of the jQuery file runs fine on that page and I even have a console.log at the end of the file to show the file is fully loaded.

www.yogagids.nl is the homepage, when you click the checkbox "Evenementen" 2 datepicker fields show up, deselect it and they are hidden. Thats how it should work.

www.yogagids.nl/listings Is the page where this doesn't work. Same story, click the "evenementen" checkbox and the 2 datepicker fields should show and hide. However on this page nothing happens.

I'm really at a loss here, any and all help would be greatly appreciated.

Here is all the code that runs on this page, the actual file is larger but i couldn't post that many characters.

    jQuery( document ).ready(function() {

        //Create dummy input fields (altField) to show the user, this way the user sees a proper dateFormat while saving Unix Timestamp in the database.
        //Do this for both the Add Listing page and the Search Fields 
        jQuery( "#event_date_start, #filter_event_date_start" ).after('<input type="text" class="input-text" name="event_date_start_dummy" id="event_date_start_dummy" placeholder="Begindatum"></input>');
        jQuery( "#event_date_end, #filter_event_date_end" ).after('<input type="text" class="input-text" name="event_date_end_dummy" id="event_date_end_dummy" placeholder="Einddatum"></input>');

        //Define Dutch format and naming for the calendars, set the calendar to use unix date (easier to compare), set an alternative field to show the proper format.
        jQuery( "#event_date_start, #filter_event_date_start" ).datepicker({
            dateFormat: "@",
            altFormat: "dd-mm-yy",
            altField: "#event_date_start_dummy",
            minDate: 0,
            dayNames: [ "Zondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag" ],
            dayNamesMin: [ "Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za" ],
            monthNames: [ "januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december" ],
            monthNamesShort: [ "jan", "feb", "maa", "apr", "mei", "jun", "jul", "aug", "sep", "okt", "nov", "dec" ],
            changeMonth: true,
            changeYear: true
        });


        //Define Dutch format and naming for the calendars, set the calendar to use unix date (easier to compare), set an alternative field to show the proper format.
        jQuery( "#event_date_end, #filter_event_date_end" ).datepicker({
            dateFormat: "@",
            altFormat: "dd-mm-yy",
            altField: "#event_date_end_dummy",
            minDate: 0,
            dayNames: [ "Zondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag" ],
            dayNamesMin: [ "Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za" ],
            monthNames: [ "januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december" ],
            monthNamesShort: [ "jan", "feb", "maa", "apr", "mei", "jun", "jul", "aug", "sep", "okt", "nov", "dec" ],
            changeMonth: true,
            changeYear: true
        });


        //Whenever a user selects a start date, set the minimum end date to the start date.
        //This prevents users from selecting end dates that happen before the start date.
        jQuery('#event_date_start, #filter_event_date_start').on('change', function() {
            // Get the Start Date
            var minDate = jQuery( "#event_date_start, #filter_event_date_start" ).val();
            // Set the minimum End Date
            jQuery( "#event_date_end, #filter_event_date_end" ).datepicker( "option", "minDate", minDate );
        });


        //Chosen.js is not used on mobile devices, so running this code will interrupt the javascript. 
        //By running it only if the screen is bigger than 600px we make sure this doesnt happen.
        if (window.innerWidth <= 600) {
            //Do nothing
        } else {
            //Category dropdown uses Chosen.js, a dropdown library.
            //When on the map view page(/listings) or submit form(/sumbit-listing) but not on my account(/my-account/listings), prevent category dropdown from closing when selecting a category.
            if (currentLocation.toLowerCase().indexOf("listings") >= 0 && document.location.href.indexOf('my-account') === -1 || currentLocation.toLowerCase().indexOf("submit-listing") >= 0){
                console.log('Chosen dropdown fix active');

                //Source of fix: https://github.com/harvesthq/chosen/issues/1546#issuecomment-63448852
                //By user: ronanquillevere
                var chosen = jQuery('.job-manager-category-dropdown').chosen().data('chosen');
                var autoClose = false;
                var chosen_resultSelect_fn = chosen.result_select;
                chosen.search_contains = true;

                chosen.result_select = function(evt) {
                    var resultHighlight = null;

                    if(autoClose === false)
                    {
                        evt['metaKey'] = true;
                        evt['ctrlKey'] = true;

                        resultHighlight = chosen.result_highlight;
                    }

                    var stext = chosen.get_search_text();

                    var result = chosen_resultSelect_fn.call(chosen, evt);

                    if(autoClose === false && resultHighlight !== null)
                        resultHighlight.addClass('result-selected');

                    this.search_field.val(stext);               
                    this.winnow_results();
                    this.search_field_scale();

                    return result;
                }
            };
        }



        //Get multiple categories from the url, that were passed from home.
        //Source: http://stackoverflow.com/questions/22209307/how-to-get-multiple-parameters-with-same-name-from-a-url-in-javascript
        function getQueryParams(key) {
           qs = location.search;
           var params = [];
           var tokens;
           var re = /[?&]?([^=]+)=([^&]*)/g;
           while (tokens = re.exec(qs))
           { 
               if (decodeURIComponent(tokens[1]) == key)
               params.push(decodeURIComponent(tokens[2]));
           }
           return params;
        }
        var ms_cats = getQueryParams('ms_cat');

        //console.log(ms_cats);

        //Set chosen.js values by using the values that were passed in the url.
        //Source: http://stackoverflow.com/questions/8980131/changing-selection-in-a-select-with-the-chosen-plugin 
        jQuery('.job-manager-category-dropdown ').val(ms_cats).trigger('chosen:updated');



        jQuery(".listingTypeSelect input[value=event]").change(function() {
            console.log('clicked');
            if (!jQuery(this).is(':checked')) {

                jQuery('.search_event_date').css('display', 'none');
                jQuery(".listingTypeSelect input[value=studio]").prop('disabled', false);
                jQuery(".listingTypeSelect input[value=teacher]").prop('disabled', false);

                if (jQuery(window).width() > 992) {
                   jQuery('.search_home_row_2 > div').css('width', '33.333%');
                } else {
                    jQuery('.search_home_row_2 > div').css('width', '100%');
                }


            } else {

                jQuery('.search_event_date').css('display', 'inline-block');
                jQuery(".listingTypeSelect input[value=studio]").attr('checked', false); // Unchecks it
                jQuery(".listingTypeSelect input[value=teacher]").attr('checked', false); // Unchecks it
                jQuery(".listingTypeSelect input[value=studio]").prop('disabled', true);
                jQuery(".listingTypeSelect input[value=teacher]").prop('disabled', true);

                if (jQuery(window).width() > 992) {
                    jQuery('.search_home_row_2 > div').css('width', '23.333%');
                    jQuery('.search_home_row_2 .search_event_date').css('width', '30%');
                } else {
                    jQuery('.search_home_row_2 > div').css('width', '100%');
                    jQuery('.search_home_row_2 .search_event_date').css('width', '100%');
                }

            }
        });



        //Notify that the file has loaded without problems.
        console.log( "Finished loading listify-child.js!" );
    });
1
  • It seems to be a loading order issue. In that the checkbox isn't found the first time the code is run. If in the console I manually run jQuery(".listingTypeSelect input[value=event]").change(function() {console.log('clicked');}); the click handler is attached to that checkbox. I don't know how the page is generated, but if you have access to a callback that the section on the right is rendered, you should use that to then call this script. To test this theory, add a console.log(jQuery(".listingTypeSelect input[value=event]")) and see if it returns anything. Commented Jul 7, 2016 at 14:11

2 Answers 2

0

I'm almost certain that the checkboxes HTML elements don't exist or are missing the corresponding value/classes when you are binding the change event. Try using the on method and also capture the event in the parent element, taking advantage of "event propagation":

     jQuery(".listingTypeSelect").on('change', 'input[value=event]', function() {
        console.log('clicked');
        if (!jQuery(this).is(':checked')) {

            jQuery('.search_event_date').css('display', 'none');
            jQuery(".listingTypeSelect input[value=studio]").prop('disabled', false);
            jQuery(".listingTypeSelect input[value=teacher]").prop('disabled', false);

            if (jQuery(window).width() > 992) {
               jQuery('.search_home_row_2 > div').css('width', '33.333%');
            } else {
                jQuery('.search_home_row_2 > div').css('width', '100%');
            }


        } else {

            jQuery('.search_event_date').css('display', 'inline-block');
            jQuery(".listingTypeSelect input[value=studio]").attr('checked', false); // Unchecks it
            jQuery(".listingTypeSelect input[value=teacher]").attr('checked', false); // Unchecks it
            jQuery(".listingTypeSelect input[value=studio]").prop('disabled', true);
            jQuery(".listingTypeSelect input[value=teacher]").prop('disabled', true);

            if (jQuery(window).width() > 992) {
                jQuery('.search_home_row_2 > div').css('width', '23.333%');
                jQuery('.search_home_row_2 .search_event_date').css('width', '30%');
            } else {
                jQuery('.search_home_row_2 > div').css('width', '100%');
                jQuery('.search_home_row_2 .search_event_date').css('width', '100%');
            }

        }
    });

It might be necessary to capture the event higher in the DOM. Example in search_jobs div.

jQuery(".search_jobs").on('change', '.listingTypeSelect input[value=event]', function() {
   //Code
});
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, this works like a charm. Wasn't aware of this way of writing the change event. Thanks =D
-1

On https://www.yogagids.nl/ form is:

<form class="job_search_form" action="https://www.yogagids.nl/listings/" method="GET">

and on https://www.yogagids.nl/listings/ :

<form class="job_filters">

So it's about rendering different html and in second case you don't have action and method attributes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.