Change Toggle Switch status dynamically - javascript

I am trying to figure out how to set toggle switch button base on a value. I am using bootstrap for the button. Anyone please tell me what is wrong?
*user.isActive only have two value either true or false.
<td><input id="activeSwitch" data-toggle="toggle" data-on="Active" data-off="InActive" data-onstyle="danger" data-width="90" data-height="30" style="font-size:38px" type="checkbox">
<input type="hidden" id="activeStatus" value='${user.isActive}'/></td>
<script>
$(document).ready(function() {
if($('#activeStatus').val() == 'true'){
$("#activeSwitch").attr("checked", "checked");
}
else if($('#activeStatus').val() == 'false'){
...
}
});
</script>

I found the answer so wanted to share with people who need help too. For people using bootstrap use:
$(document).ready(function() {
if ($('#activeStatus').val().trim() == 'true') {
$("#activeSwitch").bootstrapToggle('on');
} else if ($('#activeStatus').val().trim() == 'false') {
$("#activeSwitch").bootstrapToggle('off');
}
});
Use .bootstrap('on') instead of prop or attr if they are not working.

Try like this prop() instead of attr => prop('checked',true). use Boolean value instead of string
updated
Do with trim() its remove the unwanted space
$(document).ready(function() {
if ($('#activeStatus').val().trim() == 'true') {
$("#activeSwitch").prop("checked", true);
} else if ($('#activeStatus').val().trim() == 'false') {
$("#activeSwitch").prop("checked", false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td><input id="activeSwitch" data-toggle="toggle" data-on="Active" data-off="InActive" data-onstyle="danger" data-width="90" data-height="30" style="font-size:38px" type="checkbox">
<input type="hidden" id="activeStatus" value='true' /></td>
or single line code
$(document).ready(function() {
$("#activeSwitch").prop("checked" , $('#activeStatus').val().trim() == 'true')
})

Related

Check checkbox based on variable value

I'm struggling with a checkbox. I want the checkbox to be checked depending on a variable coming from the database. I can see the value in my console, so it's dynamically filled, but I can't have the checkbox checked.
I tried 2 things:
$(document).ready(function() {
$('input[name="OPTIN_NEWSLETTER_STARTER_INDEPENDANT"]').each(function(index) {
if ($(this).val() ==
"%%OPTIN_NEWSLETTER_STARTER_INDEPENDANT%%")
($(this).prop('checked', true));
});
And
$(document).ready(function() {
var checkBox =
[
["OPTIN_NEWSLETTER_STARTER_INDEPENDANT",
"%%OPTIN_NEWSLETTER_STARTER_INDEPENDANT%%"],
];
for (var i = 0; i < checkBox.length; i++) {
if (checkBox[i][1] == "Yes") {
if ($('input[name="' + checkBox[i][0] + '"]'))
{
$('input[name="' + checkBox[i][0] +
'"]').prop("checked", true).change();
}
}
};
This is my html checkbox:
<label class="yesNoCheckboxLabel">
<input type="checkbox"
name="OPTIN_NEWSLETTER_STARTER_INDEPENDANT" id="control_COLUMN136"
label="OPTIN_NEWSLETTER_STARTER_INDEPENDANT"
value="%%OPTIN_NEWSLETTER_STARTER_INDEPENDANT%%"
checked="">OPTIN_NEWSLETTER_STARTER_INDEPENDANT</label>
It would be great to have someone's insights, thanks!
Kind regards,
Loren
I tested your case locally and It's working fine may be you are lacking some where else and make sure use attr in order to set value for jquery 1.5 or below
For jquery 1.5 or below
($(this).prop('checked', true));
$(document).ready(function() {
$('input[name="vehicle1"]').each(function(index) {
if ($(this).val() ==
"vehicle1")
($(this).prop('checked', true));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="checkbox" name="vehicle1" value="vehicle1"> I have a bike<br>
<input type="checkbox" name="vehicle1" value="vehicle1"> I have a car
</form>
and last thing make sure that value must be same for this condition
$(this).val() == "vehicle1"

Problems with jQuery and testing checkbox

I have some little problems about testing if a checkbox is checked with jQuery. I've a table and in every row a checkbox with the same ID.
<td><input id="hp" type="checkbox" aria-label="..." checked></td>
This is the jQuery function:
$('#hp').bind("click", function() {
if($(this).prop('checked')) {
alert("check");
} else {
alert ("unchecked!");
}
});
But it only works with the first row of table. Any suggestions?
try like
<td><input id="hp" type="checkbox" class='checkBoxClass'></td>
and
$('.checkBoxClass').bind("click", function() {
if($(this).prop('checked')) {
alert("check");
} else {
alert ("unchecked!");
}
});
Change your code as below :
HTML Code
<td><input id="hp" class="hp" name="hp[]" type="checkbox" aria-label="..." checked></td>
Javascript
$('.hp').bind("click", function() {
if($(this).prop('checked')) {
alert("check");
} else {
alert ("unchecked!");
}
});
I hope it work for you.
how about?
$('input[type="checkbox"]').bind("click", function() {
if(this.checked) {
alert("check");
} else {
alert ("unchecked!");
}
});
DEMO
http://jsfiddle.net/n2cgnodp/
So, ID must be unique, if you use #hp on multiple elements, jQuery / JS will return only the first one!
Use .class instead:
jsBin demo
<input class="hp" type="checkbox" aria-label="..." checked>
$(".hp").on("change", function(){
alert(this.checked? "YEY!" : "Not checked :( ");
});
If there is no way other than giving same id to each checkbox then go for following code:
$('body #hp').bind("click", function() {
if($(this).prop('checked')) {
alert("check");
} else {
alert ("unchecked!");
}
});
Here $('body #hp') will give you all the elements with same id as hp

Enable/disable button based on accepting the 2 checkbox conditions

I have gone through the stackoverflow regarding enable/disable button conditionally and was able to find some help but NOT EXACT what I was looking for.
Instead of 1 checkbox condition, I have 2 checkbox conditions. So unless if the two checkboxes have been accepted, the button should not be enabled.
Following is my html:
<input type="checkbox" id="f_agree" value="1" onchange="checked(this, 'f_agree2')"/>
<input type="checkbox" id="f_agree2" value="1" onchange="checked('f_agree', this)"/>
<button type="submit" disabled="disabled" id="acceptbtn">Continue</button>
Following is javascript:
function checked(element1, element2) {
var myLayer = document.getElementById('acceptbtn');
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.disabled = "";
} else {
myLayer.class = "button:disabled";
myLayer.disabled = "disabled";
};
}
I have tried like above, but it is not working. I don't know where I am going wrong.
it won't work because you are not removing that attribute disabled.
function checked(element1, element2) {
var myLayer = document.getElementById('acceptbtn');
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.removeAttribute("disabled");
} else {
myLayer.class = "button:disabled";
myLayer.setAttribute("disabled","disabled");
};
}
Update
use any other name then checked as it seems to be reserved and not working.
you also need to do getElementById for element1 and element2.
function checkedFunc(element1Id, element2Id) {
var myLayer = document.getElementById('acceptbtn');
var element1 = document.getElementById(element1Id);
var element2 = document.getElementById(element2Id);
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.removeAttribute("disabled");
} else {
myLayer.class = "button:disabled";
myLayer.setAttribute("disabled","disabled");
};
}
<input type="checkbox" id="f_agree" value="1" onchange="checkedFunc('f_agree', 'f_agree2')"/>
<input type="checkbox" id="f_agree2" value="1" onchange="checkedFunc('f_agree','f_agree2')"/>
<input type="button" value="check" id="acceptbtn" />
You can try the following code
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.removeAttribute("disabled");
} else {
myLayer.class = "button:disabled";
myLayer.setAttribute("disabled", "disabled");
};
With jQuery:
var btn;
var changed = function() {
//get the length of non checked boxes
var disbl = $('input[id^=f_agree]:not(:checked)').length;
btn.prop('disabled', disbl);//disable if true, else enable
};
$(function() {
btn = $('#acceptbtn');
$('input[id^=f_agree]').on('change', changed).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" id="f_agree" value="1" />1
<input type="checkbox" id="f_agree2" value="1" />2
<input type="button" id="acceptbtn" value="Submit" />
The problem is that there is a difference between the string "f_agree" and the node with id="f_agree".
Your code should work as expected with
checked(this, document.getObjectById('f_agree2'))
Much better would be however to avoid having a widget knowing about the other... I'd implement instead by adding a list of external rules that check all widgets:
function okSubmit() {
return (document.getElementById("f_agree").checked &&
document.getElementById("f_agree2").checked);
}
This is much easier to read/maintain and also scales better in case you need to add more conditions later. In the onchange of all the widgets just call a function that will enable/disable the submit button depending on the conditions.
Try this
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.removeAttribute("disabled");
} else {
myLayer.class = "button:disabled";
myLayer.setAttribute("disabled", "disabled");
};
Try the below code -
var chk1 = document.getElementById('chk1');
chk1.addEventListener('click', checked, false);
var chk2 = document.getElementById('chk2');
chk2.addEventListener('click', checked, false);
function checked(){
if(chk1.checked && chk2.checked) {
document.getElementById('btn').removeAttribute('disabled');
} else {
document.getElementById('btn').setAttribute('disabled','disabled');
}
}
<input type="checkbox" id="chk1" />
<input type="checkbox" id="chk2" />
<button id="btn" disabled >Button<button>
I tested it and it's working! Hope it helps u...

auto-submit form only if specific number of checkboxes had been checked

I am new to jQuery. I am wondering if there is a way to count the number of checkboxes that have been checked and then auto-submit the form once a specific number of checkboxes had been checked. Let's say the user checks 2 checkboxes, nothing happens. The user checks the 3rd checkbox and the form submits.
<input type="checkbox" onclick="this.form.submit();">
You could try this, using no inline javascript...
HTML
<form>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</form>
jQuery
$('input[type="checkbox"]').on('click', function (event) {
var flag = $('input:checked').length > 2 ? true : false;
if (flag) $('form').submit();
});
Fiddle
$('input[type="checkbox"]').on('change', function() {
if( $("input[type="checkbox"]:checked").length >=3) {
$('form').submit();
}
});
JQuery function:
function SubmitIfReady() {
if ($('.checkbox-class:checked').length == 5) { // specify the number you want
$('#YourForm').submit();
}
}
HTML (form not shown):
<input type="checkbox" class="checkbox-class" onclick="SubmitIfReady();">
Or without the onclick:
JQuery function:
$(document).ready(function () {
$('.checkbox-class:checked').on('change', function() {
if ($('.checkbox-class:checked').length == 5) { // specify the number you want
$('#YourForm').submit();
}
});
});
HTML (form not shown):
<input type="checkbox" class="checkbox-class">
Like this...
$(".counted-check").click(function(e){
var myForm = $(this).closest('form');
if(myForm.find(".counted-check").filter(":checked").length > 3){
myForm.submit();
}
});
http://jsfiddle.net/HQ5N9/

Enable/Disable a button on select of radio button in jquery

I have a page in which there are 2 radio buttons and a next button. I have made next button disabled and it is enabled only when I select any radio button. But now when I go to another page and come back to this page the next button comes as disabled although the radio button is already selected. PFB the code
$(document).ready(function () {
$('#commandButton_1_0').attr('disabled', 'true');
$('input:radio[name=a_SignatureOption]').click(function () {
var checkval = $('input:radio[name=a_SignatureOption]:checked').val();
if (checkval == '1' || checkval == '2') {
$('#commandButton_1_0').removeAttr('disabled');
}
});
});
Try
$(document).ready(function() {
$('input:radio[name=a_SignatureOption]').click(function() {
var checkval = $('input:radio[name=a_SignatureOption]:checked').val();
$('#commandButton_1_0').prop('disabled', !(checkval == '1' || checkval == '2'));
});
});
Demo: Fiddle
I took time to understand your problem,
This can be solved by unchecking the radio while loading the page.
$(document).ready(function () {
$('input:radio[name=a_SignatureOption]').prop('checked', false);
$('#commandButton_1_0').attr('disabled', 'true');
$('input:radio[name=a_SignatureOption]').click(function () {
var checkval = $('input:radio[name=a_SignatureOption]:checked').val();
if (checkval == '1' || checkval == '2') {
$('#commandButton_1_0').removeAttr('disabled');
}
});
});
check out JSFiddle, btw redirect to other site and press back button to find the difference.
Hope you understand.
// Try this.............
$(document).ready(function () {
$("input:radio[name=a_SignatureOption]").removeAttr('checked');
$('#commandButton_1_0').attr("disabled","disabled");
$('input:radio[name=a_SignatureOption]').click(function () {
var checkval = $('input:radio[name=a_SignatureOption]:checked').val();
if (checkval == '1' || checkval == '2') {
$('#commandButton_1_0').removeAttr("disabled","disabled");
}
});
});
It is simple as your question is
<form name="urfrm">
<input type="radio" value="1" name="a_SignatureOption"> Yes<br>
<input type="radio" value="2" name="a_SignatureOption"> No<br>
<input type="submit" id="butn" name="butn" value="next" disabled><br>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
//This will check the status of radio button onload
$('input[name=a_SignatureOption]:checked').each(function() {
$("#butn").attr('disabled',false);
});
//This will check the status of radio button onclick
$('input[name=a_SignatureOption]').click(function() {
$("#butn").attr('disabled',false);
});
});
</script>
The easiest solution I can think of - albeit somewhat belatedly, is:
// selects all input elements, whose name is 'a_SignatureOption' and whose
// type is 'radio'
// binds a change event-handler, using 'on()':
$('input[name=a_SignatureOption][type="radio"]').on('change', function(){
// sets the 'disabled' property of the button to 'true' if zero radio inputs
// are checked, or to false if one is checked:
$('#commandButton_1_0').prop('disabled', $('input[name=a_SignatureOption][type="radio"]:checked').length === 0);
// triggers the change event-handler on page load:
}).change();
References:
Attribute-equals ([attribute="value"]) selector.
change().
on().
prop().
On load of document you need to check whether radio button is clicked or not
$(document).ready(function() {
$('input:radio[name=a_SignatureOption]').each(function() {
checked(this);
});
$('input:radio[name=a_SignatureOption]').click(function() {
checked(this);
});
function checked(obj){
if($(obj).is(':checked')) {
$('#commandButton_1_0').removeAttr('disabled');
}else{
$('#commandButton_1_0').attr('disabled', 'true');
}
}
});
You forgot to check the buttons at the beginning.
$(document).ready(function () {
$('#commandButton_1_0').attr('disabled', 'true');
if( $('input[name=a_SignatureOption]:checked' ).size() > 0 ) {
$('#commandButton_1_0').removeAttr('disabled');
}
$('input[name=a_SignatureOption]').click(function () {
if( $('input:radio[name=a_SignatureOption]:checked' ).size() > 0 ) {
$('#commandButton_1_0').removeAttr('disabled');
}
});
});
By the way, I always suggest to add classes to form elements and work with those, instead of using [name="..."]. It's quicker and simplier and you can change input names (if necessary) without touching js
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function () {
$('#commandButton_1_0').attr('disabled', 'true');
$('input:radio[name=a_SignatureOption]').click(function () {
var checkval = $('input:radio[name=a_SignatureOption]:checked').val();
alert(checkval)
if (checkval == '1' || checkval == '2') {
$('#commandButton_1_0').removeAttr('disabled');
}
else {
$('#commandButton_1_0').attr('disabled', 'disabled');
}
});
});
</script>
</head>
<body>
<input type="radio" name="a_SignatureOption" value="1" /> value1
<br />
<input type="radio" name="a_SignatureOption" value="2"/> value2
<br />
<input type="radio" name="a_SignatureOption" value="3" checked="checked"/> value3
<br />
<input type="button" id="commandButton_1_0" value="Next"/>
</body>
</html>

Categories

Resources