简体   繁体   中英

Shipping address same as Billing Address when checkbox is checked and submit form using ajax

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

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();
    // }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM