What is the best way to organize JavaScript code for handling multiple variables from multiple form elements while also preserving the selected choices?

For instance, suppose I have an HTML form like this:

<form role="search" method="get" id="searchform" action="" >

    <!-- DIRECT SEARCH INPUT TO SEARCH STRING -->
    <input type="text" value="" name="s" id="s" /> 
    <input type="submit" id="searchsubmit" value="Search" />

    <!-- DROPDOWN TO SELECT ONE CHOICE -->
    <select name='country' id='country' class='postform' >
        <option class="level-0" value="2">USA</option>
        <option class="level-0" value="3">Canada</option>
        <option class="level-0" value="4">Mexico</option>
        <option class="level-0" value="5">Cuba</option>
    </select>

    <!-- CHECKBOXES TO SELECT MULTIPLE CHOICES -->
    <div id="color">
        <input type="checkbox" name="" value="21" />Beachfront
        <input type="checkbox" name="" value="16" />TV
        <input type="checkbox" name="" value="20" />Internet
        <input type="checkbox" name="" value="17" />Pets Allowed
    </div> 

</form>

<div id="results"><!-- THE AJAX RESULTS GOES HERE --></div>

If I want to trigger an AJAX request whenever the user:

1) enters something in the search input box and clicks the search button

OR

2) selects an option from the dropdown menu

OR

3) checks one or more options from the checkboxes

The challenge lies in organizing my JavaScript code effectively to manage the user's selections across these different inputs. This includes considering not just the search term entered when clicking the search button, but also taking into account any previous choices made from the dropdown and checkboxes. Here is a snippet of what I've attempted so far:

jQuery(document).ready(function($){

    // DISPLAY RESULTS IN #results DIV AFTER AJAX CALL
    var $maincontent = $('#results'); 



    // PROCESSING SEARCH INPUT
    $('#searchsubmit').click(function(e){ 
        e.preventDefault();

        var searchval = $('#s').val();

        $.post(
            WPaAjax.ajaxurl,
            {
                action : 'ajax_search_action_do',
                searchval : searchval
            },
            function( response ) {
                $maincontent.empty();
                $maincontent.append( response );
            }
        );
    });

    // PROCESSING COUNTRY SELECTION FROM DROPDOWN
    $('#country').on('change', function() { 

            var countryval = this.value;

            $maincontent.animate({ opacity : '0.1' })

            $.post(
                WPaAjax.ajaxurl,
                {
                    action : 'ajax_search_action_do',
                    countryval : countryval
                },
                function( response ) {
                    $maincontent.empty();
                    $maincontent.append( response );
                    $maincontent.animate({ opacity : '1' })
                }
            );

            return false;
    });


    // PROCESSING CHECKBOX SELECTIONS
    $('#color input[type=checkbox]').click(function() {    
        if (this.checked) {
            // handle checked state
        }
        else {
            // do nothing
        }        

    });

});

As you can see, the code is fragmented with separate functions for click events, changes, and checkbox handling. It would be beneficial to consolidate these checks into a more cohesive structure. Any suggestions on how to achieve this in JavaScript?

Your insights and ideas are appreciated.

Answer №1

Here is an example of implementing logic:

var _do = {
    bind: function() {
        var self = this;
        $('#searchsubmit').on('click', function(e){ 
            e.preventDefault();
            self.ajax('searchval', $('#s').val());
        });

        $('#country').on('change', function() { 
            self.ajax('countryval', this.value);
        });
        return self;
    },
    ajax: function(key, value) {
        var data = {action: 'ajax_search_action_do'};
        data[key] = value;
        $.post(
            WPaAjax.ajaxurl, data, function( response ) {
                $maincontent.empty().append( response );
            }
        );
    }
}

jQuery(document).ready(function($){
    _do.bind();
});

Answer №2

Have you considered using jquery.form.js? http://malsup.com/jquery/form/

This plugin can be very useful. Simply structure the form as you would a regular redirection form, and remember to include an array in the names of your checkboxes.

<input type="checkbox" name="types[]" value="21" />Beachfront

Don't forget to add the target URL to the form, and then...

When you're ready to submit the form, use this code:

$('searchform').ajaxSubmit({

  success: function() {

    // Your callback function here

  }

)

You can trigger this submission on checkbox changes, dropdown changes, etc. To keep your code organized, use one selector for all your elements.

$('#country, #s, #color input').on('change', sendAjaxForm);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using JavaScript to load the contents of a JSON file

I attempted to display data from a JSON file on an HTML page using jQuery / Javascript. However, each time I load the page, it remains blank. Below is the code snippet: index.html <!DOCTYPE html> <html> <head> <meta conten ...

Establish the editor's starting state

Currently, I am utilizing lexical and aiming to establish initial text for the editor. At the moment, my approach involves hardcoding the initial text, but it seems I cannot simply pass a String as anticipated. Instead, the format required is JSON. Hence ...

ajax and php don't seem to be compatible

Below is the entire HTML code: <title></title> <script type="text/javascript"> function send() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safar ...

What is the best way to update the content of a particular div and its associated link ID whenever the link is clicked?

I need to update the content of a div by clicking on an href link that includes an id named data. The issue I'm facing is that I can't access the id value within my script because it's passed within a function. How can I pass the data variab ...

Customize the MUI (JoyUI) Autocomplete feature in React using react-hook-form to display a unique value instead of the label

Currently, I am in the process of creating a form that includes JoyUI (material) autocomplete and react-hook-form functionality. The array of objects I am using for my options looks like this: [ { label: "Todo", param: "TODO" }, ...

Refresh the content of a webpage in AngularJS without the need to fully reload the entire page

Within my controller and view files, I have content that is sourced from various places, including API calls. For instance, I have information retrieved from the database where users can update certain details like their last name. After submitting the up ...

Leveraging numerous identifiers in jQuery

I created a small jQuery script to check if the input box value is greater than 5, but I have two tags with IDs and only one of them seems to be working. <div id="register"> <form id="register"> <input id="first" type="text" /> <a ...

Sending Paypal IPN Data to Node.JS: A Step-by-Step Guide

I'm looking to implement a real-time donation system on my website that can update all users simultaneously. The challenge I'm facing is that the IPN (Instant Payment Notification) page, responsible for verifying payments, is written in PHP. Unf ...

Troubleshooting the Expanded Row Problem in 'angular-ui-grid'

Following a recent update, the expanded row feature in Google Chrome (version 77) is not functioning correctly compared to version 76. Prior to the update, the expanded rows in 'angular-UI-grid' worked well on all browsers including Mozilla Firef ...

Run a chunk of HTML with dynamic PHP elements using JavaScript

Within a single .php file, there is a combination of HTML, PHP, and JavaScript. The JavaScript section is crucial for detecting the browser; if the browser is not Internet Explorer, JavaScript will trigger the HTML block containing PHP. Here is the JavaS ...

Troubleshooting: Issues with jQuery Validate plugin's rules method in Javascript

I'm encountering an issue with a simple javascript file that is supposed to run the rules method, but it's not working as expected. I have confirmed that my custom javascript file is being rendered correctly since input masking is functioning pro ...

Is it possible to dynamically add an id or class to an element using document.createElement in JavaScript?

As a beginner in the world of JavaScript, I understand that the code structure I have used here may not be ideal for real-world applications. However, I am using it to practice my understanding of for loops and fetching JSON data. My main query is whether ...

Managing JSON data retrieval and manipulation techniques

My code is set up to display the image, title, and summary for all entries in a JSON file. However, I only want to display the image, title, and summary for the first entry, and only show the title for the rest of the entries. Please advise. <html> ...

Utilizing Promises in the apply function

I am currently working on a project in Node.js that utilizes bluebird for promise handling, as well as ES6 native promises. In both projects, I have a chain where I make a database query structured like this: some_function(/*...*/) .then(function () ...

Transform a REACT js Component into an HTML document

I'm working with a static React component that displays information from a database. My goal is to implement a function that enables users to download the React component as an HTML file when they click on a button. In essence, I want to give users ...

Issue with decodeURI function causing hyperlinks to display as plain text

I have been developing a Sharepoint App that includes a feature to extract contact details from a list on the Sharepoint site. Below is a snippet of my code: var currentOpeningContent = '<h4 onclick="ShowJobDetail(\'' + encodeURI(cu ...

Having trouble retrieving a specific object from an array using EJS

When re-rendering my form with any errors, I am able to display the errors in a list. However, I would like to access each error individually to display them under the invalid input instead of all at the bottom of the form. Here is what I have tried so f ...

The conversion from CSV to JSON using the parse function results in an inaccurate

I am having trouble converting a CSV file to JSON format. Even though I try to convert it, the resulting JSON is not valid. Here is an example of my CSV data: "timestamp","firstName","lastName","range","sName","location" "2019/03/08 12:53:47 pm GMT-4","H ...

Scrolling to a specific element using jQuery after a specified delay has

On my website, I have a page with an autoplaying video located at . My goal is to implement a feature where once the video completes playing after a specific duration, the webpage will automatically scroll down to the text section. This scroll action sho ...

Having difficulties fetching the post content in Wordpress using AJAX

I am currently working on ajaxifying my Wordpress theme by utilizing the ajax-in-WordPress method as detailed on this page. However, I am encountering an issue when attempting to retrieve the content of a post using get_the_content function within function ...