Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

Apply condition and loops on on checkbox element using jquery

Applying Conditions on Checkbox using is checked
Checking if Checkbox is Checked
Checking Checkbox State Based on Value using prop and value
Generate dynamic Form based on selected checkbox using jquery using id and prop
Generate Dynamic form while iterating checkbox loop using input type and prop
Checking/Unchecking All Checkboxes using prop
Conditionally Enabling/Disabling Checkboxes using prop
Removing Checkboxes Dynamically using remove:
Dynamic Checkbox Creation using container id then append
Handle Checkbox Change Event using is checked
Filter the data from laravel server side
Validate Checkboxes at least one checkbox is checked.
Filter Checkboxesvto select specific checkboxes based on a condition
Already ticked mark checkbox cannot be unticked
Already ticked mark checkbox cannot be unticked for particular card

Here's a checklist for applying conditions and loops on checkbox elements using jQuery, along with coding examples:

Applying Conditions on Checkbox:
Checking if Checkbox is Checked:

Use the :checked selector to check if a checkbox is checked.

if ($('#myCheckbox').is(':checked')) {
    // Do something when the checkbox is checked
}
Enter fullscreen mode Exit fullscreen mode

Checking Checkbox State Based on Value:

Check the state of a checkbox based on its value.

if ($('#myCheckbox[value="someValue"]').prop('checked')) {
    // Do something when the checkbox with a specific value is checked
}
Enter fullscreen mode Exit fullscreen mode

Generate dynamic Form based on selected checkbox using jquery

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Form based on Checkbox</title>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>

    <form id="myForm">
        <label for="checkboxOption1">
            <input type="checkbox" id="checkboxOption1" value="someValue1"> Checkbox Option 1
        </label>

        <label for="checkboxOption2">
            <input type="checkbox" id="checkboxOption2" value="someValue2"> Checkbox Option 2
        </label>

        <!-- Add more checkboxes as needed -->

        <div id="dynamicFormContainer">
            <!-- Dynamic form elements will be added here -->
        </div>
    </form>

    <script>
        // jQuery code to perform actions based on checkbox value
        $(document).ready(function() {
            $('input[type="checkbox"]').change(function() {
                // Check if the checkbox with a specific value is checked
                if ($('#checkboxOption1').prop('checked')) {
                    // Perform actions for Checkbox Option 1
                    generateFormOption1();
                } else if ($('#checkboxOption2').prop('checked')) {
                    // Perform actions for Checkbox Option 2
                    generateFormOption2();
                } else {
                    // Clear the dynamic form container if no checkbox is checked
                    $('#dynamicFormContainer').empty();
                }
            });

            function generateFormOption1() {
                // Clear previous form elements
                $('#dynamicFormContainer').empty();

                // Add dynamic form elements for Checkbox Option 1
                var formElement = $('<div>');
                formElement.append('<label for="inputOption1">Input for Option 1:</label>');
                formElement.append('<input type="text" id="inputOption1" name="inputOption1">');
                // Add more elements as needed

                // Append the form element to the container
                $('#dynamicFormContainer').append(formElement);
            }

            function generateFormOption2() {
                // Clear previous form elements
                $('#dynamicFormContainer').empty();

                // Add dynamic form elements for Checkbox Option 2
                var formElement = $('<div>');
                formElement.append('<label for="inputOption2">Input for Option 2:</label>');
                formElement.append('<input type="text" id="inputOption2" name="inputOption2">');
                // Add more elements as needed

                // Append the form element to the container
                $('#dynamicFormContainer').append(formElement);
            }
        });
    </script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode
  1. Two checkboxes (Checkbox Option 1 and Checkbox Option 2) are defined with distinct values.
  2. The jQuery script listens for changes in the checkbox states and triggers specific functions (generateFormOption1 and generateFormOption2) based on the checked checkbox.
  3. Each function clears the previous form elements and generates new dynamic form elements based on the selected checkbox .

Applying Loops on Checkboxes:
Iterating Over Checked Checkboxes:

Use the each() method to iterate over each checked checkbox.

$('input[type="checkbox"]:checked').each(function() {
    // Access each checked checkbox
    var checkboxValue = $(this).val();
    console.log(checkboxValue);
});
Enter fullscreen mode Exit fullscreen mode

Generate Dynamic form while iterating checkbox loop

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Form with Modified Checkboxes</title>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>

    <form id="myForm">
        <label for="checkboxOption1">
            <input type="checkbox" id="checkboxOption1"> Checkbox Option 1
        </label>

        <label for="checkboxOption2">
            <input type="checkbox" id="checkboxOption2"> Checkbox Option 2
        </label>

        <!-- Add more checkboxes as needed -->
    </form>

    <script>
        // jQuery code to modify attributes of each checkbox
        $(document).ready(function() {
            $('input[type="checkbox"]').each(function() {
                // Modify attributes of each checkbox
                $(this).attr('data-custom', 'value');
            });
        });
    </script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In this example:

Two checkboxes (Checkbox Option 1 and Checkbox Option 2) are defined.
The jQuery script selects all checkboxes using

$('input[type="checkbox"]').
Enter fullscreen mode Exit fullscreen mode

The each function is used to iterate through each checkbox.
Inside the loop, the attr function is used to set the data-custom attribute to a specific value ('value' in this case).
After running this example, each checkbox in the form will have a data-custom attribute with the value 'value'. You can adjust the attribute name and value according to your specific needs.

Checking/Unchecking All Checkboxes:

Use a loop to check or uncheck all checkboxes.

// Check all checkboxes
$('input[type="checkbox"]').prop('checked', true);

// Uncheck all checkboxes
$('input[type="checkbox"]').prop('checked', false);
Enter fullscreen mode Exit fullscreen mode

Conditionally Enabling/Disabling Checkboxes:

Use the prop() method to enable or disable checkboxes based on a condition.

// Disable checkboxes with a specific class
$('.disableCheckbox').prop('disabled', true);

// Enable checkboxes with a specific class
$('.enableCheckbox').prop('disabled', false);
Enter fullscreen mode Exit fullscreen mode

Changing Checkbox Attributes in a Loop:

Use a loop to change attributes of each checkbox.

$('input[type="checkbox"]').each(function() {
    // Modify attributes of each checkbox
    $(this).attr('data-custom', 'value');
});
Enter fullscreen mode Exit fullscreen mode

Dynamic Checkbox Removal:
Removing Checkboxes Dynamically:

Use the remove() method to dynamically remove checkboxes.

// Remove checkboxes with a specific class

$('.removeCheckbox').remove();
Enter fullscreen mode Exit fullscreen mode

Conditional Styling:
Applying Conditional Styling to Checkboxes:

Use the toggleClass() method to apply conditional styling to checkboxes based on a condition.

// Apply a custom class to checkboxes with a specific value
$('input[type="checkbox"][value="customValue"]').toggleClass('customClass', condition);
Enter fullscreen mode Exit fullscreen mode

These examples cover various scenarios for applying conditions and loops on checkbox elements using jQuery. Adapt these methods based on your specific requirements and use cases.

Dynamic Checkbox Creation:
Creating Checkboxes Dynamically:

Use the append() method to dynamically create checkboxes.

// Create a new checkbox with a specific value and label
$('#checkboxContainer').append('<input type="checkbox" value="newValue">New Checkbox');
Enter fullscreen mode Exit fullscreen mode

Toggle Checkboxes:
Toggle Checkboxes Based on Another Checkbox:

Use the change event to toggle the state of checkboxes based on the state of another checkbox.

// Toggle the state of all checkboxes based on the state of 'toggleCheckbox'
$('#toggleCheckbox').change(function () {
    $('input[type="checkbox"]').prop('checked', $(this).prop('checked'));
});
Enter fullscreen mode Exit fullscreen mode

Handle Checkbox Change Event:
Handling Checkbox Change Event:

Use the change event to perform actions when the state of a checkbox changes.

// Perform actions when the state of any checkbox changes
$('input[type="checkbox"]').change(function () {
    if ($(this).is(':checked')) {
        // Checkbox is checked
    } else {
        // Checkbox is unchecked
    }
});
Enter fullscreen mode Exit fullscreen mode

Filter the data from laravel server side
To filter data from Laravel server-side using AJAX when the state of any checkbox changes, you can follow these steps:

Define a route in your Laravel application.
Create a controller method that handles the AJAX request and filters the data.
Write the jQuery script to send the AJAX request when the checkbox state changes.
Here's a basic example:

Define a Route in Laravel:

// routes/web.php

Route::get('/filter-data', 'YourController@filterData');
Enter fullscreen mode Exit fullscreen mode

Create a Controller Method:

// app/Http/Controllers/YourController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class YourController extends Controller
{
    public function filterData(Request $request)
    {
        // Get the values of checked checkboxes
        $selectedCheckboxes = $request->input('selectedCheckboxes');

        // Perform filtering logic based on $selectedCheckboxes
        // Replace this with your actual data filtering logic

        // Sample response (replace with your actual data)
        $filteredData = [
            ['id' => 1, 'name' => 'Item 1'],
            ['id' => 2, 'name' => 'Item 2'],
        ];

        return response()->json($filteredData);
    }
}
Enter fullscreen mode Exit fullscreen mode

Write jQuery Script:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Filter Data with Checkboxes</title>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>

    <!-- Your HTML content with checkboxes and other elements -->

    <script>
        // jQuery code to perform actions when checkbox state changes
        $(document).ready(function() {
            $('input[type="checkbox"]').change(function () {
                // Create an array to store the values of checked checkboxes
                var selectedCheckboxes = [];

                // Iterate through all checkboxes
                $('input[type="checkbox"]').each(function () {
                    if ($(this).is(':checked')) {
                        // Add the value of the checked checkbox to the array
                        selectedCheckboxes.push($(this).val());
                    }
                });

                // Make an AJAX request to filter data based on checked checkboxes
                $.ajax({
                    url: '/filter-data',
                    type: 'GET',
                    dataType: 'json',
                    data: { selectedCheckboxes: selectedCheckboxes },
                    success: function(response) {
                        // Process the filtered data returned from the server
                        console.log(response);
                        // Update your UI or perform other actions based on the filtered data
                    },
                    error: function(error) {
                        console.error('Error:', error);
                    }
                });
            });
        });
    </script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In this example:

  1. When any checkbox's state changes, the jQuery script collects the values of all checked checkboxes into an array (selectedCheckboxes).
  2. It then sends an AJAX request to the /filter-data route with the array of selected checkboxes.
  3. The Laravel controller (filterData method) receives the selected checkboxes, performs data filtering logic (replace this with your actual logic), and returns the filtered data as JSON.
  4. The success callback of the AJAX request processes the filtered data, and you can update your UI or perform other actions based on the filtered data . Make sure to replace 'YourController' with the actual name of your controller in the routes and controller files. Also, customize the data filtering logic in the controller according to your specific requirements.

Validate Checkboxes:
Validate Checkboxes:

Use validation logic to ensure that at least one checkbox is checked.

// Check if at least one checkbox is checked
if ($('input[type="checkbox"]:checked').length > 0) {
    // At least one checkbox is checked
} else {
    // No checkboxes are checked
}
Enter fullscreen mode Exit fullscreen mode

The following is a complete HTML code example demonstrating the usage of the provided jQuery code to check if at least one checkbox is checked or none are checked:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Checkbox Checking Example</title>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>

    <form id="myForm">
        <label for="checkboxOption1">
            <input type="checkbox" id="checkboxOption1" value="option1"> Checkbox Option 1
        </label>

        <label for="checkboxOption2">
            <input type="checkbox" id="checkboxOption2" value="option2"> Checkbox Option 2
        </label>

        <!-- Add more checkboxes as needed -->

        <button type="button" id="checkCheckboxBtn">Check Checkboxes</button>
    </form>

    <script>
        // jQuery code to check if at least one checkbox is checked
        $(document).ready(function() {
            $('#checkCheckboxBtn').click(function() {
                if ($('input[type="checkbox"]:checked').length > 0) {
                    // At least one checkbox is checked
                    alert('At least one checkbox is checked');
                } else {
                    // No checkboxes are checked
                    alert('No checkboxes are checked');
                }
            });
        });
    </script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In this example:

  1. Two checkboxes (Checkbox Option 1 and Checkbox Option 2) are defined within a form.
  2. There's a button (#checkCheckboxBtn) that, when clicked, triggers the check for checked checkboxes.
  3. The jQuery code within the $(document).ready function checks if at least one checkbox is checked and displays an alert accordingly .

Filter Checkboxes:
Filtering Checkboxes Based on a Condition:

Use the filter() method to select specific checkboxes based on a condition.

// Filter checkboxes with a specific class
$('input[type="checkbox"]').filter('.specialCheckbox').prop('checked', true);
Enter fullscreen mode Exit fullscreen mode

These additional examples cover scenarios such as dynamically creating checkboxes, toggling checkboxes based on another checkbox, handling checkbox change events, validating checkboxes, and filtering checkboxes based on conditions. Adapt these logics based on your specific requirements and use cases.

Already ticked mark checkbox cannot be unticked

First Way

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Checkbox and Button Example</title>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>

    <form id="myForm">
        <label for="myCheckbox">
            <input type="checkbox" id="myCheckbox"> My Checkbox
        </label>

        <button type="button" id="myButton">Toggle Checkbox</button>
    </form>

    <script>
        // jQuery code to prevent checkbox from being unchecked
        $(document).ready(function() {
            $('#myButton').click(function() {
                // Check if the button text contains a checkmark
                if ($(this).text().includes('✔')) {
                    // Button contains a checkmark, do not allow the checkbox to be unchecked
                    $('#myCheckbox').prop('checked', true);
                } else {
                    // Button does not contain a checkmark, toggle the checkbox
                    $('#myCheckbox').prop('checked', !$('#myCheckbox').prop('checked'));
                }
            });
        });
    </script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Second way
particular button text includes add to cart then change this text added using includes

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Checkbox and Button Example</title>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>

    <form id="myForm">
        <label for="myCheckbox">
            <input type="checkbox" id="myCheckbox"> My Checkbox
        </label>

        <button type="button" id="myButton">Toggle Checkbox</button>
    </form>

    <script>
        // jQuery code to prevent checkbox from being unchecked
        $(document).ready(function() {
            $('#myButton').click(function() {
                // Check if the button text contains "added" (case insensitive)
                if ($(this).text().toLowerCase().includes('added')) {
                    // Button contains "added", do not allow the checkbox to be unchecked
                    $('#myCheckbox').prop('checked', true);
                } else {
                    // Button does not contain "added", toggle the checkbox
                    $('#myCheckbox').prop('checked', !$('#myCheckbox').prop('checked'));
                }
            });
        });
    </script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Third Way

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Checkbox and Button Example</title>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>

    <form id="myForm">
        <label for="myCheckbox">
            <input type="checkbox" id="myCheckbox"> My Checkbox
        </label>

        <button type="button" id="myButton">Toggle Checkbox</button>
    </form>

    <script>
        // jQuery code to prevent checkbox from being unchecked
        $(document).ready(function() {
            $('#myButton').click(function() {
                // Check if the button text is exactly "added"
                if ($(this).text().trim() === 'added') {
                    // Button text is exactly "added", do not allow the checkbox to be unchecked
                    $('#myCheckbox').prop('checked', true);
                } else {
                    // Button text is not "added", toggle the checkbox
                    $('#myCheckbox').prop('checked', !$('#myCheckbox').prop('checked'));
                }
            });
        });
    </script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Already ticked mark checkbox cannot be unticked for particular card
get particular card checkbox using this and find
button text content change using id and text and disable it using prop

    $('.add_to_cart_form').submit(function(e) {
        e.preventDefault(); // Prevent form submission
        var checkbox = $(this).find('input[type="checkbox"]');

            $('#sample_form_pic').text('Added');
    $('#sample_form_pic').prop('disabled', true).addClass('disabled');
    checkbox.prop('disabled', true);

});
Enter fullscreen mode Exit fullscreen mode

Image description

Summary

Applying Conditions on Checkbox using is checked
Checking if Checkbox is Checked
Checking Checkbox State Based on Value using prop and value
Generate dynamic Form based on selected checkbox using jquery using id and prop
Generate Dynamic form while iterating checkbox loop using input type and prop
Checking/Unchecking All Checkboxes using prop
Conditionally Enabling/Disabling Checkboxes using prop
Removing Checkboxes Dynamically using remove:
Dynamic Checkbox Creation using container id then append
Handle Checkbox Change Event using is checked
Filter the data from laravel server side
Validate Checkboxes at least one checkbox is checked.
Filter Checkboxesvto select specific checkboxes based on a condition
Already ticked mark checkbox cannot be unticked
particular button text includes add to cart then change this text added using includes
Already ticked mark checkbox cannot be unticked for particular card
get particular card checkbox using this and find
button text content change using id and text and disable it using prop

Top comments (0)