Nikki
8 months ago

Saving 2 radio buttons

Posted 8 months ago by Nikki

In my page I can have multiple addresses, but the user can only select one address. The problem I'm having is that both my radio buttons are being saved instead of just one. So if the user has 2 addresses then only one should have selected = 1 and the other address should be selected = 0, but at the moment both address = 1

My form

@foreach($addresses as $address)
    <div class="col-lg-4">
        <form id="address-radio" action="{{ route('account.post.addresses.radio', $address->id) }}" method="post">
            @csrf
            <div class="form-check">
                <input type="radio" class="form-check-input" name="address_option" id="address_{{ $address->id }}" {!! $address->selected == '1' ? 'checked' : '' !!}>
                <label for="address_{{ $address->id }}" class="form-check->label">
                    @if(!empty($address->complex))
                        {{ $address->complex }} <br>
                    @endif
                    {{ $address->address }} <br>
                    {{ $address->suburb }} <br>
                    {{ $address->city }} <br>
                    {{ $address->province }} <br>
                    {{ $address->postal_code }} <br>
                </label>
            </div>
        </form>
    </div>
@endforeach

<script>
    $(document).ready(function(){
        $('input[type="radio"]').on('change', function(){
            $(this).closest("form").submit();
        })
    })
</script>

and this is my function

public function postAddressesRadio(Request $request, $id)
{
    $selected = Address::findOrFail($id);

    if($request->address_option == 'on'){
        $selected->selected = '1';
    }else{
        $selected->selected = '0';
    }

    $selected->save();

    return redirect()->back()->with('success', 'Address was updated');
}

Please sign in or create an account to participate in this conversation.