简体   繁体   English

切换复选框

[英]Toggle a checkbox

Basically if the url has cl=true , I want to toggle the checkbox 基本上,如果URL具有cl=true ,我想切换复选框

URL: http://localhost:8080/general-setup?cl=true 网址: http:// localhost:8080 / general-setup?cl = true

My code: 我的代码:

//auto toggle clone if cl=true
var url = window.location.href;
if(url.contains('cl=true')) {
    $('#existingImageToggler').click();
}

I got a error: 我收到一个错误:

Uncaught TypeError: url.contains is not a function 未捕获的TypeError:url.contains不是函数

Try below code snippet, 试试下面的代码片段,

//auto toggle clone if cl=true
if(window.location.href.contains("cl=true")) {
     var inputs = document.getElementsById("existingImageToggler");
    inputs[i].checked = !inputs[i].checked;
}

Convert URL to string and taht string to lowercase than check using contains methode 将URL转换为字符串,将taht字符串转换为小写,比使用contains方法检查

if("http://localhost:8080/general-setup?cl=true".toLowerCase().contains("cl=true")){
   //logic
}

Are you looking for something like this? 您是否正在寻找这样的东西?

if(window.location.href.indexOf("cl=true") > -1) {
     $('#existingImageToggler').prop('checked', true);
}

this is very basic checking if url contains cl=true 这是非常基本的检查,如果url包含cl=true

Use indexOf 使用indexOf

 var txt ='http://localhost:8080/general-setup?cl=true'; if (txt.indexOf('cl=true') != -1) { console.log($('#existingImageToggler').click()); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='existingImageToggler'></div> 

To toggle the checkbox, you can use the .prop() function. 要切换复选框,可以使用.prop()函数。

$('#existingImageToggler').prop('checked', window.location.href.indexOf('cl=true') != -1);

The second argument should be a boolean ( true|false ). 第二个参数应为布尔值( true|false )。 Instead of making an if-else construction, you can also put the condition in there... saves you some code... 除了进行if-else构造之外,您还可以在其中放置条件...为您节省一些代码...

You can do something like this 你可以做这样的事情

<input type="checkbox" id="chkid" name="">

<script>
//auto toggle clone if cl=true
var url = window.location.href;

if(url.search('cl=true') != -1) {
   $('#chkid').trigger('click');
}

</script>

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

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