0

I am struggling to make it work to pass element id to Jquery from html foreach loop. I have a table and I am getting the details from database. so in each loop we are getting new data for new users. I am using bootstrap switch as seen below :

   <form method="post" id="toggleForm">
                            <fieldset>
                                <div class="form-group">
                                    <div class="custom-control custom-switch">
                                        <input type="checkbox" class="custom-control-input" id="customSwitch1" name='machine_state' status="{{$detail['status']}}">

                                    <input type="hidden" id="id" value="{{$detail['id']}}" >
                                        <label class="custom-control-label" id="statusText" for="customSwitch1"> </label>
                                        <llittle id ="littleupdate"></llittle>
                                    </div>
                                </div>
                            </fieldset>
                        </form>

In the Jquery part we have three functions as shown below:

 function putStatus() {
   var id = $("#id").val();
    
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: "post",
            url: "/admin/check-status",
            data: {id : id},
    
            success: function (result) {
                if (result == "true") {
                    $('#customSwitch1').prop('checked', true);
                    statusText(1);
                } else {
                    $('#customSwitch1').prop('checked', false);
                    statusText(0);
                }
            }, error:function (){
    
            }
        });
    }
    function statusText(status_val) {
        if (status_val == 1) {
            var status_str = "Active";
        } else {
            var status_str = "Inactive";
        }
        document.getElementById("statusText").innerText = status_str;
    }
    function onToggle() {
        $('#toggleForm :checkbox').change(function () {
            if (this.checked) {
    
                //alert('checked');
                updateStatus(1);
                // statusText(1);
            } else {
                //alert('NOT checked');
                updateStatus(0);
                // statusText(0);
            }
        });
    }
    function updateStatus(status_val) {
        var id = $('#id').val();
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: "POST",
            url: "/admin/set-status",
            data: {status: status_val, id:id},
            success: function (result) {
                if(result =="true") {
                    if(status_val == 1) {
                        $('#customSwitch').prop('checked', true);
                        // $("#updatedAt").fadeIn(0).html("<font color='green' font size='2px'>  - Updated.. User Activated!</font>").fadeOut(1500);
                        // $( '#littleupdate').fadeIn(0).html("<font color='green' font size='1px'> Updated.. </font>").fadeOut(1500);
                        statusText(1);
    
                    } else if(status_val == 0){
                        $('#customSwitch').prop('checked', false);
                        // $("#updatedAt").fadeIn(0).html("<font color='green' font size='2px'>  - Updated.. User Deactivated!</font>").fadeOut(1500);
                        // $( '#littleupdate').fadeIn(0).html("<font color='green' font size='1px'> Updated.. </font>").fadeOut(1500);
                        statusText(0);
                    }
                } else {
                    if(status_val == 1){
                        $('#customSwitch1').prop('checked', false);
                       $("#updatedAt").fadeIn(0).html("<font color='red'> -  Error while updating!</font>").fadeOut(1500);
                    } else if(status_val == 0){
                        $('#customSwitch1').prop('checked', true);
                        $("#updatedAt").fadeIn(0).html("<font color='red'> - Error while updating!</font>").fadeOut(1500);
                    }
                }
            }, error:function (){
    
            }
        });
    }
    
    $(document).ready(function () {
        //Called on page load:
        putStatus();
        onToggle();
        statusText();
    });

Html loop as a whole is looking like below:

   @foreach($details as $detail)
                                <tr>
                                    <td>
                                        {{$detail['id']}}
                                    </td>
                                    <td>
                                        {{$detail['name']}}
                                    </td>
                                    <td>
                                        {{$detail['type']}}
                                    </td>
                                    <td>
                                        {{$detail['email']}}
                                    </td>
                                    <td>
                                        <img src="{{asset('/admin/images/avatars/'.$detail['image'])}}">
                                    </td>
                                    <td>
                                        {{$detail['mobile']}}
                                    </td>
                                    <td>



                        <form method="post" id="toggleForm">
                            <fieldset>
                                <div class="form-group">
                                    <div class="custom-control custom-switch">
                                        <input type="checkbox" class="custom-control-input" id="customSwitch1" name='machine_state' status="{{$detail['status']}}">

                                        <input type="hidden" id="id" value="{{$detail['id']}}" >
                                        <label class="custom-control-label" id="statusText" for="customSwitch1"> </label>
                                        <llittle id ="littleupdate"></llittle>
                                    </div>
                                </div>
                            </fieldset>
                        </form>

                                    </td>

I really can't figure out the mechanism of passing the function to each loop element, as it only works correctly for the first instance in the table as can be seen in image below. Your help would be highly appreciated.

enter image description here

1
  • You are using duplicate ids, (invalid HTML) js will only act on the first one, as there should be only one. You need to use a class instead. Commented Aug 26, 2022 at 15:50

1 Answer 1

1

Because in loop , the id attribute is the same

In loop

<form method="post" id="toggleForm_{{$detail['id']}}">
    <fieldset>
        <div class="form-group">
            <div class="custom-control custom-switch">
                <input type="checkbox" class="custom-control-input" id="customSwitch_{{$detail['id']}}" name='machine_state' status="{{$detail['status']}}">

                <input type="hidden" class="statusForDetail" value="{{$detail['id']}}" >
                <label class="custom-control-label" id="statusText_{{$detail['id']}}" for="customSwitch_{{$detail['id']}}"> </label>
                <llittle id="littleupdate_{{$detail['id']}}"></llittle>
            </div>
        </div>
    </fieldset>
</form>

function putStatus() {
    $(".statusForDetail").each((index, element) => { 
        let id = $(element).val()
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: "post",
            url: "/admin/check-status",
            data: {id : id},
    
            success: function (result) {
                if (result == "true") {
                    $('#customSwitch_'+id).prop('checked', true);
                    statusText(1);
                } else {
                    $('#customSwitch_'+id).prop('checked', false);
                    statusText(0);
                }
            }, error:function (){
    
            }
        });
    });
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for the solution. The only issue I have is at ` $('#toggleForm :checkbox').change(function () {` , however I need to find out the way to make it work when it is toggled.
@OrkhanOrkhan The problem is that onToggle() calls updateStatus() which calls id = $('#id').val();, which is not correct because there is no longer such an element in this answer posted by @フクちゃん. You could refactor onToggle() so it passes $(this) as an argument to updateStatus().
when I change the status all statuses are changing.. I think there is a problem in : $("#toggleForm_" + id + ":checkbox").change(function ()
Yeah I figured it out finally. Thanks for all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.