Changing aria-label based on the binding of css style - javascript

I have a checkbox that i have an aria-label for but i am not sure of how to change this aria-label text to reflect whether the checkbox is checked or not for the user. Is it possible to control the aria-label text in the same function for rendering the css?
Function for checking and unchecking box:
checkbox = ko.pureComputed(function () {
var checked = checked(),
uncheck = uncheck(),
checkedIcon = 'icon_check',
uncheckedIcon = 'no_check',
if (checked) {
//Can i add in here what the aria-label text should be?
return checkedIcon;
}
if (uncheck) {
return uncheckedIcon;
}
});

You could do something like this if you would like to change the attribute based on check-box value.
HTML:
<input type="checkbox" data-bind="checked:Mycheckbox,attr:{'aria-label':MyAriaLabel}" >
VM:
$(function () {
var MainViewModel = function () {
var self = this;
self.MyAriaLabel = ko.observable('aria-lebel');
self.Mycheckbox = ko.observable();
self.Mycheckbox.subscribe(function(newVal){
self.MyAriaLabel(newVal?'Something' : 'Something else');
})
}
ko.applyBindings(new MainViewModel());
})
Example : http://jsfiddle.net/GSvnh/5129/

You could, but it sounds like you're making this more complex than it has to be. Rather than manually setting an aria-label, you can use the native API of the checkbox input type. If your html is an actual checkbox input, like:
<input id="check1" name="field-name" type="checkbox">
then when it's checked off, it should automatically get the "checked" attribute, which screenreaders should be able to pick up on. If that fails, you can use aria-checked to supplement it.
var isChecked = element.getAttribute('checked')
element.setAttribute('aria-checked', isChecked)
If you're not using normal input type="checkbox" markup for whatever reason, you can add role="checkbox" to your markup to help the browser treat it as such.
Bonus: you can even use the native check behavior to handle your css, in some cases, via something like this:
[type="checkbox"] { background-image: url('uncheckedIcon.png'); }
[type="checkbox"]:checked { background-image: url('checkedIcon.png'); }

Related

Use addEventListener() to access multiple objects

I want my checkboxes's label to highlight when on and off (like a IRL switch) and I'm not figuring out how to reach all of them without having to make a listener for each of them (I belive there must be some way)
Checkboxes be like:
<label id="labeltest"><input id="checkboxtest" type="checkbox" name="diet" value="Egg" hidden/>Egg</label>
JS be like:
var labeltest = document.getElementById("labeltest")
labeltest.addEventListener("click", function () {
if (this.firstChild.checked) {
this.classList.remove("unchecked")
this.classList.add("checked")
} else if (this.firstChild.checked === false) {
this.classList.remove("checked")
this.classList.add("unchecked")
}
});
I've tried with class instead of ID but didn't work
Also tried something like this with classes to make labeltest an array:
labeltest.forEach(element => {
element.addEventListener("click", function () {
(FUNCTION HERE)
});
But didn't work either
You don't need any JavaScript to accomplish this.
If you reorder your input and labels like this:
<input id="diet-egg" type="checkbox" name="diet" value="Egg" hidden/>
<label for="diet-egg">Egg</label>
Important: Be sure that the for attribute value matches the id of the input the label is connected to. This enables checking and unchecking the checkbox by clicking the <label> element.
Then you can use the adjacent sibling selector + to define the styles of the label whenever the input is checked and unchecked.
input + label {
/* unchecked label styles */
}
input:checked + label {
/* checked label styles */
}

Multiple conditions on single checkbox

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";
}
}

Jquery input value not showing up correctly

I have something very simple to just get an input value.
The code looks like this:
var $a = $('.custom-amount').val();
$('.custom-amount').on('change', function() {
alert($a)
})
And my input:
<div class='custom-amount'>
<input placeholder='Custom Amount' type='text-area'>
For some reason, my alerts are empty. Does anyone see whats going wrong?
Change your selector to $('.custom-amount input'), and get the value after the change event is fired, e.g.
$('.custom-amount input').on('change', function() {
var a = $(this).val();
alert(a);
});
Right now, you are trying to get the value of a div, which won't work. You need to get the value of the input.
Edit: also, it looks like you are trying to display a textarea. Try replacing this...
<input placeholder='Custom Amount' type='text-area'>
With this...
<textarea placeholder='Custom Amount'></textarea>
This may help:
http://jsfiddle.net/d648wxry/
The issue is very simple, you are getting the value of the div element. Instead you should retrieve the value of the input element so the 'custom-amount' class must be added to the input.
Also you need to execute the val() method inside the event to get the value updated.
var $a = $('.custom-amount');
$('.custom-amount').on('change', function() {
alert($a.val());
});
Cause your div has no value. Change your code to:
var $input = $('.custom-amount input');
$input.on('change', function() {
var $a = $input.val();
alert($a)
})
First of all, you only assign to $a outside of the change function. This would be more clear if you kept your code lined up better (see the edit I made to your post). This is the right way to do it:
$('.custom-amount').on('change', function() {
var $a = $('.custom-amount').val();
alert($a)
});
Second of all, the class custom-amount is assigned to a <div> instead of the <input> element. You have to select the <input> element, not the <div>. Change your markup to:
<div>
<input placeholder='Custom Amount' type='text-area' class='custom-amount'>
</div>

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.

How to turn this into a global javascript function effecting all values

This code loads via jQuery a page based onclick events of checkboxes.
function product_analysis(address, box) {
if (box.checked) {
$('#product_' + box.alt).load(address);
} else {
$('#product_' + box.alt).load('http://www.divethegap.com/update/blank2.html');
}
document.getElementById('product_quantity_PRI_' + box.alt).value = box.value;
};
With the onclick event looking as follows onclick="product_analysis('http://www.samedomain.blahblahblah', this)
What I need is that for all checkboxes that are already ticked on page load to have this function applied to them all. I am reasonably confident with javaScript but when it comes to objects and arrays I get lost.
Many Thanks,
You can use this code to find all the checkboxes that are currently checked:
$(':checkbox:checked')
If you then want to do something to all of them, you can use the each function like this:
$(':checkbox:checked').each(function() {
// alerts the checkbox for example
// "this" referes to the checkbox, one after the other
alert(this);
})
Or to do what you asked for ("for all checkboxes that are already ticked on page load to have this function applied to them all"):
$(':checkbox:checked').each(function() {
product_analysis("someaddress", this);
})
EDIT: To address the second issue (not a part of the original question, but to the comments below):
I will assume that you have fields like this in your markup. Use some meaningful IDs rather than my stupid examples of course.
<input type="checkbox" id="foo" />
<input type="checkbox" id="bar" />
<input type="checkbox" id="baz" />
Then you'll put the following in your JS:
var addresses = {
foo: 'some_address',
bar: 'some_other_address',
baz: 'yet_another_one'
};
$(':checkbox:checked').each(function() {
product_analysis(addresses[this.id], this);
})
That will invoke product_analysis with the address that corresponds to the ID of the checkbox.
EDIT (again):
There is actually a way to add meta-data directly to the html-tags that I wasn't aware of. You can add attributes prefixed by "data-" to your tag, like this:
<input type="checkbox" data-address="someaddress" data-foo="something else" data-bar="more data!" />
You can read more about it on John Resigs blog.
this is required script
$().ready(function(){
var box, address;
$(":checkbox").each(function(){
box = this;
if (box.checked) {
address = ""; //you can set address either in hidden fields or in metadata
$('#product_' + box.alt).load(address);
}
else {
$('#product_' + box.alt).load('http://www.divethegap.com/update/blank2.html');
}
document.getElementById('product_quantity_PRI_' + box.alt).value = box.value;
});
});
You need to check how many number of check is checked and then invoke your code.
var checkLength = checkObj.length;
for(var i = 0; i < checkLength ; i++) {
if(radioObj[i].checked) {
}
// here your code base on check box status
}
If you have a class called as "selected" when the check box are checked, you could do something like this
$('.selected').function(element){product_analysis(address, element)};
Thanks chaps for all your help here is I I got it. Jakob will probably consider this a hack but it is a data driven site and based on my limited technical knowledge can't be tasked with modifying a JS file every time we add a new product.
function product_analysis_global() {
$(':checkbox:checked').each(function() {
$('#product_' + this.alt).load(this.title);
});
}
function product_analysis(box) {
if (box.checked) {
$('#product_' + box.alt).load(box.title);
}
else {
$('#product_' + box.alt).load('http://www.divethegap.com/update/blank2.html');
}
document.getElementById('product_quantity_PRI_' + box.alt).value = box.value;
};

Categories

Resources