Home > Net >  Passing element id to jQuery from html loop
Passing element id to jQuery from html loop

Time:08-27

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 >
                                    <div >
                                        <input type="checkbox"  id="customSwitch1" name='machine_state' status="{{$detail['status']}}">

                                    <input type="hidden" id="id" value="{{$detail['id']}}" >
                                        <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 >
                                    <div >
                                        <input type="checkbox"  id="customSwitch1" name='machine_state' status="{{$detail['status']}}">

                                        <input type="hidden" id="id" value="{{$detail['id']}}" >
                                        <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

CodePudding user response:

Because in loop , the id attribute is the same

In loop

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

                <input type="hidden"  value="{{$detail['id']}}" >
                <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 (){
    
            }
        });
    });
}
  • Related