0

I have two address forms. One is billing, and the other is shipping. When the user checks the "ship to same address" checkbox, the shipping form is hidden.

When I pass the form before clicking on the checkbox, the form is not submitted. When the checkbox is checked, accurate data is sent for both forms, but when the user unchecks the box, the billing address posts three times.

I use jQuery and ajax code to submit the form.

    $(document).ready(function(){

      $('.le-checkbox').click(function(){

        if(this.checked) {
          $("#deliveryadd").hide();
          $(".le-checkbox").attr("checked", "checked");
          $('#submit').click(function(){
            var address= $('#address').val();
            var city_id= $('#city_id').val();
            var user = {{Auth::user()->id}};
            console.log(address,city_id,user);
            console.log(address,city_id,user);
            billing(address,city_id,user);
            shipping(daddress,dcity_id,user);
          });
        } 
        else {
          $("#deliveryadd").show();
          $(".le-checkbox").removeAttr("checked");
          $('#submit').click(function(){
            var address= $('#address').val();
            var city_id= $('#city_id').val();
            var user = {{Auth::user()->id}};
            console.log(address,city_id,user);
            billing(address,city_id,user);
          });
          $('#deliverySubmit').click(function(){    
            var daddress= $('#de_address').val();
            var dcity_id= $('#de_city_id').val();
            var user = {{Auth::user()->id}};
            console.log(daddress,dcity_id,user);    
            shipping(daddress,dcity_id,user);
          });
        }

      });

      function billing(baddress,bcity,buser){
        $.ajaxSetup({
          headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
        });
        $.ajax({
          url: '{{url("/billing-address")}}',
          type: 'post',
          dataType: 'html',
          data: {
            address:baddress,
            city_id:bcity,
            user_id:buser
          },
          success: function(result){
            $('#billing').html(result);
          }
        }).fail(function(jqXHR, textStatus, error){
          console.log(jqXHR.responseText);
        });
      }

      function shipping(saddress,scity,suser){
        $.ajaxSetup({
          headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
        });
        $.ajax({
          url: '{{url("/shipping-address")}}',
          type: 'post',
          dataType: 'html',
          data: {
            address:saddress,
            city_id:scity,
            user_id:suser
          },
          success: function(result){
            $('#shipping').html(result);
          }
        }).fail(function(jqXHR, textStatus, error){
          console.log(jqXHR.responseText);
        });
      }
    });

it's SHIPPING form code


        <h2 class="border h1">shipping address</h2>
        @if(App\Address::where('user_id',Auth::user()->id)->where('type','Delivery')->exists())
        <address class="bold" id="addr">
            @foreach ($collection = Auth::user()->address as $item)
            @if ($item->type == 'Delivery')
                {{$item->street}},<br>
                {{$item->city->name}},<br>
                {{$item->city->parent->name}}
                @endif    
            @endforeach
            </address>
        @else
    <div class="billing-address" id="deliveryadd">
                               <div class="row field-row">
                                <div class="col-xs-12">
                                    <label>address*</label>
                                    <input class="le-input" type="text" id="de_address" data-placeholder="Street address" name="de_address">
                                </div>
                            </div><!-- /.field-row -->

                            <div class="row field-row">
                                <div class="col-xs-12 col-sm-6">
                                    <label>City*</label>
                                    <select class="le-input">
                                        <option>Lahore</option>
                                    </select>
                                </div>
                                <div class="col-xs-12 col-sm-6">
                                    <label>&nbsp;</label>
                                    <select class="le-input" id="de_city_id">
                                    <option value="null">Select Town</option>
                                    @foreach ($collection = App\City::where('parent_id','!=', '0')->get() as $item)
                                    <option value="{{$item->id}}">{{$item->name}}</option>
                                    @endforeach
                                </select>
                                </div>
                            </div><!-- /.field-row -->

                            <button id="deliverySubmit" class="le-button big">Save</button>
        </div><!-- /#shipping-address -->
        <div class="row field-row">
                <div class="col-xs-12">
                    <input name="same" class="le-checkbox big" type="checkbox" />
                    <a class="simple-link bold" href="#">ship to Same address?</a>
                </div>
            </div><!-- /.field-row -->
            @endif

and it's Billing Form HTML code

<h2 class="border h1">billing address</h2>
{{-- <a style="float: right;" href="javascript:;" id="edit">Edit</a> --}}
                @if(App\Address::where('user_id',Auth::user()->id)->where('type','Billing')->exists())
                <address class="bold" id="addr">
                    @foreach ($collection = Auth::user()->address as $item)
                    @if ($item->type == 'Billing')
                        {{$item->street}},<br>
                        {{$item->city->name}},<br>
                        {{$item->city->parent->name}}
                        @endif    
                    @endforeach
                    </address>
                @else
                    <div class="row field-row">
                        <div class="col-xs-12">
                            <label>address*</label>
                            <input class="le-input" type="text" id="address" data-placeholder="Street address">
                        </div>
                    </div><!-- /.field-row -->

                    <div class="row field-row">
                        <div class="col-xs-12 col-sm-6">
                            <label>City*</label>
                            <select class="le-input">
                                <option>Lahore</option>
                            </select>
                        </div>
                        <div class="col-xs-12 col-sm-6">
                            <label>&nbsp;</label>
                            <select class="le-input" id="city_id">
                            <option value="null">Select Town</option>
                            @foreach ($collection = App\City::where('parent_id','!=', '0')->get() as $item)
                            <option value="{{$item->id}}">{{$item->name}}</option>
                            @endforeach
                        </select>
                        </div>
                    </div><!-- /.field-row -->

                    <button id="submit" class="le-button big">Save</button>
                @endif
  • I made provisional edits to your question to try to make it more clear. I hope I understood your meaning correctly. (It might help people to provide useful answers if if you can also include your HTML markup.) – Cat Apr 26 '19 at 09:28
  • Thanks Cat i'll update with HTML code – Rana Raheel Tariq Apr 26 '19 at 13:07

1 Answers1

2

Your code is assigning event handlers to clicks on your submit buttons when a checkbox is clicked. That means:

  • if the checkbox is not clicked, no event handers for those button clicks are set. So clicking the buttons will not do any of your JS submission stuff - but it will probably do the normal non-JS form submission;

  • if you click the checkbox one time, eg to tick it, you add an event handler to your #submit button. If you now untick the checkbox, you add another event handler to your #submit button, and one on your #deliverySubmit button! Unticking the checkbox does not remove the event handler you added previously. So if you click #submit, both handlers will fire. If you tick and untick the checkbox more times, you just keep piling up additional event handlers, all of which will run when you finally click the button.

This is not a good approach. Instead, you should set up your event handlers independent of user interactions, and have the code work out what to do based on checkbox state.

Some other observations:

  • To track clicks on a checkbox, you should use $('.le-checkbox').on('change', function() {, not click;

  • I am not sure why you are manually setting checkbox state (eg $(".le-checkbox").attr("checked", "checked");) when the checkbox is ticked? I would not do that, it will surely just cause problems, and isn't actually doing anything.

  • In you #submit handler when the checkbox is ticked, you have shipping(daddress,dcity_id,user);, but those variables are not set. If the checkbox is ticked, then shipping == billing, so I think you really mean shipping(address, city_id, user);, right?

  • I am not sure why your checkbox text is an actual link? That just complicates things - just use a label, so that clicking the text will properly toggle the checkbox.

  • You haven't shown us your #submit button HTML, so I don't know - why do you have 2 buttons? Isn't one enough?

Putting all this together, try something like this:

$('#submit').click(function(){
    var $checkbox=$('.le-checkbox'),
        address= $('#address').val(),
        city_id= $('#city_id').val(),
        daddress= $('#de_address').val(),
        dcity_id= $('#de_city_id').val(),
        user = {{Auth::user()->id}};

    // Billing address is always sent, no matter the checkbox state
    billing(address, city_id, user);

    // Shipping address depends on checkbox state
    if ($checkbox.is(':checked') {
        shipping(address, city_id, user);
    } else {
        shipping(daddress, dcity_id, user);
    }
});


$('.le-checkbox').on('change', function(){
    $("#deliveryadd").toggle();
    // .toggle() is simpler than .show() and .hide()
    // if (this.checked) {
    //     $("#deliveryadd").hide();
    // } else {
    //     $("#deliveryadd").show();
    // }
}
Don't Panic
  • 13,965
  • 5
  • 32
  • 51
  • i'm use to type of form that's why i'm use two save button #submit button save billing address and if use not checked the checkbox then delivery address save with #deliverysubmit button – Rana Raheel Tariq Apr 26 '19 at 18:19
  • Not i'm update Billing address HTML code you can understand batter and give me your good response Thank you – Rana Raheel Tariq Apr 26 '19 at 18:19
  • Thanks Man it's working for me with little-bit changing – Rana Raheel Tariq Apr 26 '19 at 18:32
  • Great, glad it helped! :-) I am rolling back the edit you made to my code. I understand you needed to change it for your use, that's fine and I'm glad you were able to get it working. But on SO my answer should represent *my answer*, not the final result you ended up using. If there was a bug of course please let me know, and I will fix it! :-) – Don't Panic Apr 26 '19 at 19:02
  • Not an issue i understand it's your answer and always is your. Thank you for your help – Rana Raheel Tariq May 04 '19 at 12:17