簡體   English   中英

如何根據 Jquery 中的值選中復選框

[英]How to make checkbox checked according to a value in Jquery

我需要根據數據值檢查我的復選框的狀態。 到目前為止,我正在使用以下方法。

$(document).ready(function(){  
      $('#add').click(function(){  
           $('#insert').val("Insert");  
           $('#update_form')[0].reset();  
      });  
      $(document).on('click', '.update_data', function(){ 
           var row_id = $(this).attr("id");  
           
           $.ajax({  
                url:"./project/userdetail.php",  
                method:"POST",  
                data:{row_id:row_id},  
                dataType:"json", 
                success:function(data){  
                      ...........
                     if(data.accesslocations=='ABC,DEF,GHI'){
                      document.getElementById("check1").checked = true;
                      document.getElementById("check2").checked = true;
                      document.getElementById("check3").checked = true;
                      
                     }

                     if(data.accesslocations=='ABC,GHI'){
                      document.getElementById("check1").checked = true;
                      document.getElementById("check3").checked = true;
                      
                     }
                     if(data.accesslocations=='ABC'){
                      document.getElementById("check1").checked = true;
                     }

                    
                     
                     
                     ...........

                 $('#employee_id_update').val(data.row_id);  
                 $('#insert').val("Update");
                 $('#new_data_Modal').modal('show'); 
                        
                      
                }, 
                error: function(req, status, error) {
               alert(req.responseText);      
                }   
           });  
      });  

我的目的是檢查data.accesslocations並檢查它是否包含ABCABC,DEF同樣,

If ABC contains need to check1 status as checked.
If DEF contains need to check2 status as checked.
If GHI contains need to check3 status as checked.

我也試過下面的方法。 但是后來我無法打開我的對話框new_data_Modal

               if(strstr(data.accesslocations, "ABC")){
                  document.getElementById("check1").checked = true;
                 }

 const handleFoobarCheckboxes = (str) => { const values = str.split(","); document.querySelectorAll('[name="foobar[]"]').forEach(elCkb => { elCkb.checked = values.includes(elCkb.value); }); }; handleFoobarCheckboxes("GHI,ABC");
 <label><input name="foobar[]" type="checkbox" value="ABC"> ABC</label> <label><input name="foobar[]" type="checkbox" value="DEF"> DEF</label> <label><input name="foobar[]" type="checkbox" value="GHI"> GHI</label>

從上面的示例中可以看出,值的順序無關緊要,您的腳本仍然有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM