I am looking to change the style of the parent label when the checkbox is checked. I realise this can't feasibly be done with CSS, is this possible with Javascript?
<label id="cont">
<span>
<input type="checkbox" />
</span>
</label>
Yes, here's an example:
const container = document.querySelector('#cont');
const checkbox = document.querySelector('input');
checkbox.addEventListener('change', () => {
if (checkbox.checked) {
container.style.background = 'red'
} else {
container.style.background = 'white'
}
})
<label id="cont">
<span>
<input type="checkbox" />
</span>
</label>
Your question is a bit unclear. If you have just a single parent element and checkbox like your code suggests, then it's straightforward.
You can define the new styles you want a class(let's say a class called new-style) inside your stylesheet, then add a listener function inside your js script to trigger when the checkbox is clicked. The listener function will basically insert the class into the parent if it doesn't have it or remove it if it does. Something like this.
<script>
let checkbox = document.querySelector('input[type="checkbox"]');
checkbox.onclick = function() {
let parent = document.querySelector('#cont')
parent.classList.toggle('new-style');
}
</script>
Have you tried it this way? You can use css :checked property for this.
input:checked + label {
color: red;
}
<input id="name" type="checkbox">
<label for="name" id="cont">
label
</label>
Related
how can we change classname of parent span element on click of input radio button.
<label for="L">
<span class="lbllevel1">
<span class="label-size">L</span>
<input id="L" name="size" type="radio" value="L">
</span>
</label>
I want to add "selected" class to span element which is with class "lbllevel1" on click of radio button.
Basically, i need output as <span class="lbllevel1 selected"> when radio button is clicked
you can add an event listener to radio button for click event or change event, use document.getElementById('L') to get the input, and inside event handler function use e.currentTarget to get current clicked input, you can use .classList += to add class to element, something like this:
var input = document.getElementById('L');
input.addEventListener("click", function(e){
e.currentTarget.parentElement.classList += ' selected';
})
.selected{
background-color:#888888;
}
<label for="L">
<span class="lbllevel1">
<span class="label-size">L</span>
<input id="L" name="size" type="radio" value="L">
</span>
</label>
var lInput = document.getElementById("L");
lInput.addEventListener("click", function() {
lInput.parentNode.classList.add("selected");
})
You could listen to the change event of radio by then add parent element with selected class if radio is checked:
document.querySelector("#L").addEventListener("change", function () {
// check if radio is checked
if (this.checked)
{
// add .selected class to parent
this.parentElement.classList.add("selected");
}
});
working copy
<label for="L">
<span class="lbllevel1">
<span class="label-size">L</span>
<input id="L" name="size" onclick="changeAttr(this)" type="radio"
value="L">
</span>
</label>
<script>
function changeAttr(ele)
{
ele.parentElement.classList.add('newClass');
}
</script>
Please see if this is helpful or not :)
Check through name
if($("input:radio[name='Name']").is(":checked")) {
//write your code
}
Check through class
if($("input:radio[class='className']").is(":checked")) {
//write your code
}
Check through data
if($("input:radio[data-name='value']").is(":checked")) {
//write your code
}
I have the following html:
<td><label class="checkbox-inline"><input type="checkbox" class="chkRootCauseSummary" /> </label></td>
How can i insert text into the label, without losing the checkbox?
Ive tried the following, but i lose the checkbox:
$('.chkRootCauseSummary').click(function () {
var num = $(this).closest('table').find('input[type=checkbox]:checked').length;
$(this).closest('label').append().html(num);
});
There is a much cleaner way to do it. Simply, while creating your checkbox add a value attribute (or an attribute with any name)
<input type="checkbox" class="chkRootCauseSummary" value="Some Value" />
and use CSS selector :after like
[type=checkbox]:after {
content: attr(value);
}
what you are looking for is a prepend since it needs to be added inside .checkbox-inline and outside .chkRootCauseSummary
Replace
$(this).closest('label').append().html(num);
with
$(this).closest('label').prepend(num);
try this
$('.chkRootCauseSummary').click(function() {
var num = $(this).closest('table').find('input[type=checkbox]:checked').length;
$(this).closest('label').after(num)
});
$('.chkRootCauseSummary').click(function () {
var num = $(this).closest('table').find('input[type=checkbox]:checked').length;
$(this).closest('label').after().html(num);
});
Hi i have a check box using metro-ui
<label class="text_blue small_text">
<input name="enterprise_admin_session[remember_me]" type="hidden" value="0"><input tabindex="3" type="checkbox" value="1" name="enterprise_admin_session[remember_me]" id="enterprise_admin_session_remember_me">
<span class="check border_radius_zero"></span> Keep me logged in </label>
when i use tab and focus on this check-box , i am not able to identify the checkbox is focused. Don't know what i am missing
Or if there is any way from jquery to catch the focus event on the checkbox input and then change the css of <span class ="check border_radius_zero"></span>
Please help me to fix it, Thanks
I'm not really sure what your problem is, but if you want to do it with jQuery here is an example of how you can do it.
$("input[type='checkbox']").focus(function(){
var span_element = $(this).next("span.check.border_radius_zero");
// Change background color
span_element.css("background","red");
// Or Toggle class
span_element.toggleClass("className");
// Or Whatever you want to do with that span
span_element.DoWhateverYouWantWithMe();
});
If you need to discard that changes you made on focus, you can attach a blur event handler.
$("input[type='checkbox']").blur(function(){
var span_element = $(this).next("span.check.border_radius_zero");
// Change background color
span_element.css("background","initial");
// Or Toggle class
span_element.toggleClass("className");
// Or Whatever you want to do with that span
span_element.UnDoWhateverYouWantWithMe();
});
I personaly prefer do it with a class so you can simplify the code, even use the same handler! For example, you can do this.
$("input[type='checkbox']").focus(function(){
var span_element = $(this).next("span.check.border_radius_zero");
span_element.addClass("className");
}).blur(function(){
var span_element = $(this).next("span.check.border_radius_zero");
span_element.removeClass("className");
});
With the same handler:
var focus_blur_event_handler = function(){
var span_element = $(this).next("span.check.border_radius_zero");
span_element.toggleClass("className");
}
$("input[type='checkbox']").bind("focus",focus_blur_eventHandler);
$("input[type='checkbox']").bind("blur",focus_blur_eventHandler);
No need of Javascript or Jquery. You can style using CSS by simply adding this to your stylesheet.
input[type="checkbox"]:focus ~ .check{
/*Your style goes here*/
}
For reference, how to use general sibling selector(~) follow this link http://www.sitepoint.com/web-foundations/general-sibling-selector-css-selector/
Here's the fiddle:
https://jsfiddle.net/6a14tfd0/1/
input[type="checkbox"]:focus ~ .check{
color:red
}
<label class="text_blue small_text">
<input name="enterprise_admin_session[remember_me]" type="hidden" value="0">
<input tabindex="3" type="checkbox" value="1" name="enterprise_admin_session[remember_me]" id="enterprise_admin_session_remember_me">
<span class="check border_radius_zero">***</span> | Keep me logged in </label>
Fiddle link here
<script>
function show1() {
if (document.getElementById("check1").checked == true) {
document.getElementById("info1").style.display="inline";
} else {
if (document.getElementById("check1").checked == false)
document.getElementById("info1").style.display="none";
}
}
</script>
<input type="checkbox" id="check1" name="check1" value="" onclick="show1();">
<style>
#info1, #info2 {
display: none;
}
</style>
What I need to do about 20 times is to show hidden fields info1, info2 etc. when check1, check2 is selected.
First it is always a good idea to find handlers in Javascript instead of inline events.
Second give all your inputs the same class to do so.
Have a data-* attribute that will store the corresponding input message.
You HTML would look like
HTML
<div class="container">
<div>
<input type="checkbox" id="check1" name="check1" value="" data-id="info1" class="checkbox"/>
<label for="check1">Click here for more information</label>
</div>
<div id="info1" class="info">Hidden information here will now appear onclick check1</div>
</div>
<div class="container">
<div>
<input type="checkbox" id="check2" name="check3" value="" data-id="info2" class="checkbox"/>
<label for="check2">Click here for more information</label>
</div>
<div id="info2" class="info">Hidden information here will now appear onclick check2</div>
</div>
<div class="container">
<div>
<input type="checkbox" id="check3" name="check3" value="" data-id="info3" class="checkbox"/>
<label for="check3">Click here for more information</label>
</div>
<div id="info3" class="info">Hidden information here will now appear onclick check3</div>
</div>
JS
// Get all the checkbox elements
var elems = document.getElementsByClassName('checkbox');
// iterate over and bind the event
for(var i=0; i< elems.length; i++) {
elems[i].addEventListener('change', show);
}
function show() {
// this corresponds to the element in there
// Get the info attribute id
var infoId = this.getAttribute('data-id');
if (this.checked) {
document.getElementById(infoId).style.display = "inline";
} else {
document.getElementById(infoId).style.display = "none";
}
}
Check Fiddle
This is one way of doing this.
I've updated your jsfiddle:
document.addEventListener('change', function(e) {
var id = e.target.getAttribute('data-info-id');
var checked = e.target.checked;
if (id) {
var div = document.getElementById(id);
if (div) div.style.display = checked ? 'block' : 'none';
}
});
Instead of creating an if ... else block for every checkbox, which becomes hard to maintain, I've associated every check with its DIV via the custom attribute data-info-id, which is set to the id of the aforementioned DIV.
I bind the 'change' event to the document (event delegation) and when it fires I check the source element has a data-info-id attribute. Then, I get the DIV with such id and show or hide it based on the value of the checked property.
The obvious advantage of doing it this way, via custom attributes, is that you don't depend of the position of the div, and you can change which checks shows what DIV in a declarative way, just changing the HTML.
Maybe you are looking for a javascript only solution, but there's a pretty simple solution in CSS
HTML
<div>
<input type="checkbox" id="check1" name="check1" value="" />
<label for="check1"> Click here for more information</label>
<div id="info1">Hidden information here will now appear onclick </div>
</div>
<div>
<input type="checkbox" id="check2" name="check2" value=""/>
<label for="check2"> Click here for more information</label>
<div id="info2">Hidden information here will now appear onclick </div>
</div>
CSS
input[type=checkbox] ~ div {
display: none;
}
input[type=checkbox]:checked ~ div {
display: block;
}
Fiddle here
Looks for an input with the data-enable attribute that matches to the id of the element being shown/hidden.
HTML
<input type="checkbox" data-enable="info0" name="check[]"/>
<input type="text" id="info0" name="info[]"/>
Javascript
function toggleEl(evt) {
var checkbox = evt.target;
var target = checkbox.getAttribute('data-enable');
var targetEl = document.getElementById(target);
// if checked, use backed-up type; otherwise hide
targetEl.type = (checkbox.checked)
? targetEl.getAttribute('data-type')
: 'hidden';
}
var inputs = document.getElementsByTagName('input');
for(var i=0,l=inputs.length;i<l;i++) {
var input = inputs[i];
var target = input.getAttribute('data-enable');
if(target!==null) {
var targetEl = document.getElementById(target);
// back-up type
targetEl.setAttribute('data-type',targetEl.type);
// hide it if the checkbox is not checked by default
if(!input.checked)
{ targetEl.type = 'hidden'; }
// add behavior
input.addEventListener('change',toggleEl,false);
}
}
Check out the following JSFiddle .
//<![CDATA[
// common.js
var doc = document, bod = doc.body, IE = parseFloat(navigator.appVersion.split('MSIE')[1]);
bod.className = 'js';
function gteIE(version, className){
if(IE >= version)bod.className = className;
}
function E(e){
return doc.getElementById(e);
}
//]]>
//<![CDATA[
// adjust numbers as needed
for(var i=1; i<2; i++){
(function(i){
E('check'+i).onclick = function(){
var a = E('info'+i).style.display = this.checked ? 'block' : 'none';
}
})(i);
}
//]]>
I have a form with a text input and a radio button pair used to select yes/no. For purposes of keeping this simple, the radio button click event checks the value and if yes, it shows the input text field. If no, it hides the input field. I also check the initial state on document ready and show/hide the input text field.
I find that clicking No results in the input hiding using a jQuery .hide() method. But when I select Yes the resulting .show() method call does not show the input. If I set the radio to Yes and then refresh the page then the input shows up just fine.
Firebug show no input tag. It's like clicking No radio deleted the input from the DOM.
Here's the JS code sample:
$(document).ready(function() {
if ($('#cost_sharing_yes').attr('checked') == 'checked') {
$('input#Institutional_CS_TP').show();
} else {
$('input#Institutional_CS_TP').hide();
}
$('#cost_sharing_yes').click(function() {
$('input[id="Institutional_CS_TP"]').show();
});
$('#cost_sharing_no').click(function() {
$('input#Institutional_CS_TP').fadeOut("fast");
});
}
You are missing ) for closing ready function:
$(document).ready(function() {
} // <--
For getting the checked property of the inputs perperly you should use prop method instead of attr.
$(document).ready(function() {
var isChecked = $('#cost_sharing_yes').prop('checked');
$('#Institutional_CS_TP').toggle(isChecked);
// ..
})
I figured out my problem. It was a self-inflicted coding problem.
To keep the example simple I had removed another function call in the mix that I didn't think had any bearing on the problem. I was wrong. In that function I had
$('td#Institutional_CS_TP).text('$0');
$('input[name="Institutional_CS_TP"]').val('0.00');
This resulted in only the td value showing, not the input inside that same td.
Both my td and the input tags inside the td had the same ID values...not a good idea.
html code
<div id="myRadioGroup">
Value Based<input type="radio" name="cars" value="2" />
Percent Based<input type="radio" name="cars" value="3" />
<br>
<div id="Cars2" class="desc" style="display: none;">
<br>
<label for="txtPassportNumber">Commission Value</label>
<input type="text" id="txtPassportNumber" class="form-control" name="commision_value" />
</div>
<div id="Cars3" class="desc" style="display: none;">
<br>
<label for="txtPassportNumber">Commission Percent</label>
<input type="text" id="txtPassportNumber" class="form-control" name="commision_percent" />
</div>
</div>
Jquery code
function myFunction() {
var x = document.getElementById("myInput");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
function myFunction1() {
var y = document.getElementById("myInput1");
if (y.type === "password") {
y.type = "text";
} else {
y.type = "password";
}
}