jQuery, how do I call a url by checking a checkbox - javascript

I have this:
<span id="social">
Facebook:
<input id="id_connected_to_facebook" type="checkbox" name="connected_to_facebook">
<br>
Twitter:
<input id="id_connected_to_twitter" type="checkbox" name="connected_to_twitter">
<br>
</span>
and with jQuery I would like to call a different URL for all the 4 possible actions (1: check facebook, 2: uncheck facebook, 3: check twitter, 4: uncheck twitter).
How would I do that?

I am not sure what you are going for. If you want to redirect to a page on clicking on the check box you can do this
Specify what url you want to call in your checkbox element using data attribute
<input type="checkbox" data-target="http://www.facebook.com" />
Script is
$(function(){
$("input[type='checkbox']").change(function(){
var item=$(this);
if(item.is(":checked"))
{
window.location.href= item.data("target")
}
});
});
Sample JsFiddle : http://jsfiddle.net/45aZ8/2/
EDIT : If you want to open it in a new window, use window.open method instead of updating the current url
Replace
window.location.href= item.data("target")
with
window.open(item.data("target")
http://www.w3schools.com/jsref/met_win_open.asp
EDIT 3 : Based on comment : If you want to load one url on Checked state and load another url on uncheck, you can do like this
Give 2 data attributes for each checkbox. One for checked state and one for unchecked
Facebook<input type="checkbox" data-target="http://www.facebook.com" data-target-off="http://www.google.com" /> <br/>
Twitter<input type="checkbox" data-target="http://www.twitter.com" data-target-off="http://www.asp.net" /> <br/>
And the script is
$(function(){
$("input[type='checkbox']").change(function(){
var item=$(this);
if(item.is(":checked"))
{
window.open(item.data("target"))
}
else
{
window.open(item.data("target-off"))
}
});
})
Working sample : http://jsfiddle.net/45aZ8/5/

$('input[type="checkbox"]').change(function() {
if($(this).is(':checked')) {
if($(this).attr('id') == 'connected_to_facebook') {
// possibility: 1
} else {
// possibility: 3
}
} else {
if($(this).attr('id') == 'connected_to_facebook') {
// possibility: 2
} else {
// possibility: 4
}
}
});

$('#id_connected_to_facebook, #id_connected_to_twitter').click(function(){
$.post('http://target.url', {this.id:this.checked});
});
now you'll get in $_POST either id_connected_to_facebook or id_connected_to_twitter and as a value it would be 1 or 0

Related

Create button which takes to a particular URL according to data in Form Field

I've two input form fields and i want when the user clicks a submit button he should be taken to a URL based on the input in these two fields. For example if the input in the two input fields is A and B respectively the condition should be set such that the User is taken to www.mydomain.com/C in Javascript. I DON'T want the values to be appended to the URL like www.mydomain.com/a/b which I already know how to.
I have seen lot of questions on SO and Google on URL Generation but none was the case as mine. I would really appreciate help from fellow SO users. Thanks in advance.
Do you mean something like this? This would take you to the address when both inputs have the value 'something' and the button is clicked.
<input type="text" id="a">
<input type="text" id="b">
<button onclick="go()">Go</button>
<script>
function go() {
if (document.getElementById('a').value == 'something' && document.getElementById('b').value == 'something') {
window.location = 'http://www.example.com/C';
}
}
</script>
If you are using jquery:
$( "form" ).submit(function() {
// TODO read your variables
// TODO apply conditions and redirect accordingly
if ( ... ) {
window.location = 'http://www.example.com/C'
} else {
window.location = 'http://www.example.com/D'
}
return false; // prevent default submit
});

How to keep Checkboxes checked after refresh the page [duplicate]

hi i am javascript newbie.
I have checkbox that slideDown other input , i want to keep that checkbox checked and the other input showed after refreshing the page if the input checkbox checked
javascript:
function validateSitec(){
if (document.getElementById('sitecheck').checked){
$('#sitecheck').prop('checked', true);
$('#closedmsg').slideDown();
}else{
$('#closedmsg').slideUp();
$("#sitecheck").removeProp("checked").checkboxradio("refresh");
}
}
this my inputs:
<label for="sitecheck">
<span style="font-weight:bold;">close site+ msg:</span>
</label>
<input name="" type="checkbox" id="sitecheck" onclick="validateSitec()" /><span style="font-weight:bold;">click to activate msg</span><br>
<input type="text" name="closedmsg" id="closedmsg" style="width:440px;height:120px;display:none;" value="enter closed msg.."/>
i want if checked stay checked.. and wont change after refreshing the page , then when unchecked so back to normal and be unchecked when refreshing the page..
should i use php for making it not change after checking with javascript?
Edited:
Thanks to all for helping
credit goes to : leiyonglin .
The working code for anyone who like to use it:
download first:
https://github.com/carhartl/jquery-cookie
then use this codes working awesome :
JavaScript:
<script type="text/javascript">
function validateSitec(){
if (document.getElementById('sitecheck').checked){
$('#sitecheck').prop('checked', true);
$('#closedmsg').slideDown();
$.cookie("cookieChecked", "#sitecheck");
}else{
$('#closedmsg').slideUp();
$("#sitecheck").removeProp("checked");
$.cookie("cookieChecked","");
}
}
$(function(){
var cookieChecked = $.cookie("cookieChecked");
if(cookieChecked){
$('#sitecheck').prop('checked', true);
$('#closedmsg').show();
}else{
$("#sitecheck").removeProp("checked");
$('#closedmsg').hide();
}
})
</script>
html inputs:
<label for="sitecheck">
<span style="font-weight:bold;">close site temp:</span>
</label>
<input name="" type="checkbox" id="sitecheck" onclick="validateSitec()" /><span style="font-weight:bold;">close site and add message</span><br>
<input type="text" name="closedmsg" id="closedmsg" style="width:440px;height:120px;display:none;" value="<?php echo $data['csitemsg']; ?>" />
This working perfect thx again all.
You can use cookie to maintain your data on page refresh by using cookie. I notice you are using JQuery in your code. Here is a JQuery-Cookie plugin which will let you use cookie to manage your data across page refresh.
https://github.com/carhartl/jquery-cookie
Go to Usage section and you will find how to create, read, delete and set expire easily form the plugin.
Set cookies:
Save the checked element in cookieChecked
function validateSitec(){
if (document.getElementById('sitecheck').checked){
$('#sitecheck').prop('checked', true);
$('#closedmsg').slideDown();
$.cookie("cookieChecked", "#sitecheck");
}else if(document.getElementById('closedmsg').checked){
$('#closedmsg').slideUp();
$("#sitecheck").removeProp("checked").checkboxradio("refresh");
$.cookie("cookieChecked", "#closedmsg");
} else {
$.cookie("cookieChecked","");
}
}
When page onload
$(function(){
var cookieChecked = $.cookie("cookieChecked");
if(cookieChecked){
$(cookieChecked).trigger("click");
}
})
I use the jquery cookie plugin : https://github.com/carhartl/jquery-cookie
Identify the page refresh event and store the status of check box in cache or local storage. After refresh completes based on the checked status perform your logic
Try this, not use additional plugin:
<script>
function validateSitec(){
if (document.getElementById('sitecheck').checked){
$('#sitecheck').prop('checked', true);
$('#closedmsg').slideDown();
document.cookie="sitecheck=site_checked";
}else{
$('#closedmsg').slideUp();
$("#sitecheck").removeProp("checked").checkboxradio("refresh");
document.cookie="sitecheck=site_unchecked";
}
}
</script>
When document ready:
<script>
$(function(){
var kuki=read_cookie("sitecheck");
if(kuki=="site_checked"){
$('#sitecheck').prop('checked', true);
$('#closedmsg').slideDown();
}else{
$('#closedmsg').slideUp();
$("#sitecheck").removeProp("checked").checkboxradio("refresh");
}
});
</script>
Read cookies
<script>
function read_cookie(name) {
var name = name + "=";
var kukiAri = document.cookie.split(';');
for(var i=0;i < kukiAri.length;i++) {
var kuki = kukiAri[i];
while (kuki.charAt(0)==' ') kuki = kuki.substring(1,kuki.length);
if (kuki.indexOf(name) == 0)
return kuki.substring(name.length,kuki.length);
}
return null;
};
</script>

Change/Get check state of CheckBox

I just want to get/change value of CheckBox with JavaScript. Not that I cannot use jQuery for this. I've tried something like this but it won't work.
JavaScript function
function checkAddress()
{
if (checkAddress.checked == true)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onchange="checkAddress()" />
Using onclick instead will work. In theory it may not catch changes made via the keyboard but all browsers do seem to fire the event anyway when checking via keyboard.
You also need to pass the checkbox into the function:
function checkAddress(checkbox)
{
if (checkbox.checked)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onclick="checkAddress(this)" />
You need to retrieve the checkbox before using it.
Give the checkbox an id attribute to retrieve it with document.getElementById(..) and then check its current state.
For example:
function checkAddress()
{
var chkBox = document.getElementById('checkAddress');
if (chkBox.checked)
{
// ..
}
}
And your HTML would then look like this:
<input type="checkbox" id="checkAddress" name="checkAddress" onclick="checkAddress()"/>
(Also changed the onchange to onclick. Doesn't work quite well in IE :).
I know this is a very late reply, but this code is a tad more flexible and should help latecomers like myself.
function copycheck(from,to) {
//retrives variables "from" (original checkbox/element) and "to" (target checkbox) you declare when you call the function on the HTML.
if(document.getElementById(from).checked==true)
//checks status of "from" element. change to whatever validation you prefer.
{
document.getElementById(to).checked=true;
//if validation returns true, checks target checkbox
}
else
{
document.getElementById(to).checked=false;
//if validation returns true, unchecks target checkbox
}
}
HTML being something like
<input type="radio" name="bob" onclick="copycheck('from','to');" />
where "from" and "to" are the respective ids of the elements "from" wich you wish to copy "to".
As is, it would work between checkboxes but you can enter any ID you wish and any condition you desire as long as "to" (being the checkbox to be manipulated) is correctly defined when sending the variables from the html event call.
Notice, as SpYk3HH said, target you want to use is an array by default. Using the "display element information" tool from the web developer toolbar will help you find the full id of the respective checkboxes.
Hope this helps.
You need this:
window.onload = function(){
var elCheckBox=document.getElementById("cbxTodos");
elCheckBox.onchange =function (){
alert("como ves");
}
};
Needs to be:
if (document.forms[0].elements["checkAddress"].checked == true)
Assuming you have one form, otherwise use the form name.
As a side note, don't call the element and the function in the same name it can cause weird conflicts.
<input type="checkbox" name="checkAddress" onclick="if(this.checked){ alert('a'); }" />
I know this is late info, but in jQuery, using .checked is possible and easy!
If your element is something like:
<td>
<input type="radio" name="bob" />
</td>
You can easily get/set checked state as such:
$("td").each(function()
{
$(this).click(function()
{
var thisInput = $(this).find("input[type=radio]");
var checked = thisInput.is(":checked");
thisInput[0].checked = (checked) ? false : true;
}
});
The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object!
ENJOY!
This is an example of how I use this kind of thing:
HTML :
<input type="checkbox" id="ThisIsTheId" value="X" onchange="ThisIsTheFunction(this.id,this.checked)">
JAVASCRIPT :
function ThisIsTheFunction(temp,temp2) {
if(temp2 == true) {
document.getElementById(temp).style.visibility = "visible";
} else {
document.getElementById(temp).style.visibility = "hidden";
}
}
var val = $("#checkboxId").is(":checked");
Here is a quick implementation with samples:
Checkbox to check all items:
<input id="btnSelectAll" type="checkbox">
Single item (for table row):
<input class="single-item" name="item[]" type="checkbox">
Js code for jQuery:
$(document).on('click', '#btnSelectAll', function(state) {
if ($('#btnSelectAll').is(':checked')) {
$('.single-item').prop('checked', true);
$('.batch-erase').addClass('d-block');
} else {
$('.single-item').prop('checked', false);
$('.batch-erase').removeClass('d-block');
}
});
Batch delete item:
<div class="batch-erase d-none">
<a href="/path/to/delete" class="btn btn-danger btn-sm">
<i class="fe-trash"></i> Delete All
</a>
</div>
This will be useful
$("input[type=checkbox]").change((e)=>{
console.log(e.target.checked);
});

How do I check whether a checkbox is checked in jQuery?

I need to check the checked property of a checkbox and perform an action based on the checked property using jQuery.
For example, if the age checkbox is checked, then I need to show a textbox to enter age, else hide the textbox.
But the following code returns false by default:
if ($('#isAgeSelected').attr('checked')) {
$("#txtAge").show();
} else {
$("#txtAge").hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">
Age is selected
</div>
How do I successfully query the checked property?
How do I successfully query the checked property?
The checked property of a checkbox DOM element will give you the checked state of the element.
Given your existing code, you could therefore do this:
if(document.getElementById('isAgeSelected').checked) {
$("#txtAge").show();
} else {
$("#txtAge").hide();
}
However, there's a much prettier way to do this, using toggle:
$('#isAgeSelected').click(function() {
$("#txtAge").toggle(this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>
Use jQuery's is() function:
if($("#isAgeSelected").is(':checked'))
$("#txtAge").show(); // checked
else
$("#txtAge").hide(); // unchecked
Using jQuery > 1.6
<input type="checkbox" value="1" name="checkMeOut" id="checkMeOut" checked="checked" />
// traditional attr
$('#checkMeOut').attr('checked'); // "checked"
// new property method
$('#checkMeOut').prop('checked'); // true
Using the new property method:
if($('#checkMeOut').prop('checked')) {
// something when checked
} else {
// something else when not
}
jQuery 1.6+
$('#isAgeSelected').prop('checked')
jQuery 1.5 and below
$('#isAgeSelected').attr('checked')
Any version of jQuery
// Assuming an event handler on a checkbox
if (this.checked)
All credit goes to Xian.
I am using this and this is working absolutely fine:
$("#checkkBoxId").attr("checked") ? alert("Checked") : alert("Unchecked");
Note: If the checkbox is checked it will return true otherwise undefined, so better check for the "TRUE" value.
Use:
<input type="checkbox" name="planned_checked" checked id="planned_checked"> Planned
$("#planned_checked").change(function() {
if($(this).prop('checked')) {
alert("Checked Box Selected");
} else {
alert("Checked Box deselect");
}
});
$("#planned_checked").change(function() {
if($(this).prop('checked')) {
alert("Checked Box Selected");
} else {
alert("Checked Box deselect");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" name="planned_checked" checked id="planned_checked"> Planned
Since jQuery 1.6, the behavior of jQuery.attr() has changed and users are encouraged not to use it to retrieve an element's checked state. Instead, you should use jQuery.prop():
$("#txtAge").toggle(
$("#isAgeSelected").prop("checked") // For checked attribute it returns true/false;
// Return value changes with checkbox state
);
Two other possibilities are:
$("#txtAge").get(0).checked
$("#txtAge").is(":checked")
This worked for me:
$get("isAgeSelected ").checked == true
Where isAgeSelected is the id of the control.
Also, #karim79's answer works fine. I am not sure what I missed at the time I tested it.
Note, this is answer uses Microsoft Ajax, not jQuery
If you are using an updated version of jquery, you must go for .prop method to resolve your issue:
$('#isAgeSelected').prop('checked') will return true if checked and false if unchecked. I confirmed it and I came across this issue earlier. $('#isAgeSelected').attr('checked') and $('#isAgeSelected').is('checked') is returning undefined which is not a worthy answer for the situation. So do as given below.
if($('#isAgeSelected').prop('checked')) {
$("#txtAge").show();
} else {
$("#txtAge").hide();
}
Use:
<input type="checkbox" id="abc" value="UDB">UDB
<input type="checkbox" id="abc" value="Prasad">Prasad
$('input#abc').click(function(){
if($(this).is(':checked'))
{
var checkedOne=$(this).val()
alert(checkedOne);
// Do some other action
}
})
This can help if you want that the required action has to be done only when you check the box not at the time you remove the check.
You can try the change event of checkbox to track the :checked state change.
$("#isAgeSelected").on('change', function() {
if ($("#isAgeSelected").is(':checked'))
alert("checked");
else {
alert("unchecked");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="isAgeSelected" />
<div id="txtAge" style="display:none">
Age is selected
</div>
Using the Click event handler for the checkbox property is unreliable, as the checked property can change during the execution of the event handler itself!
Ideally, you'd want to put your code into a change event handler such as it is fired every time the value of the check box is changed (independent of how it's done so).
$('#isAgeSelected').bind('change', function () {
if ($(this).is(':checked'))
$("#txtAge").show();
else
$("#txtAge").hide();
});
I ran in to the exact same issue. I have an ASP.NET checkbox
<asp:CheckBox ID="chkBox1" CssClass='cssChkBox1' runat="server" />
In the jQuery code I used the following selector to check if the checkbox was checked or not, and it seems to work like a charm.
if ($("'.cssChkBox1 input[type=checkbox]'").is(':checked'))
{ ... } else { ... }
I'm sure you can also use the ID instead of the CssClass,
if ($("'#cssChkBox1 input[type=checkbox]'").is(':checked'))
{ ... } else { ... }
I hope this helps you.
I believe you could do this:
if ($('#isAgeSelected :checked').size() > 0)
{
$("#txtAge").show();
} else {
$("#txtAge").hide();
}
I decided to post an answer on how to do that exact same thing without jQuery. Just because I'm a rebel.
var ageCheckbox = document.getElementById('isAgeSelected');
var ageInput = document.getElementById('txtAge');
// Just because of IE <333
ageCheckbox.onchange = function() {
// Check if the checkbox is checked, and show/hide the text field.
ageInput.hidden = this.checked ? false : true;
};
First you get both elements by their ID. Then you assign the checkboxe's onchange event a function that checks whether the checkbox got checked and sets the hidden property of the age text field appropriately. In that example using the ternary operator.
Here is a fiddle for you to test it.
Addendum
If cross-browser compatibility is an issue then I propose to set the CSS display property to none and inline.
elem.style.display = this.checked ? 'inline' : 'none';
Slower but cross-browser compatible.
This code will help you
$('#isAgeSelected').click(function(){
console.log(this.checked);
if(this.checked == true) {
$("#txtAge").show();
} else {
$("#txtAge").hide();
}
});
This works for me:
/* isAgeSelected being id for checkbox */
$("#isAgeSelected").click(function(){
$(this).is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();
});
There are many ways to check if a checkbox is checked or not:
Way to check using jQuery
if (elem.checked)
if ($(elem).prop("checked"))
if ($(elem).is(":checked"))
if ($(elem).attr('checked'))
Check example or also document:
http://api.jquery.com/attr/
http://api.jquery.com/prop/
This is some different method to do the same thing:
$(document).ready(function (){
$('#isAgeSelected').click(function() {
// $("#txtAge").toggle(this.checked);
// Using a pure CSS selector
if ($(this.checked)) {
alert('on check 1');
};
// Using jQuery's is() method
if ($(this).is(':checked')) {
alert('on checked 2');
};
// // Using jQuery's filter() method
if ($(this).filter(':checked')) {
alert('on checked 3');
};
});
});
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>
Use this:
if ($('input[name="salary_in.Basic"]:checked').length > 0)
The length is greater than zero if the checkbox is checked.
My way of doing this is:
if ( $("#checkbox:checked").length ) {
alert("checkbox is checked");
} else {
alert("checkbox is not checked");
}
$(selector).attr('checked') !== undefined
This returns true if the input is checked and false if it is not.
You can use:
if(document.getElementById('isAgeSelected').checked)
$("#txtAge").show();
else
$("#txtAge").hide();
if($("#isAgeSelected").is(':checked'))
$("#txtAge").show();
else
$("#txtAge").hide();
Both of them should work.
$(document).ready(function() {
$('#agecheckbox').click(function() {
if($(this).is(":checked"))
{
$('#agetextbox').show();
} else {
$('#agetextbox').hide();
}
});
});
1) If your HTML markup is:
<input type="checkbox" />
attr used:
$(element).attr("checked"); // Will give you undefined as initial value of checkbox is not set
If prop is used:
$(element).prop("checked"); // Will give you false whether or not initial value is set
2) If your HTML markup is:
<input type="checkbox" checked="checked" />// May be like this also checked="true"
attr used:
$(element).attr("checked") // Will return checked whether it is checked="true"
Prop used:
$(element).prop("checked") // Will return true whether checked="checked"
This example is for button.
Try the following:
<input type="button" class="check" id="checkall" value="Check All" /> <input type="button" id="remove" value="Delete" /> <br/>
<input type="checkbox" class="cb-element" value="1" /> Checkbox 1 <br/>
<input type="checkbox" class="cb-element" value="2" /> Checkbox 2 <br/>
<input type="checkbox" class="cb-element" value="3" /> Checkbox 3 <br/>
$('#remove').attr('disabled', 'disabled');
$(document).ready(function() {
$('.cb-element').click(function() {
if($(this).prop('checked'))
{
$('#remove').attr('disabled', false);
}
else
{
$('#remove').attr('disabled', true);
}
});
$('.check:button').click(function()
{
var checked = !$(this).data('checked');
$('input:checkbox').prop('checked', checked);
$(this).data('checked', checked);
if(checked == true)
{
$(this).val('Uncheck All');
$('#remove').attr('disabled', false);
}
else if(checked == false)
{
$(this).val('Check All');
$('#remove').attr('disabled', true);
}
});
});
The top answer didn't do it for me. This did though:
<script type="text/javascript">
$(document).ready(function(){
$("#li_13").click(function(){
if($("#agree").attr('checked')){
$("#saveForm").fadeIn();
}
else
{
$("#saveForm").fadeOut();
}
});
});
</script>
Basically when the element #li_13 is clicked, it checks if the element # agree (which is the checkbox) is checked by using the .attr('checked') function. If it is then fadeIn the #saveForm element, and if not fadeOut the saveForm element.
To act on a checkbox being checked or unchecked on click.
$('#customCheck1').click(function() {
if (this.checked) {
console.log('checked');
} else {
console.log('un-checked');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="customCheck1">
EDIT: Not a nice programming expression if (boolean == true) though .checked property might return other type variables as well..
It is better to use .prop("checked") instead. It returns true and false only.
I am using this:
<input type="checkbox" id="isAgeSelected" value="1" /> <br/>
<input type="textbox" id="txtAge" />
$("#isAgeSelected").is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();
Though you have proposed a JavaScript solution for your problem (displaying a textbox when a checkbox is checked), this problem could be solved just by css. With this approach, your form works for users who have disabled JavaScript.
Assuming that you have the following HTML:
<label for="show_textbox">Show Textbox</label>
<input id="show_textbox" type="checkbox" />
<input type="text" />
You can use the following CSS to achieve the desired functionality:
#show_textbox:not(:checked) + input[type=text] {display:none;}
For other scenarios, you may think of appropriate CSS selectors.
Here is a Fiddle to demonstrate this approach.

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:
Click submit if the checkbox is unchecked
Click apply if the checkbox is checked
Currently I have $(“#checkbox”).click(); if the user calls the API and I’m not sure how to implement this where $(“#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.
$(‘#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.
$('#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:
$(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 :
$(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>

Categories

Resources