[英]Change button behaviour if checkbox is checked
I have a checkbox which functions as a toggle and when clicked submits a form with the check / unchecked status being used to enable / disable the service. 我有一个复选框,它可以用作切换按钮,单击后将提交一个带有选中/未选中状态的表单,用于启用/禁用该服务。
However, I now have an API which selects preferences based on location and I want to: 但是,我现在有一个API,可以根据位置选择首选项,我想:
Click submit if the checkbox is unchecked 如果未选中此复选框,则单击提交
Click apply if the checkbox is checked 如果选中此复选框,请单击“应用”。
Currently I have $(“#checkbox”).click();
目前,我有
$(“#checkbox”).click();
if the user calls the API and I'm not sure how to implement this where $(“#apply”).click();
如果用户调用了API,但我不确定如何在
$(“#apply”).click();
实现该方法$(“#apply”).click();
would be used if the checkbox was checked already to avoid turning the service off. 如果已选中该复选框以避免关闭服务,则将使用此选项。 I've tried
$('#checkbox').attr
but not having problems with it. 我试过
$('#checkbox').attr
但没有问题。
$(‘#apicall’).off('click').on('click', function () {
$.ajax({
type: 'GET',
dataType: 'json',
url: "https:// [PRIVATE API REDACTED]“,
success : function(result){
console.log(result);
result=result.successData.server;
best_ovpn=best_ovpn.trim();
$(“#dropdown”).val(apical);
show_openvpn_status();
if($('#checkbox').attr('checked')) {
$(" # checkbox ").click();
} else {
$(" # apply ").click();
}
});
});
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if(this.checked){
alert("Checkbox is checked.");
}
else if(!(this.checked)){
alert("Checkbox is unchecked.");
}
});
});
You can use this code to check whether a checkbox is checked or not. 您可以使用此代码来检查是否选中了一个复选框。 You can make appropriate api calls based on its status.
您可以根据其状态进行适当的api调用。
$('#checkbox').on('change', function(){
if($(this).is(':checked')){
alert('checked');
}else{
alert('unchecked');
}
});
if you want to know if the checkbox is checked, you can use .is method of jQuery along with :checked
like this: 如果您想知道是否选中了该复选框,则可以将jQuery的.is方法与
:checked
一起使用,如下所示:
$(function(){ console.log("Checkbox1", $("#checkbox1").is(":checked")); console.log("Checkbox2", $("#checkbox2").is(":checked")); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="checkbox1" type="checkbox" checked /> <input id="checkbox2" type="checkbox" />
and when you want to check the checkbox you can use .prop method : 当您想选中复选框时,可以使用.prop方法:
$(function(){ $('#checkbox').prop('checked', true); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" id="checkbox" /> <p>Checked the checkbox using jQuery</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.