简体   繁体   English

使用Jquery在页面加载时有条件地选中此框

[英]Check the box conditionally upon page load using Jquery

Upon page load all of the check boxes remain unchecked (pic below), I'm getting value1 text from java session and storing it under JSON object, now I'm comparing if the value1 text of the below page matches with value1 text I'm getting from session. 页面加载后,所有复选框均保持未选中状态(如下图所示),我从Java会话中获取了value1文本并将其存储在JSON对象下,现在我正在比较以下页面的value1文本是否与value1文本匹配:我从会议开始。 If match found then make the check box true else keep it unchecked. 如果找到匹配项,则使复选框为true,否则不要选中它。 I'm trying below, but it checks all the boxes.. 我在下面尝试,但是它选中了所有框。

<script type="text/javascript">
            $.s1.proxy.contentReady(function() {
                var sessionValue = <%= json %>;  //loaded from java session
                sessionValue.forEach(function(sessionValue) {
                         $("input:checkbox[name=myFormProperties]").each(function(){      
                            var val = $(this).closest("tr").find("td:nth-child(2)").text().trim();
                             if(val!=null && val!=''){
                                 if (sessionValue.startsWith(val)) {
                                    alert("session and page value match found ");
                                     $("input:checkbox[name=myFormProperties]").attr('checked', true); // this makes all the checkbox value true. How to make only //specific check box value true here
                                }
                             }
                        });
                    });
            });

        </script> 

Upon check box true that selected value come as a link next to the check box as shown in pic. 选中复选框后,所选值将作为复选框旁边的链接出现,如图所示。 复选框

That's because you are setting it on all the checkboxes with name myFormProperties. 那是因为您要在所有名为myFormProperties的复选框上进行设置。

Instead of $("input:checkbox[name=myFormProperties]").attr('checked', true); 代替$("input:checkbox[name=myFormProperties]").attr('checked', true); (which just selects all the checkboxes again), just select the current checkbox from the each loop like this (只需再次选择所有复选框),只需从每个循环中选择当前复选框即可,如下所示

$(this).attr('checked',true);

You are making all the check box checked with your code 您正在用代码选中所有复选框

$("input:checkbox[name=myFormProperties]").attr('checked', true);    

For checking the checkbox with value use below 要选中带有值的复选框,请在下面使用

$("input[value='" + val + "']").prop('checked', true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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