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 */
}
Related
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";
}
}
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'); }
I am writing a program in which when a user click on check box , the font of the input (which i am writing) changes. Like firstly if the check box is unchecked the font is 'arial' and when the check box is checked the input font should become 'verdana'.
I am able to do this but the function changes all the previous text written into verdana.
Code Sample:
<input type= "checkbox" onchange = "tests();" name="remember" id = "remember"> **(Checkbox)**
function tests(){
if (remember.checked == 1){
$(.form-control).css('font-family','verdana');
}else{
$('.form-control').css('font-family','arial');
}
}
i need that whenever i check this , the upcoming data should be in verdana and the previous should remain same in input box.
Instead of changing the font of whole form class $(.form-control) do it for specific class of checkbox
Update:
add this css
input[type=checkbox]:checked + label {
font-family:'verdana'
}
input[type=checkbox] + label {
font-family:'arial'
}
In your code you seem to be using JQuery, so you can do this:
$("#remember").change(function() {
if ($(this).is(":checked")) {
$(".myText").css("font-family", "Verdana");
} else {
$(".myText").css("font-family", "Arial");
}
});
Here is the JSFiddle demo
I have a situation where I have the following form elements:
<label for="edit-type-config-associated-element--2">Destination Data Element </label>
<input type="text" id="edit-type-config-associated-element--2"
name="type_config[associated_element]" value="23" size="60"
maxlength="128" class="form-text ajax-processed"
style="visibility: hidden;">
<input type="text" id="edit-type-config-associated-element--2_display"
value="23" size="60" maxlength="128"
class="form-text ajax-processed dropdowntree_aux dropdowntree_input valid"
readonly="" style="top: 61.515625px; left: 15px; position: absolute;
width: 389px; height: 16px;">
I would like to add a change listener to the second input element (identified by edit-type-config-associated-element--2_display) and then change the input in the first input element (identified by edit-type-config-associated-element--2). The catch here is that everytime this form is displayed the number appearing at the end of both ids increments by one (why they couldn't use a consistent id, I have no idea but it is what I am stuck with).
Here is the javascript I am using to try and accomplish this:
// Add a change listener to associated element link for dc mappings
$('.dropdowntree_input').live('change', function () {
// Get the data element id
var dataElementID = $.trim($(this).val()),
dataElementLinks = Drupal.settings.data_element_links;
console.log('text field has changed to: ' + dataElementID);
if (dataElementLinks.hasOwnProperty(dataElementID)) {
$('#linked_form_elements').show();
} else {
$('#linked_form_elements').hide();
}
// Update the underlying text input to contain the right value.
$(':input[type="text"][name="type_config[associated_element]"]').val(dataElementID);
However this is not working. It seems that this function is never called when the second textfield is updated.
Any ideas where I have gone off the rails?
Thanks.
Looks like you were missing a [ in your selector
$('input[type="text"][name="type_config[associated_element]"]').val(dataElementID);
^ here
Also if you are using jQuery >= 1.9 then .live() is no longer supported.
If you are using jQuery >= 1.7 then use .on() instead, also since the first and second inputs are next/prev siblings you can use that relationship to find the element
$(document).on('change', '.dropdowntree_input', function () {
var dataElementID = $.trim($(this).val()),
dataElementLinks = Drupal.settings.data_element_links;
console.log('text field has changed to: ' + dataElementID);
if (dataElementLinks.hasOwnProperty(dataElementID)) {
$('#linked_form_elements').show();
} else {
$('#linked_form_elements').hide();
}
//since the hidden element is the previous sibling
$(this).prev().val(dataElementID);
})
I'm trying to make radio buttons that when you have them active, it displays a dropdown. I can already make it display, but when I click on another radio button, it shows one, but doesn't hide the other...
Code:
<input type='radio' name='op' onchange='$("#ban_length").fadeToggle();'/>
<input type='radio' name='op' onchange='$("#rank_list").fadeToggle();'/>
JavaScript section:
$(document).ready(function() {
$('#op1').change(function(){
$("#ban_length").fadeIn();
$("#rank_list").fadeOut();
});
$('#op2').change(function(){
$("#ban_length").fadeOut();
$("#rank_list").fadeIn();
});
});
HTML:
<input type='radio' name='op' id='op1'/>
<input type='radio' name='op' id='op2'/>
<div id="ban_length">demo</div>
<div id="rank_list">demo</div>
Demo:
http://jsfiddle.net/b2UPt/1/
<input type='radio' name='op' onchange='$("#ban_length").fadeIn();$("#rank_list").fadeOut();'/>
<input type='radio' name='op' onchange='$("#rank_list").fadeIn();$("#ban_length").fadeOut();'/>
Though I would suggest removing the javascript from the elements themselves, giving them ids and adding the javascript to a separate script with $(theID).change(function(){....
Alternatively, you can use hide instead of fadeOut if you would like them to hide immediately.
And one last suggestion. If there are many of these and not just 2, I would add a shared class to each of the elements you are fading in. Then instead of hide on each element, just call $(".className").hide() to hide any that might be visible.
The change event only fires on the element that was clicked (i.e. the radio button that is now enabled). It isn't fired when a radio button is automatically disabled.
So you need to check all the radio buttons every time one of them triggers the change event. You need to be able to tell them apart, though, so start by giving them ids:
<input type="radio" name="op" id="radio_ban_length" />
<input type="radio" name="op" id="radio_rank_list" />
After that, you can use them to toggle the correct dropdowns:
$('input:radio').change(function() {
var id = $(this).attr("id");
if (id === "radio_ban_length") {
$("ban_length").fadeIn();
$("rank_list").fadeOut();
} else {
$("rank_list").fadeIn();
$("ban_length").fadeOut();
}
});
Alternatively, if you like a challenge or if you might have more than two radio's, you could use filter() and :checked to do something like this:
function getDropdownId(radioId) {
return '#' + radioId.replace(/^radio_/, '');
}
var radios = $('input:radio');
radios.change(function() {
// Checked radio's:
radios.filter(':checked').each(function(){
var id = getDropdownId($(this).attr('id'));
$(id).fadeIn();
});
// Unchecked radio's:
radios.filter(':not(:checked)').each(function(){
var id = getDropdownId($(this).attr('id'));
$(id).fadeOut();
});
});
Note that this method does rely on the id's of the radio buttons matching those of the dropdowns (e.g. radio_ban_length for ban_length).
Update: here is a live example: http://jsfiddle.net/55ANB/1/
add id="ban" and id="rank" to your radios
in your jquery section, add the click handler to the radio buttons
$(':radio').click(function() {
if ($(this).attr("id") == "ban") $("ban_length").fadeToggle();
if ($(this).attr("id") == "rank") $("rank_length").fadeToggle();
});