Multiple conditions on single checkbox - javascript

I wanted to have a single checkbox in a form but i need to implement multiple scenarios but not sure if this is possible using a single checkbox or if i need radio buttons . Please advise
box shown and checked: Accepted / yes
(hidden)Box shown and not checked: Declined / no
Box not shown: Not Shown / blank

not sure if this is possible using a single checkbox
box shown and checked: Accepted / yes
(hidden)Box shown and not checked: Declined / no
Box not shown: Not Shown / blank
if the requirements 1/2/3 can be met using a single checkbox .The reason i ask is a single checkbox can hold only one value and if there is a way i can alter the value in Jquery dynamically still satisfying all the requirements.
Yes, it is possible. You can create an object having properties set to selectors :checked, :not(:checked, :hidden), :hidden; with corresponding values set to yes, no, blank. Set variable at change event handler using for..in loop, .is()
var obj = {
":checked": "yes",
":not(:checked, :hidden)": "no",
":hidden": "blank"
};
var curr;
$(":checkbox").change(function() {
for (var prop in obj) {
if ($(this).is(prop)) {
curr = obj[prop]; break;
}
}
// do stuff with `curr`
console.log(curr);
});
// check `:hidden`
$(":checkbox").prop("hidden", true)
.change() // `curr` should log `blank`
.prop("hidden", false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input type="checkbox" />

I have created one sample onchange function where you can handle mutiple events
codepen URL for reference:
http://codepen.io/nagasai/pen/xOGNYW
<input type="checkbox" id="checkTest" onchange="myFunction()">
<input type="text" id="myText" value="checked">
#myText
{
display:none;
}
function myFunction() {
if (document.getElementById("checkTest").checked) {
document.getElementById("myText").style.display = "block";
} else {
document.getElementById("myText").style.display = "none";
}
}

Related

JSON parse of string from cookie and ticking boxes doesn't tick boxes

I am writing a client side script to clean up the system that my college uses, and I am having an issue with a personal completion feature. What I have is an add-on that injects a <script> element into the DOM, and in this way I can modify the UI. However, I've run into an issue.
I have added some checkboxes to 'UnitBlocks' that allows me to check units that I have completed but the college hasn't uploaded yet. These trigger a JQuery event that allows me to tick the boxes and then change the color of the UnitBlock to yellow (see below for code):
var pc = false;
$(this).find('#personalCompletion').click(function(){ // personal completion is the checkboxId
if (pc === false)
{
$(this).closest('a').css('background-color', '#FFCC45 !important');
$(this).closest('a').children('p').text('Done');
pc = true;
}
else
{
$(this).closest('a').css('background-color', '');
$(this).closest('a').children('p').text('In Progress');
pc = false;
}
$(this).closest('p').append(' <input type="checkbox" id="personalCompletion"></input>'); //this re appends the checkbox
});
This works fine and it allows me to tick/untick the box. However, when I reload the page they dissapear, so I decided to store a cookie using JS with the tickbox values stored as "302": "yes", "304": "no", "313": "yes". The numbers are the unit numbers and the yes/no is if the boxes are ticked or not (this cookie is manual and for testing purposes). My code then goes onto pull the cookie for each UnitBlock, and dependant on the yes/no value of the cookie, it sets the tick box (please see below for my code)
var cookieValues = getCookie('completedUnits');
for (var i = 0; i <= cookieValues.length; i++)
{
if (cookieValues[i].includes($(this).attr('data-modcode'))) //data-modcode is a custom attribute with the unit number in (302 etc.)
{
if (cookieValues[i].text().indexOf('yes') >= 0) //if it includes the word 'yes'
{
$(this).find('#personalCompletion').attr('checked');
}
}
}
This doesn't throw an error or anything, it just doesn't tick any boxes...
You should use the .prop() method to change checked property (just like selected and disabled properties, too) representing and changing state of form elements.
There's big difference between checked property and checked attribute: the attribute represents defaultChecked property value, which is just initial state of the input, while the checked property changes state of the checkbox.
$(function() {
var $checkbox = $('#checkbox');
$('.debug').text($('.debug').text() + '\n' +
$checkbox.attr('checked') + '\n' +
$checkbox.prop('checked'));
$('#button').on('click', function() {
$checkbox.prop('checked', !$checkbox.prop('checked'));
$('.debug').text($('.debug').text() + '\n' +
$checkbox.prop('checked'));
});
});
.debug {
white-space: pre;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="checkbox" checked/>
<input type="button" id="button" value="click me!" />
<div class="debug"></div>

jQuery: focusout triggering before onclick for Ajax suggestion

I have a webpage I'm building where I need to be able to select 1-9 members via a dropdown, which then provides that many input fields to enter their name. Each name field has a "suggestion" div below it where an ajax-fed member list is populated. Each item in that list has an "onclick='setMember(a, b, c)'" field associated with it. Once the input field loses focus we then validate (using ajax) that the input username returns exactly 1 database entry and set the field to that entry's text and an associated hidden memberId field to that one entry's id.
The problem is: when I click on the member name in the suggestion box the lose focus triggers and it attempts to validate a name which has multiple matches, thereby clearing it out. I do want it to clear on invalid, but I don't want it to clear before the onclick of the suggestion box name.
Example:
In the example above Paul Smith would populate fine if there was only one name in the suggestion list when it lost focus, but if I tried clicking on Raphael's name in the suggestion area (that is: clicking the grey div) it would wipe out the input field first.
Here is the javascript, trimmed for brevity:
function memberList() {
var count = document.getElementById('numMembers').value;
var current = document.getElementById('listMembers').childNodes.length;
if(count >= current) {
for(var i=current; i<=count; i++) {
var memberForm = document.createElement('div');
memberForm.setAttribute('id', 'member'+i);
var memberInput = document.createElement('input');
memberInput.setAttribute('name', 'memberName'+i);
memberInput.setAttribute('id', 'memberName'+i);
memberInput.setAttribute('type', 'text');
memberInput.setAttribute('class', 'ajax-member-load');
memberInput.setAttribute('value', '');
memberForm.appendChild(memberInput);
// two other fields (the ones next to the member name) removed for brevity
document.getElementById('listMembers').appendChild(memberForm);
}
}
else if(count < current) {
for(var i=(current-1); i>count; i--) {
document.getElementById('listMembers').removeChild(document.getElementById('listMembers').lastChild);
}
}
jQuery('.ajax-member-load').each(function() {
var num = this.id.replace( /^\D+/g, '');
// Update suggestion list on key release
jQuery(this).keyup(function(event) {
update(num);
});
// Check for only one suggestion and either populate it or clear it
jQuery(this).focusout(function(event) {
var number = this.id.replace( /^\D+/g, '');
memberCheck(number);
jQuery('#member'+number+'suggestions').html("");
});
});
}
// Looks up suggestions according to the partially input member name
function update(memberNumber) {
// AJAX code here, removed for brevity
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
document.getElementById('member'+memberNumber+'suggestions').innerHTML = self.xmlHttpReq.responseText;
}
}
}
// Looks up the member by name, via ajax
// if exactly 1 match, it fills in the name and id
// otherwise the name comes back blank and the id is 0
function memberCheck(number) {
// AJAX code here, removed for brevity
if (self.xmlHttpReq.readyState == 4) {
var jsonResponse = JSON.parse(self.xmlHttpReq.responseText);
jQuery("#member"+number+"id").val(jsonResponse.id);
jQuery('#memberName'+number).val(jsonResponse.name);
}
}
}
function setMember(memberId, name, listNumber) {
jQuery("#memberName"+listNumber).val(name);
jQuery("#member"+listNumber+"id").val(memberId);
jQuery("#member"+listNumber+"suggestions").html("");
}
// Generate members form
memberList();
The suggestion divs (which are now being deleted before their onclicks and trigger) simply look like this:
<div onclick='setMember(123, "Raphael Jordan", 2)'>Raphael Jordan</div>
<div onclick='setMember(450, "Chris Raptson", 2)'>Chris Raptson</div>
Does anyone have any clue how I can solve this priority problem? I'm sure I can't be the first one with this issue, but I can't figure out what to search for to find similar questions.
Thank you!
If you use mousedown instead of click on the suggestions binding, it will occur before the blur of the input. JSFiddle.
<input type="text" />
Click
$('input').on('blur', function(e) {
console.log(e);
});
$('a').on('mousedown', function(e) {
console.log(e);
});
Or more specifically to your case:
<div onmousedown='setMember(123, "Raphael Jordan", 2)'>Raphael Jordan</div>
using onmousedown instead of onclick will call focusout event but in onmousedown event handler you can use event.preventDefault() to avoid loosing focus. This will be useful for password fields where you dont want to loose focus on input field on click of Eye icon to show/hide password

checkbox checked function for two set of checkboxes in a single page, cant calll functions individually

I have a two set of input checkbox in one page. and I have added a "checked" function to each set and each has different functionality.
I will set an example,
<div id="set1">
for(var i=0;i<n;i++)
<input type="checkbox" class=filter[i] onclick="clickCheck(filter[i])">array values
}
</div>
<div id="set2">
(for var j=0;j<n;j++)
<input type="checkbox" name="facets" value=array[j]>array values
}
</div>
Ive used jquery functions like
$("#set1 :checkbox").click(checkFacetSelectionCount);
checkFacetSelectionCount()
{
$('#set1 :input[type=checkbox]:checked').each(function() {
alert("Checked");
}
and
clickCheck(s)
{
if ($("#set2").is(':checked'))
{
alert(s);
}
else
{
alert("Nothing Checked");
}
, These two functions get activated on click on checkbox, so what happens is that whenever I click on any of the set, both set of functions will get activated. How can I prevent this? How can I differently call these two functions?
I think that
first one should
$('#set1 :input[type=checkbox]:checked')
{function body;}
and another should
$('#set2 :input[type=checkbox]:checked')
^ 2 instead of 1
{function body;}

Using custom jQuery radio buttons with CakePHP Form Helper

I'm using a custom jQuery plugin to convert radio buttons to actual images, and it works with basic checkboxes, but when using Cake's built-in input form helper, it acts more as a checkbox by not unchecking the already clicked options. Not only that, but it isn't populating $this->data (or sending anything when the form is submitted).
The js looks like this:
//##############################
// jQuery Custom Radio-buttons and Checkbox; basically it's styling/theming for Checkbox and Radiobutton elements in forms
// By Dharmavirsinh Jhala - dharmavir#gmail.com
// Date of Release: 13th March 10
// Version: 0.8
/*
USAGE:
$(document).ready(function(){
$(":radio").behaveLikeCheckbox();
}
*/
$(document).ready(function() {
$("#bananas").dgStyle();
var elmHeight = "15"; // should be specified based on image size
// Extend JQuery Functionality For Custom Radio Button Functionality
jQuery.fn.extend({
dgStyle: function()
{
// Initialize with initial load time control state
$.each($(this), function(){
var elm = $(this).children().get(0);
elmType = $(elm).attr("type");
$(this).data('type',elmType);
$(this).data('checked',$(elm).attr("checked"));
$(this).dgClear();
});
$(this).mouseup(function() {
$(this).dgHandle();
});
},
dgClear: function()
{
if($(this).data("checked") == true)
{
$(this).addClass("checked");
}
else
{
$(this).removeClass("checked");
}
},
dgHandle: function()
{
var elm = $(this).children().get(0);
if($(this).data("checked") == true)
$(elm).dgUncheck(this);
else
$(elm).dgCheck(this);
if($(this).data('type') == 'radio')
{
$.each($("input[name='"+$(elm).attr("name")+"']"),function()
{
if(elm!=this)
$(this).dgUncheck(-1);
});
}
},
dgCheck: function(div)
{
$(this).attr("checked",true);
$(div).data('checked',true).addClass('checked');
},
dgUncheck: function(div)
{
$(this).attr("checked",false);
if(div != -1)
$(div).data('checked',false).css({
backgroundPosition:"center 0"
});
else
$(this).parent().data("checked",false).removeClass("checked");
}
});
The PHP/Html looks like this:
<span id="bananas-cat" class="cat">
<?= $this->Form->radio('bananas',array(),array('legend' => false, 'id' => 'bananas', 'name' => 'category')); ?>
<label for="bananas">Bananas</label>
</span>
While it upon first inspection may look correct, when clicked, nothing gets passed within $this->data and it acts like a checkbox and doesn't unselect the value when I add an additional radio checkbox.
Although the radio functionality does work without CakePHP's html form helper like so:
<span id="animals-cat" class="cat">
<input type="radio" name="category" id="animals" />
<label for="animals">Animals</label>
</span>
If anyone can help me out here, I would be forever indebted. I've been trying to solve this for way too long now that I'm considering just scrapping the whole idea to begin with.
What I would suggest is see and compare the HTML output of example and one being generated by CakPHP, try to make it similar to example so that you can get your custom-radio-buttons working.
But if you can not do that I would highly recommend to override those helpers by some parameters so that you can get the exact HTML as an output and Javascript should work flawlessly.
Let me know if that does not work for you.

Check and un-check checkboxes using Javascript

Hey guys im trying to get a checkbox scenario worked out, I have 7 boxes and im trying to get a logic statement where it works things out. I have 7 checkboxes and the 7th box is all of the above, when all of the above is clicked it deselects all of the previous ones, when 1-6 is selected it deselects the all of the above box. What ends up happening in my current code it deselects all of the 1-6 boxes and then they are now unable to click. Unfortunately i'm kind of constrained to things. so i'll paste my code any help greatly appreciated.
This is a snippet of very horrible coding, i just through this together while i was trying multiple ways to get it to work.
if (document.forms[0].propDetails[6].checked==true) {
for (var x=0;x<6;x++) {
document.forms[0].propDetails[x].checked=false;
}
}
else {
document.forms[0].propDetails[6].checked=false;
}
} // end of function
I first suggest that you give a specific NAME attribute to the 1-6 checkboxes, and parsing them using getElementsByName like so :
<input type="checkbox" id="myChk1" name="myChk" />
...
<input type="checkbox" id="myChk6" name="myChk" />
<input type="checkbox" id="myChkAll" onchange="chkAll(this);" />
<script type="text/javascript">
function chkAll(obj) {
var isChecked = obj.checked;
var chk1to6 = document.getElementsByName('myChk');
for (var i = 0 ; i < chk1to6.length ; i++) {
chk1to6[i].checked = isChecked;
}
}
</script>
Give different unique Id to all the checkboxs...
like
chckbx1
chckbx2
chckbx3
.
.
chckbx7
the call a same function on click of any of the checkbox with the object of that checkbox
i.e. onclick=functionname(this);
In side the function check the id
functioname(str){
if(str.id=="chckbx7"){
//deselect all except chckbx7
}
else{
//deselect chckbx7
}
}

Categories

Resources