jquery - check/uncheck customized checkbox with hidden input - javascript

I have this in HTML
<div class="my-checkbox">
<label>I do agree</label>
<input type="hidden" name="agreement" value="0">
</div>
and this in jQuery
$('.my-checkbox').on('click', function()
{
if($(this).children('[type="hidden"]').val() == 0)
{
$(this).children('[type="hidden"]').val(1);
$(this).addClass('active');
}
else
{
$(this).children('[type="hidden"]').val(0);
$(this).removeClass('active');
}
});
When I click .my-checkbox, it will change the value to 1 and add class active and when I click it again vice-versa. It works correctly but in mobile device when I click it it changes the value and set to active but when I click it again, it changes the value but the active class doesn't remove. How do I know that? just by double clicking and submit the form and the result was => you should agree with agreements.
Thanks

Makes no sense to reinvent the checkbox when it is a is simple CSS to change the style to make it work the same way. No adding/removing classes. No JavaScript needed, just a simple CSS selector.
#agree + label {
color: red
}
#agree:checked + label {
color: green
}
<div class="my-checkbox">
<input type="checkbox" id="agree" name="agreement" hidden>
<label for="agree" >I do agree</label>
</div>
Now why does your code not work?
if($(this).children('[type="hidden"]').val() == 0) <-- If zero
{
$(this).children('[type="hidden"]').val(0); <-- set zero
You are not toggling to 1. You have your logic reversed.

Related

Show hide text box from a dynamic element jQuery c#

Below is my code, I am trying to hide and show dynamic elements. The problem I am having is, I only want my hidden div to only show one at a time if only I check "Other". However, the code below will show the hidden div for all number of #dynamicRows I have. so it works for initial 1st #dynamicRow added, the problem is when I have two or more #dynamicRows
$('#dynamicRow').on('click', 'input[id^=race]', function () {
if ($(this).is(":checked")) {
if ($(this).val() == "Other") {
$(".cssclass").each(function (index) {
$(this).closest("div").show();
});
}
else {
$(".cssclass").each(function () {
$(this).closest("div").hide();
});
}
}
});
Below are dynamic rows, for help purposes i am showing the html code, however, it doesn't exist on the screen, a user will click "ADD" to generate the code below. I have no problem in generating dynamic row and it is not why I am posting. note the name in my radio button is generated by c# and everything works. Again the problem is not how to create a dynamic row, it is nicely taken care of in C#.
Dynamic row one works with the above jQuery:
<div id="dynamicRow">
<input type="radio" value="No" id="race[]" name="Person[hhhhhh].race"> No:
<input type="radio" value="Other" id="race[]" name="Person[hhhhhh].race"> Other:
<div id="iamhidden" class="cssclass">
I appear one at a time, when other radio button is checked
</div>
</div>
Dynamic row two doesn't work with the above jquery and it takes the above form events as its own, so if i check the radio button in row 2, the 1st dynamic row responds to that event and vice versa:
<div id="dynamicRow">
<input type="radio" value="No" id="race[]" name="Person[hhhhh].race"> No:
<input type="radio" value="Other" id="race[]" name="Person[hhhhh].race"> Other:
<div id="iamhidden" class="cssclass">
I appear one at a time, when other radio button is checked
</div>
</div>
Working Example
id should be unique in same document, replace the duplicate ones by a class :
<input type="radio" value="No" class="race" name="Person[hhhhhh].race"> No:
<input type="radio" value="Other" class="race" name="Person[hhhhhh].race"> Other:
Also add class and not id to the dynamic rows generated by your C# code :
<div class="dynamicRow">
Then in your js use this class :
$(".cssclass").hide();
$('.dynamicRow').on('click', '.race', function () {
if ($(this).val() == "Other") {
$(this).next(".cssclass").show();
} else {
$(this).nextAll(".cssclass").hide();
}
});
Hope this helps.
Try this:
$('body').on('click', '#dynamicRow', function () {
if ($(this).find('[value=Other]').is(":checked")) {
$(".cssclass").each(function (index) {
$(this).closest("div").show();
});
} else {
$(".cssclass").each(function () {
$(this).closest("div").hide();
});
}
});
He is a working example of what you wanted. I am generating the required with js only.
Few Points to mention
you add the event listener to the parent of the dynamic generated content.
Avoid use of IDs if they are not going to be unique and prefer classes and pseudo selectors if required
var counter = 0;
function addNewEntry(){
++counter;
var str = '<div class="dynamicRow"><input type="radio" value="No" id="race[]" name="Person[hh'+counter+'].race"> No:<input type="radio" value="Other" id="race[]" name="Person[hh'+counter+'].race"> Other:<div id="iamhidden" class="cssclass"> I appear one at a time, when other radio button is checked</div> </div>';
$('#dynamicRowContainer').append(str);
$("#dynamicRowContainer .dynamicRow:last-child .cssclass").hide()
}
$('#dynamicRowContainer').on('change', '.dynamicRow > input', function () {
if(this.value=="Other"){
$(this).siblings('.cssclass').show();
}else{
$(this).siblings('.cssclass').hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="addNewEntry()">Add New Entry</button>
<div id="dynamicRowContainer">
</div>

css metro-ui not able to show focus on check-box

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>

Automatically checking / unchecking parent inputs

I'm hoping someone can help me out here.
I'm trying to automatically check parent items in an input list, but also uncheck children if the parent is unchecked.
The great thing is I found some code that replicates the desired functionality perfectly: http://jsfiddle.net/3y3Pb/14/
EDIT: To clarify - the functionality required is this: Check mark a child input & all of the parent items get checked. Uncheck a Parent - all child inputs get unchecked. See the above example.
However, this doesn't seem to be working with my particular code (it's output from a WordPress plugin - Advanced Custom Fields) so I don't want to modify it).
I've narrowed it down to what I BELIEVE is the problem. ACF wraps each input with a <label></label>. I don't know why, but this breaks the functionality:
http://jsfiddle.net/3y3Pb/223/
When I remove the <label></label> it works fine:
http://jsfiddle.net/3y3Pb/225/
Changing the markup isn't really an option here, I would REALLY appreciate it if someone could assist me in making this work!
This should work, its simple and only uses divs and a few lines of jquery:
$('[type="checkbox"]').change(function () {
var kids = $(this).next().next();
if (kids.is('div') && !$(this).prop('checked'))
{
kids.children().each(function(){$(this).prop('checked',false)});
}
var thisChecked = $(this).prop('checked');
var master = $(this).parent().prevAll('[type="checkbox"]:first');
master.prop('checked', thisChecked ? true : master.prop('checked'));
});
div {
margin-left: 25px;
}
div div {
margin-left: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />Master Check
<br />
<div>
<input type="checkbox" />Slave Check 1
<br />
<input type="checkbox" />Slave Check 2
<br />
<input type="checkbox" />Slave Check 3
<br />
<div>
<input type="checkbox" />Slave 2 Check 1
<br />
<input type="checkbox" />Slave 2 Check 2
<br />
<input type="checkbox" />Slave 2 Check 3</div>
</div>
I have improved the javascript code.
$(document).ready(function() {
$('input[type=checkbox]').click(function(){
// if is checked
if($(this).is(':checked')){
$(this).parents('ul').children('li').children('label').find('input').prop('checked', true);
} else {
// uncheck all children
$(this).closest('li').find('input').prop('checked', false);
}
});
});
Children travels a single level down the DOM tree, whereas find goes for multiple levels down looking into descendants.
It was the label - here is the solution:
$('input[type=checkbox]').click(function(){
// if is checked
if($(this).is(':checked')){
$(this).parents('li').children('label').find('input[type=checkbox]').prop('checked', true);
} else {
// uncheck all children
$(this).closest('li').find('input[type=checkbox]').prop('checked', false);
}
});

Checking a different checkbox hides input field

I have an input field that only shows when the option "Other" is checked. The input field fades out when I uncheck the "Other" checkbox, but I would also like the input field to fade out say if, instead of unchecking the "Other" checkbox I check another checkbox of the same group. Therefore, the "Other" input field should not be visible unless "Other" is checked. I have the javascript partially working, but when I check another checkbox the "Other" input field stays visible.
HTML
<input type="checkbox" id="residence_check" name="found"/>
<label for="residence_check">
Residence
</label>
<input type="checkbox" id="tradeshow_check" name="found"/>
<label for="tradeshow_check">
Tradeshow
</label>
<input type="checkbox" id="office_check" name="found"/>
<label for="office_check">
Office Building
</label>
<input type="checkbox" id="check_other" value="found_other" name="found"/>
<label for="check_other">
Other
</label>
<input type="text" id="check_input" placeholder="Other"/>
Javascript
$('#check_other').change(function() {
if($(this).is(":checked")) {
$('#check_input').fadeIn();
} else {
$('#check_input').fadeOut('fast');
}
});
From what I gather from your use case is that you don't want to use checkboxes, but radio buttons. If that is the case, this would be a good way to implement what you want:
http://jsfiddle.net/AeP58/1/
$('input[type=radio]').on('change', function() { //event on all radio buttons
if($(this).attr('id') == 'check_other' && $(this).prop('checked')) {
$('#check_input').fadeIn();
} else {
$('#check_input').fadeOut('fast');
}
});
If you do want checkboxes, you could change the code a bit and probably get what you want.
If you want to have some fun with checkboxes you could try this:
function showHideOtherInput() {
console.log($(this)[0]==$('#check_other')[0]);
var shouldShow=$('[id$="_check"]:checked').length===0 && $('#check_other').prop('checked');
console.log(shouldShow);
if(shouldShow) {
$('#check_input').fadeIn();
} else {
$('#check_input').fadeOut('fast');
}
}
$('#check_input').hide(); //since nothing is selected at this point just hide the input
$('#check_other').change(showHideOtherInput);
//for each XXXX_check checkbox trigger the show or hide function
$('[id$="_check"]').each(function(ix,el){$(el).change(showHideOtherInput)});
Hope this works for you.
:)

How to display diffrence divs according to radio selection

I have 2 radio buttons no one of them checked by default and I want if any one of them checked a Div appear according to what radio button was checked.
( Divs have different content )
and if the selection changed the one which appeared now disappear and the other appear.
and when one of them appear there are another 2 radio to do the same thing for another one div ( one to show and one to hide )
Here what I tried to do
JavaScript
function haitham()
{
if(document.getElementById('s').checked == true)
{
document.getElementById('StudentData').style.display = "block";
document.getElementById('GraduateData').style.display = "none";
}
else if(document.getElementById('g').checked == true)
{
document.getElementById('GraduateData').style.display = "block";
document.getElementById('StudentData').style.display = "none";
}
}
function info()
{
if(document.getElementById('y').checked == true)
{
document.getElementById('MoreInfo').style.display = "block";
}
else if(document.getElementById('n').checked == true)
{
document.getElementById('MoreInfo').style.display = "none";
}
}
HTML
<input class="margin2" id="s" type="radio" name="kind" value="student" onchange="haitham()"
required="required" />Student
<input class="margin2" id="g" type="radio" name="kind" value="graduate" onchange="haitham()"
required="required" />Graduate
<div id="StudentData">
content 1
<input class="margin2" id="y" type="radio" name="info" value="yes" onchange="info()"
required="required" />Student
<input class="margin2" id="n" type="radio" name="info" value="no" onchange="info()"
required="required" />Graduate
</div>
<div id="GraduateData">
content 2
</div>
<div id="MoreInfo">
content 3
</div>
the first work good but the other 2 radio did not work although it should be the same
Thank you ...
Your problem wasn't a javascript or html one, it was actually a CSS issue. Your code was fine, aside from the fact that the values for display are "none" and "block" not "" and "hidden". I modified your code and updated the fiddle.
Here's the link:
http://jsfiddle.net/8JpSQ/4/
Just add a clicked event to the radio buttons, and through a Javascript function change the attribute of the respective DIV to hidden when required. To show it instead, remove the attribute 'hidden'. Also, we'd probably be able to help more if you can post some code showing what you tried/what went wrong. But what I suggested should be the general approach to make what you want happen.
I have no idea what your HTML is, so here's what I have:
$('input[type="checkbox"]').click(function() {
$('.divWrapper > div').eq($(this).index()).fadeOut().siblings().fadeIn();
});
I'm assuming this is your structure:
<form>
<checkbox>
<checkbox>
...
</form>
<div class="divWrapper">
<div>
<div>
...
</div>

Categories

Resources