2

I create a web shop with items that is from database, it has modal with the category with a price with radio button that will change the swatches menu. The problem is that when I choose item 2 and click the radio button price it will show the swatches menu, but when i close that modal and choose item 1 the result of item 2 is also shown in item 1 and even if i click the radio button in item 1 it is not responding. here is the output sample

Here is the jquery code

function populateswatches() {

        var swatchesName = $('input[name=optradio]:checked').val();

        $.getJSON('getdata.php', {swatchesName: swatchesName}, function(swatch) {

            var html = '';
            $.each(swatch, function(index, array) {
                html = html + '<div class="col-md-3 w3-margin-top"><div class="w3-display-container w3-hover-opacity"><div class="w3-center"><input type="radio" name="swatches_code" value="' + array['swatches_code'] + '" required></div><div class="w3-display-middle w3-display-hover"><a href="../backend/functions/images/'+array['images']+'" target="_blank"><button type="button" class="btn btn-primary"><i class="fa fa-search fa-lg" aria-hidden="true"></i></button></a></div><img src="../backend/functions/images/'+array['images']+'" style="width:100%"><div class="w3-center">' + array['swatches_code']+'</div></div></div>';
            });
            $('.swatches').html(html);
        });
    }

    $(function() {
        $('input[name=optradio]').change(function() {
            populateswatches();
        });
    });

Here is the php code where the modal will be called

<div class="col-md-2 w3-margin-top">
<div class="w3-container">
    <div class="w3-display-container w3-hover-opacity">
            <h3 class="w3-center">'.$row["prod_name"].'</h3>
            <img src="../backend/functions/images/'.$row["img"].'" alt="'.$row["prod_name"].'" style="width:100%">
            <div class="w3-display-bottommiddle w3-display-hover">
                <button class="w3-button w3-blue" data-backdrop="false" data-toggle="modal" data-target="#'.$row["id_num"].'">MORE INFO</button>
            </div>
    </div>
</div>

here is the php code for the modal and the radio button

<div id="'.$row["id_num"].'" class="modal fade" role="dialog">

<!-- Modal content-->
<div class="modal-content modal-lg">
<form class="store-item">
  <div class="modal-header">
    <h3 class="modal-title" style="color:black">'.$row["prod_name"].'</h3>
  </div>
  <div class="modal-body">
    <div class="w3-row-padding">
        <div class="w3-half">
        <img src="../backend/functions/images/'.$row["img"].'" alt="Avatar" style="width:100%">
        </div>
        <div class="w3-half">
        <ul class="w3-ul w3-border">
            <li class="w3-light-grey w3-padding-8">
            <h4 style="color:black">Description</h4>
            <p>'.$row["description"].'</p>
            </li>
            <li class="w3-padding-8">
            <h4 style="color:black">SIZE</h4>
            <p>H-'.$row["height"].' | W-'.$row["width"].' | L-'.$row["length"].'</p>
            </li>
            <li class="w3-light-grey w3-padding-8">
            <h4>PRICES</h4>$priceSQL="SELECT * FROM price WHERE id_item='$IDitem'";
        $priceRES=mysqli_query($conn,$priceSQL);
        while($priceROW=mysqli_fetch_assoc($priceRES)){
            $id_categ=$priceROW["id_category"];

            $catSQL="SELECT * FROM category WHERE id_category='$id_categ'";
            $catRES=mysqli_query($conn,$catSQL);
            while($catROW=mysqli_fetch_assoc($catRES)){
            echo '
                <div class="radio">
                  <label><input type="radio" name="optradio" value="'.$priceROW["price"].'-'.$id_categ.'" required>'.$catROW["swatches_category"].'- &#8369;'.formatMoney($priceROW["price"]).'</label>
                </div>
            ';
            }
        }

            </li>
        </ul>
            <h4>SWATCHES</h4>   
            <div class="form-group">
                <span class="swatches"></span>
            </div>  
            <input type="hidden" value="'.$IDitem.'" name="id_item">        
        </div>
    </div>
  </div>
  <div class="modal-footer">
    <button type="button" onclick="refresh()" class="btn btn-default">Close</button>
    <button type="submit" class="btn btn-success">Add to Cart</button>
  </div>
</form>
</div></div></div>}`
  • Does every item have its own modal window? Or is there one single modal window that is being reused by changing its contents through AJAX? – vi5ion Jul 03 '17 at 09:05
  • it is single modal that is being reused. – Cliford Ching Jul 03 '17 at 09:29
  • Are you replacing all of the content, so also the radio buttons? If that is the case then you are creating new radio buttons for `optradio`, which do not yet have the change event attached to them. This can be fixed by delegating your change event: `$(document).on('change', 'input[name=optradio]', function() { populateswatches(); });` – vi5ion Jul 03 '17 at 09:39
  • I tried it but same problem occur. by the way I edited the code so that it will be much clear to come up with solutions. – Cliford Ching Jul 03 '17 at 09:48
  • Could you also share the code where you actually change the content of the modal? That seems to be the only part that is missing and it would probably answer a lot of the questions I still have :) – vi5ion Jul 03 '17 at 09:56
  • its complete now. – Cliford Ching Jul 03 '17 at 10:21
  • If you're really reusing the same modal window then there should be some JavaScript function that is triggered by a click event, which sends an AJAX request to retrieve the information of the item that was clicked on, in order to show this information in the existing modal. I'm not seeing any code like that. So how are you reusing the modal if there is no functionality that changes the content of the existing modal? Sorry if I'm missing something, but I'm just not getting a complete picture here. – vi5ion Jul 03 '17 at 10:37
  • I used while loop php so that i can call single modal in each item in the store. – Cliford Ching Jul 03 '17 at 11:04
  • But if you used a while loop in php, that would result in multiple modal windows in your html. So every item does have its own modal window. – vi5ion Jul 03 '17 at 11:19
  • I see. I'm just new in coding so im lost with this things. – Cliford Ching Jul 03 '17 at 11:49
  • No worries :) At least now I have an idea where the problem lies. I'll try to post an answer as soon as I get back from a meeting. – vi5ion Jul 03 '17 at 11:56

1 Answers1

2

I think the problem lies with the following lines:

var swatchesName = $('input[name=optradio]:checked').val();
--
$('.swatches').html(html);
--
$('input[name=optradio]').change(function() {
  populateswatches();
});

These don't just target the elements in the active modal window, but all elements that match the provided selectors. So that goes beyond the scope of the active modal window and includes all other modal windows as well.

$('.swatches').html(html); will change the HTML of all elements with a classname of swatches, not just the span in the active modal window. This explains why you're seeing the results of the first item with the other items as well.
Then when you try to change the option you run into a problem with var swatchesName = $('input[name=optradio]:checked').val(); because this one will always return the value of the radio button that you checked with the first item.

To solve this you can pass the element that was clicked on to the populateswatches function. In this function you can then look for the parent modal to which this element belongs. For any other elements that you then want to target, you only look for elements that are below this modal.

function populateswatches($el) {
  var $modal = $el.closest('.modal');
  var swatchesName = $el.val();
  $.getJSON('getdata.php', {swatchesName: swatchesName}, function(swatch) {
    var html = '';
    $.each(swatch, function(index, array) {
      html = html + 
             '<div class="col-md-3 w3-margin-top">' +
               '<div class="w3-display-container w3-hover-opacity">' +
                 '<div class="w3-center">' +
                   '<input type="radio" name="swatches_code" value="' + array['swatches_code'] + '" required>' +
                 '</div>' +
                 '<div class="w3-display-middle w3-display-hover">' +
                   '<a href="../backend/functions/images/'+array['images']+'" target="_blank">' +
                     '<button type="button" class="btn btn-primary">' +
                       '<i class="fa fa-search fa-lg" aria-hidden="true"></i>' +
                     '</button>' +
                   '</a>' +
                 '</div>' +
                 '<img src="../backend/functions/images/'+array['images']+'" style="width:100%">' +
                 '<div class="w3-center">' + array['swatches_code']+'</div>' +
               '</div>' +
             '</div>';
    });
    $modal.find('.swatches').html(html);
  });
}

$(function() {
  $('input[name=optradio]').on('click', function() {
    populateswatches($(this));
  });
});
vi5ion
  • 1,028
  • 7
  • 11