Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

How to convert form element into array using map function in jquery

Appends variable that contain html elements that contain another html elements
How to appends html elements to div container id
When we select all checkbox other checkbox selected
how to get all selected checkbox variable in array using map function based on data-id
In react js how to perform checkbox

Step 1: create a a div container and pagination container with id in blade page

  <div class="row" id="resultContainer" style="margin-top:2%;">
    <div class="col-lg-12 col-md-12 col-sm-12 col-12">
        <div class="col-md-12 col-lg-12">
            <div class="card" style="padding: 27px;">

                <div id="resultContent">
                    <!-- Your data results will be added here -->
                        </div>
                        <div class="card-body" id="paginationContainer">
                            <!-- Pagination buttons will be added here -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
Enter fullscreen mode Exit fullscreen mode

step 2: create a variable is used to store the HTML code generated within the immediately invoked function expression (IIFE) that precedes it
socialSiteHtml is varable

Appends variable that contain html elements that contain another html elements

   var socialSiteHtml = (function () {
        var html = '';
        var nonNullSocialPrices = extractNonNullSocialPrice(item);
        var nonNullSocialSites = extractNonNullSocialSites(item);
        if (nonNullSocialPrices.length > 0) {
            // Add a "Select All" checkbox row
            html += '<div class="row">';
            if (isLoggedIn) {
            html += '<div class="col-md-3' + (isAdded ? 'hideCheckboxes ' : '') + (!isLoggedIn ? 'nothingLoggedInClass' : '') + '">' +
    '<input type="checkbox" name="selectAll" class="selectAll">' +
    ' All' +
    '</div>';
            }

            else{


            }
            html += '</div>';

            // Display three social sites in the same row
            for (var i = 0; i < nonNullSocialPrices.length; i += 4) {
                // Add a row for each set of 4 social sites
                html += '<div class="row">';
                // Display each social site
                for (var j = 0; j < 4 && i + j < nonNullSocialPrices.length; j++) {
                    var site = nonNullSocialPrices[i + j].site.trim();
                    var site_url = nonNullSocialSites[i + j].site_url.trim();
                    console.log(site_url)
                    var cartSocialsObject = JSON.parse(item.cart_socials);
                    var hasPrice = item.cart_socials && Object.keys(cartSocialsObject).includes(site);
                    html += '<div class="col-md-3">';

                    if (hasPrice) {
    // Add a link with the site_url
    html += '<a href="' + site_url + '" target="_blank" style="color: black; font-size: 16px;">';
    html += '<i class="fas fa-cart-plus"></i> <span data-site="' + site + '">' + site + '</span>: ' + nonNullSocialPrices[i + j].price;
    html += '</a>';
} else if (isAdded) {
    // Show the 'not added' icon in red with a checkbox and add a link with the site_url
    html += '<i class="fas fa-times" style="color:red"></i> ';
    html += '<input type="checkbox" name="socialSite" value="' + site_url + '" data-site="' + site + '" class="socialSite ' +  (isAdded ? 'hideCheckboxes ' : '') + (!isLoggedIn ? 'notLoggedInClass' : '') + '">';
    html += ' <a href="' + site_url + '" target="_blank" style="color: black; font-size: 16px;"><span data-site="' + site + '">' + site + '</span>: </a>' + nonNullSocialPrices[i + j].price;
} else {
    // Add a link with the site_url for the social site name
    html += '<a href="' + site_url + '" target="_blank" style="color: black; font-size: 16px;">';
    // Just display the checkbox and social site name
    html += '<input type="checkbox" name="socialSite" value="' + site_url + '" data-site="' + site + '" class="socialSite ' +  (isAdded ? 'hideCheckboxes ' : '') + (!isLoggedIn ? 'notLoggedInClass' : '') + '">';
    html += ' <span data-site="' + site + '">' + site + '</span>: ' + nonNullSocialPrices[i + j].price;
    html += '</a>';
}
                    html += '</div>';
                } // Display each social site

                html += '</div>';
            }
        }
        return html;
    })();
Enter fullscreen mode Exit fullscreen mode

step3:appends it to an HTML element with the id resultContainer
How to appends html elements to div container id


var html = '<div class="card mb-3">' +
        '<div class="card-body">' +
        '<div class="row">' +
        '<div class="col-md-1">' + // Adjust the column size based on your layout
        avatarHtml +
        '</div>' +
        '<div class="col-md-3">' +
        '<h5 class="card-title"><a href="' + '/influencer/' + item.slug + '" target="_blank">' + item.user_name + '</a></h5>' +
        '<p class="card-text"> ' + item.city_name + ', ' + item.state_name + ', ' + item.country_name + '</p>' +
        '</div>' +
        '<div class="col-md-8">' +
        socialSiteHtml +
        '</div>' +
        '</div>';
        if (isLoggedIn) {
    if (isAdded) {
        // Add a row for the buttons
        html += '<div class="row">';
        html += '<div class="col-md-8 text-right">';

        html += '</div>';


    // Add a column for the "Go to Cart" button
    html += '<div class="col-md-2 text-right">';
    html += '<a href="' + '/influencer/' + item.slug + '" target="_blank" class="btn btn-sm btn-primary" role="button">View Profile</a>';
    html += '</div>';
        // Add a column for the "Go to Cart" button
        html += '<div class="col-md-1 text-right">';
        html += '<a href="{{ route('carts') }}" class="btn btn-sm btn-primary" role="button">Go to Cart</a>';
        html += '</div>';
        // Add a column for the existing button
        html += '<div class="col-md-1 text-right">';
        html += '<button class="btn btn-sm ' + buttonClass + ' add-to-cart-button" data-id="' + item.id + '" ' + buttonDisabled + ' onclick="mySocialsClick(this, event)" style="cursor: ' + (isAdded ? 'default' : 'pointer') + ';">' +
    buttonText +
    '</button>';
        html += '</div>';
        html += '</div>';
    } else {
        // Add a row for the existing button
        html += '<div class="row">';
        html += '<div class="col-md-9 text-right">';   
        html += '</div>';
        html += '<div class="col-md-2 text-right">';
    html += '<a href="' + '/influencer/' + item.slug + '" target="_blank" class="btn btn-sm btn-primary" role="button">View Profile</a>';
    html += '</div>';
        html += '<div class="col-md-1 text-right">';
        html += '<button class="btn btn-sm ' + buttonClass + ' add-to-cart-button" data-id="' + item.id + '" ' + buttonDisabled + ' onclick="mySocialsClick(this, event)" style="cursor: ' + (isAdded ? 'default' : 'pointer') + ';">' +
    buttonText +
    '</button>';

        html += '</div>';
        html += '</div>';
    }
}

    html += '</div>' +
        '</div>';

    resultContainer.append(html);
});
Enter fullscreen mode Exit fullscreen mode

step4: when we select checkbox
When we select all checkbox other checkbox selected

 html += '<div class="col-md-3' + (isAdded ? 'hideCheckboxes ' : '') + (!isLoggedIn ? 'nothingLoggedInClass' : '') + '">' +
    '<input type="checkbox" name="selectAll" class="selectAll">' +
    ' All' +
    '</div>';
Enter fullscreen mode Exit fullscreen mode

Image description

step5:
how to get all selected checkbox variable in array using map function based on data-id
This function is triggered when the state of a checkbox with the class selectAll is changed. Here's what it does:
Function for Handling Checkbox Selection:

$('body').on('change', '.selectAll', function() {
    var checkboxes = $(this).closest('.card-body').find('[name="socialSite"]');
    checkboxes.prop('checked', $(this).prop('checked'));
});
Enter fullscreen mode Exit fullscreen mode

Image description

step 6 when we click add cart button
how to get all selected checkbox variable in array using map function based on data-id

 html += '<div class="col-md-1 text-right">';
        html += '<button class="btn btn-sm ' + buttonClass + ' add-to-cart-button" data-id="' + item.id + '" ' + buttonDisabled + ' onclick="mySocialsClick(this, event)" style="cursor: ' + (isAdded ? 'default' : 'pointer') + ';">' +
    buttonText +
    '</button>';
Enter fullscreen mode Exit fullscreen mode

Image description

step 7 This function is triggered when the state of aa button with the class add-to-cart-button is clicked. Here's what it does:

$(document).on('click', '.add-to-cart-button', function(event) {
    event.preventDefault();
    var checkboxes = $(this).closest('.card').find('input[name="socialSite"]:checked');

    var selectedSites = checkboxes.map(function() {
        return $(this).data('site'); // Use data attribute to retrieve the site name
    }).get();
    console.log("selected site aayega");
    console.log(selectedSites);
    mySocialsClick($(this), selectedSites);
});
Enter fullscreen mode Exit fullscreen mode

Image description

Image description
note
rigth click on (5) and copyobject

[
    "facebook",
    "youtube",
    "wordpress",
    "instagram",
    "quora"
]
Enter fullscreen mode Exit fullscreen mode

In react js how to convert into array

import React, { useState } from 'react';


const MyComponent = () => {
  const [selectedSites, setSelectedSites] = useState([]);

  const handleCheckboxChange = (event) => {
    const { checked, dataset } = event.target;
    if (checked) {
      setSelectedSites((prevSelectedSites) => [...prevSelectedSites, dataset.site]);
    } else {
      setSelectedSites((prevSelectedSites) =>
        prevSelectedSites.filter((site) => site !== dataset.site)
      );
    }
  };

  const handleSelectAll = (event) => {
    const { checked } = event.target;
    const allSites = document.querySelectorAll('[name="socialSite"]');

    if (checked) {
      const allSelectedSites = Array.from(allSites).map((checkbox) => checkbox.dataset.site);
      setSelectedSites(allSelectedSites);
    } else {
      setSelectedSites([]);
    }
  };

  return (
    <div>
      <input type="checkbox" name="selectAll" onChange={handleSelectAll} />
      {/* Render your checkboxes and use handleCheckboxChange for the onChange event */}
      <CheckboxComponent name="exampleSite1" onChange={handleCheckboxChange} />
      <CheckboxComponent name="exampleSite2" onChange={handleCheckboxChange} />
      {/* Add more checkboxes as needed */}
      {/* Additional JSX */}
    </div>
  );
};

const CheckboxComponent = ({ name, onChange }) => {
  return (
    <div>
      <input type="checkbox" name="socialSite" data-site={name} onChange={onChange} />
      {/* Additional JSX */}
    </div>
  );
};

export default MyComponent;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)