0

I currently have an html page which contains this part of code:

<td><input type="checkbox" onchange="getButtonDetails(this)" data-toggle="switch" data-title="printing" data-order="{{ $order->order_number }}" class="ct-primary" value="0" /></td>
<td><input type="checkbox" onchange="getButtonDetails(this)" data-toggle="switch" data-title="engraving1" data-order="{{ $order->order_number }}" class="ct-primary" value="0" /></td>
<td><input type="checkbox" onchange="getButtonDetails(this)" data-toggle="switch" data-title="engraving2" data-order="{{ $order->order_number }}" class="ct-primary" value="0" /></td>
<td><input type="checkbox" onchange="getButtonDetails(this)" data-toggle="switch" data-title="assembly" data-order="{{ $order->order_number }}" class="ct-primary" value="0" /></td>
 <td><input type="checkbox" onchange="getButtonDetails(this)" data-toggle="switch" data-title="completed" data-order="{{ $order->order_number }}" class="ct-primary" value="0" /></td>

This html above is in a for each loop so the html actually displays about 50 times with a different order number.

I'm trying to see when a person switches the data-toggle switch and then record that info to a database via ajax. My code (based upon newbie knowledge) to accomplish this is as follows:

function getButtonDetails(elem){
              var $selfSelection = $(elem);

                console.log($selfSelection.data('order'));
                if($selfSelection.val() == '1') {
                  $selfSelection.val('0');
                } else {
                  $selfSelection.val('1');
                };

                $.ajax({
                    type: 'POST',
                    url: 'orders',
                    data: {
                        '_token': $('input[name=_token]').val(),
                        'order_id': $selfSelection.data('order'),
                        'printing': $selfSelection.filter('[data-title="printing"]').val(),
                        'engraving1': $selfSelection.filter('[data-title="engraving1"]').val(),
                        'engraving2': $selfSelection.filter('[data-title="engraving2"]').val()
                    }
                  });
                  toastr.success('Successfully saved', 'Success Alert', {timeOut: 5000});
            };

using javascript I'm doing an onchnage event which is calling the function getButtonDetails. The parameter being passed is THIS. Since I'm assuming that'll get THIS input data.

In the function I set var $selfSelection to = $ elem so in essence I'm trying to do $selfSelection = this current element.

I check with a console log ot make sure this indeed is the order I want.

Then I do an if else to set the val of the current selected element. If user switches it'll give it the appropriate value. All this works good.

However when I try to pass data I have been lost. My last failed attempt is to pass the data using a filter to select the data-title of the current element. This updates one column on the database but doesn't update all. What I need is this: When switch is activated on "printing" it should get the val of engraving1, engraving 2 etc at the set time and then fill those fields. Currently if I change one it seems to not recognize any other one.

Any ideas? Again my knowledge is subpar so excuse any newbie mistakes.

FabricioG
  • 3,107
  • 6
  • 35
  • 74

1 Answers1

0

I'm guessing by

switches the data-toggle switch

you mean clicks a checkbox. I'd suggest rather than applying a function to each checkbox on the html level, you could just bind an event listener to those checkboxes in the script.

$('.ct-primary').on('change', function() {
  let $row = $(this).parents('tr');

  $.ajax({
    type: 'POST',
    url: 'orders',
    data: {
      '_token': $row.find('input[name=_token]').val(),
      'order_id': $(this).attr('data-order'),
      'printing': $row.find('.printing')[0].checked,
      'engraving1': $row.find('.engraving1')[0].checked,
      'engraving2': $row.find('.engraving2')[0].checked,          
      'assembly': $row.find('.assembly')[0].checked,
      'completed': $row.find('.completed')[0].checked
    }
  });

  toastr.success('Successfully saved', 'Success Alert', {timeOut: 5000});
});

https://jsfiddle.net/z1t5cnyg/

First, I'll point out that there's a difference between .attr('data-') and .data(). jQuery Data vs Attr?

Next, I cleared some redundant overhead and added a class for each checkbox. Classes are really nifty for organizing things logically and they allow you to easily format things with css.

Lastly, the part of the code that might need explanation. When you're working with jQuery, you're working with a jQuery object of the data rather than the data itself. The first item in the jQuery object is the data itself so using $(...)[0] on the checkbox returns the checkbox element itself. Then .checked is a property of a checkbox.

PoorlyWrittenCode
  • 1,003
  • 1
  • 7
  • 10
  • THANK YOU!!!! One question, sorry what does the 0 represent? Is that the first element found with this class? @PoorlyWrittenCode – FabricioG Apr 27 '18 at 22:04
  • Yes. if you `console.log($('.ct-primary'))`, I updated the fiddle to do this, you'll see it gives you an object with with all five of your checkboxes, a length property and a prevObject. With the first checkbox element having a key of 0, `[0]`, the second one having a key of 1, `[1]` and so on. jQuery also has a `.get()` method, but I'm more partial to the array notation. https://api.jquery.com/get/ – PoorlyWrittenCode Apr 28 '18 at 05:45