Home > Back-end >  How to use divs as radio button and save data from inside the selected div to valiables using javasc
How to use divs as radio button and save data from inside the selected div to valiables using javasc

Time:06-06

I have multiple divs in my HTML with sample class name and I want these divs to behave like a radio button, that is when a div is clicked / selected, I want to achieve following. 1: Change the selected div background color 2: Get values from different elements those are inside the selected div and save the values in variables. I am able to change the color but I am not able to get the unique values from inside the selected div. Here is the HTML

 <div >
                    <div >
                        <input type="hidden"  value="5" />
                        <p >Deep</p>
                        <h4 >Deep Cleaning</h4>
                        <p>All-inclusive cleaning service</p>
                        <p >Price Per Cleaner</p>
                        <p >41.90 <span >/h</span></p>
                    </div>
                </div>
                <div >
                    <div >
                        <input type="hidden"  value="4" />
                        <p >Last Minute</p>
                        <h4 >Last-Minute Cleaning</h4>
                        <p>Last minute &amp; after party cleaning</p>
                        <p >Price Per Cleaner</p>
                        <p >43.90 <span >/h</span></p>
                    </div>
                </div>
                <div >
                    <div >
                        <input type="hidden"  value="3" />
                        <p >Moving</p>
                        <h4 >Move-In-Out Cleaning</h4>
                        <p>For move-ins, and move-outs</p>
                        <p >Price Per Cleaner</p>
                        <p >41.90 <span >/h</span></p>
                    </div>
                </div>

And here the the Script

    var packageId = "";
    var packageTitle = "";
    var packagePrice = "";
    var packages = document.getElementsByClassName('package');
    Array.prototype.forEach.call(packages, function (element) {
        element.addEventListener('click', function () {
            $('.package').css("background-color", "#FFFFFF");
            $(this).css("background-color", "#FCF6CC");
            packageId = $('.packageId').attr('value');
            packageTitle = $('.packageTitle').text();
            packagePrice = $('packagePrice').text();
            console.log(packageId);
            console.log(packageTitle);
            console.log(packagePrice);
        });
    });

CodePudding user response:

The reason that youre not getiing the unique value is because you are using get element by class ,

ie packagePrice = $('.packagePrice').text();

and there are 3 elements with same class name , to fix this issue

  const elem = $(this);
  packagePrice = elem.find('.packagePrice').text();
  • Related