KnockoutJS + Advanced Checkbox Functionality - javascript

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" />

Related

How to grab ID of element which ID has been dynamically given?

I’m trying to make a simple show when checkbox is checked kind of section but am unable to get a hold of the element because the IDs of the element are assigned dynamically by PHP.
The element will be inside a foreach loop so there will be multiple instances of it with dynamically given IDs.
example:
//Laravel blade template
<element id="attrb{{ $elem->id }}> "></element>
//Javascript
if ($("#attrb*ID").is(":checked")) {
$("#attrbs-container").show();
} else {
$("#attrbs-container").hide();
}
With Jquery
$('input[id^="attrb"]').change(function(e){
if($(this).is(':checked')) console.log($(this).prop('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="attrb1" value="1" />
Run, and check the box. You can replace console.log with your .show or whatever.
The selector input[id^="attrb"] means an input with an id that ^= starts with attrb. You could also use input[type="checkbox"] if these are the only checkboxes you have, but it's less specific.
Change vs Click
change fires when the data (state) of the element changes. click will trigger anytime you click. In this case it probably doesn't matter too much which you use. A better example of change vs click is using radio buttons, and clicking an already checked radio. Checkboxes un-click when checked, radio buttons not so much. I'm just in a habit of using change over click for state changes.
$('input[id^="attrb"]').click(function(e){
if($(this).is(':checked')) console.log($(this).prop('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="attrb1" value="1" />
Run and click the radio 2x. It fires 2 times.
$('input[id^="attrb"]').change(function(e){
if($(this).is(':checked')) console.log($(this).prop('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="attrb1" value="1" />
Do the same thing here, but with change. That's the difference.
DYNAMIC vs Dynamic
What I mean here is DYNAMIC is something that changes at run time on the client, Dynamic is static HTML where the ID changes on the server side only. For DYNAMIC you want to use on like this
$(someparent).on('change', 'input[id^="attrb"]', function(e){ ... });
Where someparent is a static element that doesn't change at runtime. This will use event delegation and "bubbling" to find the content that was changed on the client side.
I don't think you meant DYNAMIC but I included it just in case.
Cheers!
you could create a function with a callback if you're assigning the id with javascript (after an ajax request)
function addID(add, callback)
Then use the funciton:
addId(function(){
//dynamically add ID
}, function(){
// callback function
if ($(“#attrb*ID”).is(":checked")) {
$(“#attrbs-container").show();
} else {
$(“#attrbs-container").hide();
}
})

Foundation checkbox value error

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.

How to use jquery to validate whether at least one tick box from #age-groups, #subjects and #topics have been selected

In my upload form I have a few select boxes. These are arranged in divs called #age-groups, #subjects and #topics.
I want to be able to use jquery to make sure the user clicks at least one checkbox from each of the 3 individual divs.
Please could someone help me figure out how to do this.
For when at least one checkbox in each div is clicked I want the function to output:
if (at least 1 checkbox is ticked in each of the 3 divs)
{
$('#two')
.append('<div class="done rotatetwo wiggler"></div>')
.addClass('grey')
}
If possible can this function output the above code as soon as the final required select box is selected.
$(":checkbox").click(function(){
if (($("#age-groups input:checked").length>0) && ($("#subjects input:checked").length>0) && ($("#topics input:checked").length>0){
$('#two').append('<div class="done rotatetwo wiggler"></div>').addClass('grey');
}
});
You need to check the parents of check box/select box for determination.
Have a look at this
basically,
HTML
<fieldset id="age-groups">
<input type="checkbox" name="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" value="Bananas" />
</fieldset>
JavaScript/Jquery
var atLeastOneIsChecked_ageGroups = $('#age-groups :checkbox:checked').length > 0;
will work for you
You'll need to use three selectors to identify any checked checkboxes inside of your three DIVs, then examine the length property of the resulting jQuery objects to make sure that they're greater than zero.
if($('#age-groups input:checkbox:checked').length && ... ) {
// do your stuff here
}
I've only included the selector for the #age-groups div, but you should be able to modify that to select for the other two.
-- misread the question. This would help you if you wanted to check if at least one box is selected across all relevant divs.
try something like this:
if($("#age-groups input[name^='foo']:checked:enabled, #subjects input[name^='foo']:checked:enabled, #topics input[name^='foo']:checked:enabled").length > 0)
// at least one selected
else
// none selected
Of course, this can be simplified if you add a class to all check boxes instead of using the parent div to group them.
if( $("input[name^='foo'].test:checked:enabled").length > 0)
// something selected
Hope this helps!

How do I make a checkbox unclickable *without* it being greyed out in the browser?

How do you create an HTML checkbox that is unclickable, but not greyed out? I used the disabled=disabled tag, but that makes it greyed out (in Chrome). Otherwise it works well. Working in jQuery and Rails...
Thanks.
Usability concerns aside:
$("input:checkbox").click(function() { return false; });
For example: http://jsfiddle.net/nKwRj/
Use jQuery.on with false as the callback:
$(":checkbox").on("click", false);
Fiddle
I had the same issue where i wanted the user to check the box but not the client the client was supposed to see the checked box only and not to make changes so
in html just add a css pointer event style
<input name='test' type='checkbox' style="pointer-events: none;"/>
Prevent checkboxes from being changed by ID or by Class.
/* by class */
$(".nochange").click(function () {
return false;
});
/* by ID */
$("#nochange").click(function () {
return false;
});
<input name='test' type='checkbox' class='nochange' checked='checked' />
<br />
<input name='test' type='checkbox' id='nochange' checked='checked' />
http://jsfiddle.net/mjames757/nX64E/1/
Why do you want to make a unclickable checkbox appear to be clickable? To fool the users?
If you really want to fool the users, you could place a div with 0.01 opacity above it using absolute positioning (no script required). But I still wonder why you feel the need to do this prank on your users... ;)
EDIT: If what you really need is to include a value the user should not change but you don't want what you probably are considering "an ugly disabled checkbox", you should use input type hidden, which is completely invisible.
If you want to indicate that something is preselected but not changeable or something like that, use a disabled checkbox to indicate this (or an image of a pretty checkbox if you like), but beware that the value of a disabled checkbox is not submitted. Use a hidden field to include the the data needed.
Just add onclick="return false" in your HTML code.
Example:
<input type="checkbox" onclick="return false" class="checkbox" checked >
I ran into this post in search of an answer to the initial question - and found the opposals to non-grayed disabled checkboxes convincing, so instead i made a td-tag containing this: <%if rs("yes/no value") = -1 then response.write("√")%> (wing is a &radic). Then i get a clean info wing not inviting to click.

jQuery checkbox script as facebook invite friends window

I'm looking for a jQuery script or idea on how to create a similar window to the one facebook uses when you invite friends to an event.
So basically a dialog window that has a list of people inside and when you select your friends it changes the background color and checks the checkbox of that friend so when they submit the form I can collect the data.
Thanks,
How about something like this? Oversimplified, but this should get the point across...
Markup:
<div class="member">
<span class="member_name">Mike</span>
<input type="checkbox" class="member_checkbox" />
<input type="hidden" value="002" class="member_id" />
</div>
Member Select javascript:
// .member-selected would set a new background color
$(".member").click(function() {
$(this).addClass("member-selected");
// Find the checkbox
var checkbox = $(this).find('.member_checkbox');
// If the checkbox is checked, uncheck it, and
// if it's not, then check it
if( $(checkbox).attr("checked") != true) {
$(checkbox).attr("checked", true);
} else {
$(checkbox).attr("checked" false);
}
});
Form submission javascript:
// Create an array to hold ID numbers to submit
var add_members = [];
$(".member").each(function() {
if( $(this).find('.member_checkbox').is(":checked") ) {
add_members.push( $(this).find('.member_id').val() );
}
});
You would end up with an array of member IDs that you could then post using AJAX.
** EDIT **
In the click function (see above) there should be additional lines that check or uncheck the checkbox based on its current state.
EDIT: I made a JSBIN out of Mike's suggestion. May help you solve your problem. When a checkbox is clicked its class is alerted then changed (member-selected is added or removed, I'm using toggleClass()) and then its class is alerted again. Check it out: jsbin.com/uxuxu3/4/edit
I don't know how facebook's 'invite friends to an event' window looks these days, but I believe you will find Facebox a similar modal. Check Facebox and other, perhaps even better options, at 19 jQuery Modal Boxes to improve your UI.

Categories

Resources