Foundation checkbox value error - javascript

I'm using the Foundation 4 framework and I added a custom form into my page.
HTML:
<label for="checkbox2">
<input type="checkbox" id="checkbox2" style="display: none;">
<span class="custom checkbox"></span> <p> CHECKBOX TEST</p>
</label>
JS:
if($('#checkbox2').is(":checked")){
isnewsletter = 1;
} else {
isnewsletter = 0;
}
and even this
newsletter = $('#checkbox2').val(),
isn't working.
How can I check, if my checkbox is checked?

$('#checkbox2').change(function(){
if($(this).is(":checked")){
console.log(1);
} else {
console.log(0);
}
});

First checking works fine. If you add checked="checked" to your checkbox isnewsletter will be 1.
P.S. You don't mention any other way how you tick checkbox in your program. Your checkbox is not displayed on the page, so you cannot tick it manually.

The question isn't quite clear whether OP wants to check if checkbox is :checked on change, at any random moment during interaction on a page, or on validation using the Foundation 4 Abide library. I've run into issues with the custom form and toggling hidden fields, as well as validating hidden fields, and the custom form doesn't help. However, I've worked around it, but those are different questions.
The "custom" form does by default hide the input and create a span after it that gets the class "checked", and the property on the hidden checkbox doesn't visually appear in Chrome's developer toolbar (I haven't checked FireBug to see if that property appears). However, if you write a code based check of the property of the checkbox, it will return 'true':
$("#checkbox2").change(function() {
console.log($(this).is(":checked"));
console.log($(this).prop('checked'));
// set up if using either method above, your choice.
if( $(this).prop('checked')) {
// do stuff
}
});
Or you can check the span.checkbox.custom directly after the input for the class "checked":
$("#checkbox2").change(function() {
console.log($(this).next().hasClass("checked"));
// set up if statement using that logic above:
if($(this).next().hasClass("checked") ) {
// do stuff
}
});
Use the same logic to check whether the checkbox is checked at any point, just don't bother with the .change() function. These will return true if the box is checked:
$("#checkbox2").next().hasClass("checked");
$("#checkbox2").is(":checked");
$("#checkbox2").prop("checked");
Foundation 4 didn't have validation built into Abide, you'd have to add it in.
This requires adjusting Abide.
I answered that question here.

Related

How would I pass a iCheck Checkbox value to Laravel?

I'm trying to implement a purchased theme, and it uses iCheck to theme it's checkbox's. It however does not change or add a value on/off or the checked option to the input, it only does it in the div that it wraps the input in. How would I go about getting the value to my backend Laravel Application? I currently have the following code.
<label><input type="checkbox" name="terms">
I agree with the Terms and Conditions</label>
And
$('input[type="checkbox"]').iCheck({
checkboxClass: 'icheckbox_minimal-grey',
increaseArea: '20%' // optional
});
Figured out a solution, up for other answers if someone else has something better.
I just created a hidden input and set the value to 0. Then did a bind to the ifClicked event and toggled the value in the hidden input.
$('#rememberme').on('ifClicked', function(event){
var value = $('#remembermehidden').val();
if(value == "0")
{
$('#remembermehidden').val('1');
} else {
$('#remembermehidden').val('0');
}
});

KnockoutJS + Advanced Checkbox Functionality

This checkbox is advanced in that not only is it set based on existing data, but the page must also respond in several ways to the user changing the checkbox by manually checking or unchecking it.
Imagine you have a murderCaseModel with list of various Witnesses to a crime.
Here is a Fiddle for you:
http://jsfiddle.net/maxgrr/j6fm7162/6/
The requirements are as follows:
Already Done
If previous witnesses exist from the loaded data, set the checked status of the box on page load
<input type='checkbox' data-bind='checked: numWitnesses() > 0'></input>
Delete Witness
Add Witness
TODO
Toggling the checkbox causes another area on the page to appear or disappear
If it is toggled by the user to 'No'(unchecked) we make the witness display area INVISIBLE (ideally, remove from DOM) and delete all of the Witness objects.
If it is toggled to 'Yes'(checked) we make the witness display area VISIBLE and make sure there is at least one Witness object ready to be filled out by the user.
This whole problem is very tricky to me and determining the auto value for the checkbox but also the user selected value for it it difficult to grasp. Any help is much appreciated. It's a cool functionality!
You can use a computed to make your wereThereAnyWitnesses field a little smarter:
self.wereThereAnyWitnesses = ko.computed({
read: function() {
return self.numWitnesses() > 0;
},
write: function(wereThereAnyWitnesses) {
if (!wereThereAnyWitnesses && self.numWitnesses() > 0) {
if (!confirm("Remove all current witnesses?"))
return self.wereThereAnyWitnesses.notifySubscribers();
else
self.witnesses.removeAll();
}
if (wereThereAnyWitnesses && self.numWitnesses() == 0)
self.addWitness();
}
}, this);
And in your HTML:
<input type='checkbox' data-bind='checked: wereThereAnyWitnesses' />
See Fiddle
You can use jQuery. First, make sure you have included jQuery libraries in you head tags. Just copy the following code in your head tags:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
Then, use the following code to see if the check box is checked:
<script type="text/javascript">
if ($('#the_checkbox').is(":checked"))
{
$('#the_textarea').hide();
}
</script>
And here is the input:
<input type="checkbox" id="the_checkbox" />

Hiding/showing fields conditionally w/ checkboxes

I'm using a conditional fields form from Bootstrap Validator and don't know enough Javascript to make one last thing work.
The form as it is now is live here
My problem is both "...a brochure to be sent to me" and "...to arrange a field demonstration" need to open the same address fields, however, if you check "...a brochure sent to me," then check "...to arrange a field demonstration" the fields open and then close again.
How do I create an if statement to verify if the field is already visible and leave it open if it IS, and open it is it's NOT?
It looks the bootstrapValidator.js file is addressing the checkboxes by class, both of your checkboxes have the name "topic[]" with the same value of "address". You could give each field its unique ID, add in javascript that tells the page to see if either of the checkboxes are checked, and then make the style display set to block.
Try
//HTML - Added ID's to each and the onclick='showblock()'
<input type='checkbox' value='address' name='topic[]' id='address1' onclick='showblock()'></input>
<input type='checkbox' value='address' name='topic[]' id='address2' onclick='showblock()'></input>
<div data-topic="address" style="display: block;" id="addressform">
//JS
function showblock() {
if (document.getElementById("address1").checked == true || document.getElementById("address2").checked == true) {
document.getElementById("addressform").style.display = "block";
} else {
document.getElementById("addressform").style.display = "none";
}
}
This should work, if it doesn't then the bootstrapValidator is probably overwriting it, you can just change the value of "address" to something other than address.

How to disable enable a checkbox based on another checkbox?

Following code is generated by a for loop.
<form action="saveresponse.php" method="POST" name="mainForm">
<input class="cbox_yes" type="checkbox" name="yes[]" value="01.jpg"
onclick="spenable()" /> OK
<input class="cbox_sp" type="checkbox" name="sp[]" value="01.jpg" disabled />Special<br />
<input class="cbox_yes" type="checkbox" name="yes[]" value="02.jpg"
onclick="spenable()" /> OK
<input class="cbox_sp" type="checkbox" name="sp[]" value="02.jpg" disabled />Special<br />
etc etc upto n times...
Now, what I want is that on page load, all the sp[] checkboxes should be disabled and enabled only if their corrosponding yes[] checkbox is checked by user.
Javascript code I am using: (Just to check if JS is capturing the states of yes[] checkbox?
function spenable(){
var yes = document.mainForm.yes[].value;
if (yes == true)
//alert("true");
document.mainForm.yes[].value = checked;
else
//alert("false");
document.mainForm.yes[].value = checked;
};
};
But I am not getting any alert (Neither Yes, Nor No).
So, is yes[] (Square brackets) in second line is incorrect? Or my if/else condition is wrong in JS?
P.S. All the questions here at SO or on Google deal with only one case/pair.
P.S. If required, I can change yes[] to yes1, yes2, yes3 etc and corresponding sp1, sp2, sp3 where 1,2,3 is $i of For loop, but then how will I capture/refer to it in JS?
_UPDATE:_
The flow/conditions are(Clarification):
Initially Special checkbox will be disabled and OK checkbox will be unchecked.
Then if user checks Ok, Special gets enabled.
If user want, he can tick Special.
If, later, user changes mind and untick the OK, Special should be unticked as well as disabled again.
I used jQuery here for the sake of simplicity.
$("input[name='yes[]']").change(function() { //When checkbox changes
var checked = $(this).attr("checked");
$(this).next().attr("disabled", !checked); //The next checkbox will enable
});​ // or disable based on the
// checkbox before it
Demo: http://jsfiddle.net/DerekL/Zdf9d/
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/1/
Update
It will uncheck the first checkboxes when the Special checkbox is checked.
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/2/
More Updates
Here's the demo:
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/3/
jQuery: http://jsfiddle.net/DerekL/Zdf9d/4/
Little note: document.querySelectorAll works on all modern browsers and IE8+ including IE8. It is always better to use jQuery if you want to support IE6.
You can't use yes[] as an identifier in the Javascript, so you have to access the field using the name as a string:
document.mainForm["yes[]"]
This will not return a single element, it will return an array of elements. Use an index to access a specific element:
document.mainForm["yes[]"][0]
The value of the checkbox will always be the value property, regardless of whether the checkbox is selected or not. Use the checked property to find out if it's selected:
function spenable() {
var yes = document.mainForm["yes[]"][0].checked;
if (yes) {
alert("true");
} else {
alert("false");
};
}
To access the specific checkbox that was clicked, send the index of the checkbox in the event call:
<input class="cbox_yes" type="checkbox" name="yes[]" value="01.jpg" onclick="spenable(0);" /> OK
Use the index in the function:
function spenable(idx) {
var yes = document.mainForm["yes[]"][idx].checked;
var sp = document.mainForm["sp[]"][idx];
sp.disabled = !yes;
}
If you are open to using jQuery:
$('input[type="checkbox"]').click(function(){
var obj = $(this);
obj.next('.cbox_sp').attr({'disabled':(obj.is(':checked') ? false : 'disabled')});
});
This solution will assign an onclick event handler to all checkboxes and then check to see if the corresponding "special" checkbox should be disabled or not. It also sets the default checked state to true.
Working Example: http://jsfiddle.net/6YTqC/

Using depends with the jQuery Validation plugin

I've got a form with a bunch of textboxes that are disabled by default, then enabled by use of a checkbox next to each one.
When enabled, the values in these textboxes are required to be a valid number, but when disabled they don't need a value (obviously). I'm using the jQuery Validation plugin to do this validation, but it doesn't seem to be doing what I expect.
When I click the checkbox and disable the textbox, I still get the invalid field error despite the depends clause I've added to the rules (see code below). Oddly, what actually happens is that the error message shows for a split second then goes away.
Here is a sample of the list of checkboxes & textboxes:
<ul id="ItemList">
<li>
<label for="OneSelected">One</label><input id="OneSelected" name="OneSelected" type="checkbox" value="true" />
<input name="OneSelected" type="hidden" value="false" />
<input disabled="disabled" id="OneValue" name="OneValue" type="text" />
</li>
<li>
<label for="TwoSelected">Two</label><input id="TwoSelected" name="TwoSelected" type="checkbox" value="true" />
<input name="TwoSelected" type="hidden" value="false" />
<input disabled="disabled" id="TwoValue" name="TwoValue" type="text" />
</li>
</ul>
And here is the jQuery code I'm using
//Wire up the click event on the checkbox
jQuery('#ItemList :checkbox').click(function(event) {
var textBox = jQuery(this).siblings(':text');
textBox.valid();
if (!jQuery(this).attr("checked")) {
textBox.attr('disabled', 'disabled');
textBox.val('');
} else {
textBox.removeAttr('disabled');
textBox[0].focus();
}
});
//Add the rules to each textbox
jQuery('#ItemList :text').each(function(e) {
jQuery(this).rules('add', {
required: {
depends: function(element) {
return jQuery(element).siblings(':checkbox').attr('checked');
}
},
number: {
depends: function(element) {
return jQuery(element).siblings(':checkbox').attr('checked');
}
}
});
});
Ignore the hidden field in each li it's there because I'm using asp.net MVC's Html.Checkbox method.
Using the "ignore" option (http://docs.jquery.com/Plugins/Validation/validate#toptions) might be the easiest way for you to deal with this. Depends on what else you have on the form. For i.e. you wouldn't filter on disabled items if you had other controls that were disabled but you still needed to validate for some reason. However, if that route doesn't work, using an additional class to filter on (adding and removing with your checkboxes) should get you to where you want to go, but easier.
I.e.
$('form').validate({
ignore: ":disabled",
...
});
Usually when doing this, I skip 'depends' and just use the required jQuery Validate rule and let it handle the checking based on the given selector, as opposed to splitting the logic between the validate rules and the checkbox click handler. I put together a quick demo of how I accomplish this, using your markup.
Really, it boils down to required:'#OneSelected:checked'. This makes the field in question required only if the expression is true. In the demo, if you submit the page right away, it works, but as you check boxes, the form is unable to submit until the checked fields are filled with some input. You could still put a .valid() call in the checkbox click handler if you want the entire form to validate upon click.
(Also, I shortened up your checkbox toggling a bit, making use of jQuery's wonderful chaining feature, though your "caching" to textBox is just as effective.)
Depends parameter is not working correctly, I suppose documentation is out of date.
I managed to get this working like this:
required : function(){ return $("#register").hasClass("open")}
Following #Collin Allen answer:
The problem is that if you uncheck a checkbox when it's error message is visible, the error message doesn't go away.
I have solved it by removing the error message when disabling the field.
Take Collin's demo and make the following changes to the enable/disable process:
jQuery('#ItemList :checkbox').click(function()
{
var jqTxb = $(this).siblings(':text')
if ($(this).attr('checked'))
{
jqTxb.removeAttr('disabled').focus();
}
else
{
jqTxb.attr('disabled', 'disabled').val('');
var obj = getErrorMsgObj(jqTxb, "");
jqTxb.closest("form").validate().showErrors(obj);
}
});
function getErrorMsgObj(jqField, msg)
{
var obj = {};
var nameOfField = jqField.attr("name");
obj[nameOfField] = msg;
return obj;
}
You can see I guts remove the error message from the field when disabling it
And if you are worrying about $("form").validate(), Don't!
It doesn't revalidate the form it just returns the API object of the jQuery validation.
I don't know if this is what you were going for... but wouldn't changing .required to .wasReq (as a placeholder to differentiate this from one which maybe wouldn't be required) on checking the box do the same thing? If it's not checked, the field isn't required--you could also removeClass(number) to eliminate the error there.
To the best of my knowledge, even if a field is disabled, rules applied to it are still, well, applied. Alternatively, you could always try this...
// Removes all values from disabled fields upon submit
$(form).submit(function() {
$(input[type=text][disabled=disabled]).val();
});
I havent tried the validator plugin, but the fact that the message shows for a splitsecond sounds to me like a double bind, how do you call your binders? If you bind in a function try unbinding just before you start, like so:
$('#ItemList :checkbox').unbind("click");
...Rest of code here...
Shouldn't validate the field after disabling/enabling?
jQuery('#ItemList :checkbox').click(function(event) {
var textBox = jQuery(this).siblings(':text');
if (!jQuery(this).attr("checked")) {
textBox.attr('disabled', 'disabled');
textBox.val('');
} else {
textBox.removeAttr('disabled');
textBox[0].focus();
}
textBox.valid();
});
I had the exact same problem.
I solved this by having the radio-button change event handler call valid() on the entire form.
Worked perfect. The other solutions above didn't work for me.

Categories

Resources