I have this code that I'm still modifying. But I'm still having a hard time. I'm new in jquery . I'm planning to make a multiple checkbox with image. please check my code. It's not working. my sample code is two checkbox. Im planning to put it on array so that I could put more than two checkboxes with image. instead of making jquery code in each of checkbox.
here is my code
html
<form id="form1">
<img src="https://cdn2.iconfinder.com/data/icons/windows-8-metro-style/128/unchecked_checkbox.png" title="blr" id="blr" class="" />
<input type="checkbox" id="imgCheck[]" name="imgCheck" value="barney" />
<img src="https://cdn2.iconfinder.com/data/icons/windows-8-metro-style/128/unchecked_checkbox.png" title="blr" id="blr" class="" />
<input type="checkbox" id="imgCheck[]" name="imgCheck" value="barney2" />
<input type="submit" value="Submit" />
</form>
jquery
$('img').on('click', function(){
var $$ = $(this)
if( !$$.is('.checked')){
$$.addClass('checked');
$('input[id=imgCheck]').prop('checked', true);
} else {
$$.removeClass('checked');
$('input[id=imgCheck]').prop('checked', false);
}
})
style
.checked {border:solid 2px red}
Try
$('img').on('click', function () {
var $$ = $(this)
//toggle the checked state
$$.toggleClass('checked');
//set the next checkbox's state in synch with the checked state of the image
//from the given markup we can assume that an image will always be related to the next sibling element which will be checkbox
$$.next('input').prop('checked', $$.hasClass('checked'));
})
Demo: Fiddle
toggleClass()
hasClass()
next()
Related
I would like to conditionally disable a button based on a radio and checkbox combination. The radio will have two options, the first is checked by default. If the user selects the second option then I would like to disable a button until at least one checkbox has been checked.
I have searched at length on CodePen and Stack Overflow but cannot find a solution that works with my conditionals. The results I did find were close but I couldn't adapt them to my needs as I am a Javascript novice.
I am using JQuery, if that helps.
If needed:
http://codepen.io/traceofwind/pen/EVNxZj
<form>
<div id="input-option1">First option: (required)
<input type="radio" name="required" id="required" value="1" checked="checked">Yes
<input type="radio" name="required" id="required" value="2">No
<div>
<div id="input-option2">Optionals:
<input type="checkbox" name="optionals" id="optionals" value="2a">Optional 1
<input type="checkbox" name="optionals" id="optionals" value="2b">Optional 2
<div>
<div id="input-option3">Extras:
<input type="checkbox" name="extra" id="extra" value="3">Extra 1
<div>
<button type="button" id="btn">Add to Cart</button>
</form>
(Please excuse the code, it is in short hand for example!)
The form element IDs are somewhat fixed. The IDs are generated by OpenCart so I believe the naming convention is set by group, rather than unique. I cannot use IDs such as radio_ID_1 and radio_ID_2, for example; this is an OpenCart framework facet and not a personal choice.
Finally, in pseudo code I am hoping someone can suggest a JQuery / javascript solution along the lines of:
if radio = '2' then
if checkboxes = unchecked then
btn = disabled
else
btn = enabled
end if
end if
Here is a quick solution and I hope that's what you were after.
$(function() {
var $form = $("#form1");
var $btn = $form.find("#btn");
var $radios = $form.find(":radio");
var $checks = $form.find(":checkbox[name='optionals']");
$radios.add($checks).on("change", function() {
var radioVal = $radios.filter(":checked").val();
$btn.prop("disabled", true);
if (radioVal == 2) {
$btn.prop("disabled", !$checks.filter(":checked").length >= 1);
} else {
$btn.prop("disabled", !radioVal);
}
});
});
Here is a demo with the above + your HTML.
Note: Remove all the IDs except the form ID, button ID (since they're used in the demo) as you can't have duplicate IDs in an HTML document. an ID is meant to identify a unique piece of content. If the idea is to style those elements, then use classes.
If you foresee a lot of JavaScript development in your future, then I would highly recommend the JavaScript courses made available by Udacity. Although the full course content is only available for a fee, the most important part of the course materials--the videos and integrated questions--are free.
However, if you don't plan to do a lot of JavaScript development in the future and just need a quick solution so you can move on, here's how to accomplish what you are trying to accomplish:
$(document).ready(function(){
$('form').on('click', 'input[type="radio"]', function(){
conditionallyToggleButton();
});
$('form').on('click', 'input[type="checkbox"]', function(){
conditionallyToggleButton();
});
});
function conditionallyToggleButton()
{
if (shouldDisableButton())
{
disableButton();
}
else
{
enableButton();
}
}
function shouldDisableButton()
{
if ($('div#input-option1 input:checked').val() == 2
&& !$('form input[type="checkbox"]:checked').length)
{
return true;
}
return false;
}
function disableButton()
{
$('button').prop('disabled', true);
}
function enableButton()
{
$('button').prop('disabled', false);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div id="input-option1">First option: (required)
<input type="radio" name="required" id="required" value="1" checked="checked">Yes
<input type="radio" name="required" id="required" value="2">No
<div>
<div id="input-option2">Optionals:
<input type="checkbox" name="optionals" id="optionals" value="2a">Optional 1
<input type="checkbox" name="optionals" id="optionals" value="2b">Optional 2
<div>
<div id="input-option3">Extras:
<input type="checkbox" name="extra" id="extra" value="3">Extra 1
<div>
<button type="button" id="btn">Add to Cart</button>
</form>
Note that the JavaScript code above is a quick-and-dirty solution. To do it right, you would probably want to create a JavaScript class representing the add to cart form that manages the behavior of the form elements and which caches the jQuery-wrapped form elements in properties.
I have a simple Checkbox
<div>
<input type="checkbox" id="chkBox1" value="Test" /> Test
</div>
MVC 5 renders this html for this checkbox
<div class="checker" id="uniform-chkBox1">
<span class="checked">
<input type="checkbox" value="Test" id="chkBox1">
</span>
</div>
I want to uncheck this checkbox using Javascript/JQuery but I cannot figure it out. Using Firebug, when I remove the span class "checked" the checkbox gets unchecked but I cannot figure out how to do this in Javascript.
$('#chkBox1').prop('checked', true)
checks it off and
$('#chkBox1').prop('checked', false) turns if off.
Instead of prop(), you can also use attr()
If you instead want to just remove the class checked from the span element. you can do
$('#uniform-chkBox1 span.checked').removeClass('checked')
Use .prop().
In your case $("#chkBox1").prop("checked", false); will uncheck and $("#chkBox1").prop("checked", true); will check.
Run code below to see in action.
setInterval(function() {
if ($("#chkBox1").prop("checked"))
$("#chkBox1").prop("checked", false);
else
$("#chkBox1").prop("checked", true);
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" value="Test" id="chkBox1" checked />
First of all: http://jsfiddle.net/1q5st19f/
I have a checkbox group where if all the child checkboxes (countries) are checked, the parent checkbox (region) becomes checked as well. Likewise, if the parent checkbox is unchecked, the child checkboxes should be unchecked, too. I found a script that worked perfectly until I styled the checkboxes with prettyCheckable (from http://arthurgouveia.com/prettyCheckable/).
If I remove prettyCheckable, it works. If I add it, it's correctly styled but won't work anymore. What am I doing wrong? I tried to rename the classes but that didn't work either.
The basic markup is like
<fieldset>
<input type="checkbox" class="parentCheckBox" /> Africa
<div class="content">
<input type="checkbox" value="1" name="cntrs[]" class="childCheckBox" data-label=""> Algeria<br />
<input type="checkbox" value="2" name="cntrs[]" class="childCheckBox" data-label=""> Angola<br />
<input type="checkbox" value="3" name="cntrs[]" class="childCheckBox" data-label=""> Benin<br />
</div>
</fieldset>
prettyCheckable made this a bit tricky. It says in the documentation that you can use $('#myInput').prettyCheckable('check'); but I could not get it to work. So I just used the anchors class checked instead to determine if the checkbox is checked.
This may not be the most pretty implementation but it's working. You should make the code more modular an maybe reconsider some of the choices I quickly made.
First I removed the childCheckBox from the HTML and initialized prettyCheckable with options, so I could get the class to the wrapper div:
// make childCheckboxes prettyCheckable
$('.content input:checkbox').each(function () {
$(this).prettyCheckable({
// add this class to the wrapper div created by prettyCheckable
customClass: "childCheckBox"
});
});
Same with the parentCheckbox:
// make parentCheckBox prettyCheckable
$('input:checkbox.parentInput').prettyCheckable({
// add this class to the wrapper div created by prettyCheckable
customClass: "parentCheckBox"
});
I also changed childCheckBox click event to do the functionality you wanted
//clicking the last unchecked or checked checkbox should check or uncheck the parent checkbox
$('.childCheckBox').click(function () {
var $parentAnchor = $(this).parents('fieldset:eq(0)').find('.parentCheckBox a');
var $childAnchors = $(this).parents('fieldset:eq(0)').find('.childCheckBox a');
var $thisAnchor = $(this).find('a');
var parentIsChecked = $parentAnchor.hasClass('checked');
var thisIsChecked = $thisAnchor.hasClass('checked');
var isLastOne = true;
// loop through all childCheckBoxes and determine if this is the last one checked or unchecked
$childAnchors.each(function (index) {
if ((!thisIsChecked && $(this).hasClass('checked'))
|| (thisIsChecked && !$(this).hasClass('checked'))) {
isLastOne = false;
}
});
// if the childCheckBox was the last one, change the state of the parentCheckBox
if (isLastOne && thisIsChecked) {
$parentAnchor.addClass('checked');
} else if (isLastOne && !thisIsChecked) {
$parentAnchor.removeClass('checked');
}
});
I was pretty tired when forking this, so I hope I didn't do any stupid mistakes. If you have any questions about the code, please ask.
Fiddle: http://jsfiddle.net/1q5st19f/17/
This took me forever to debug. There were a number of issues most importantly of which was that you are using a very backlevel version of prettyCheckable. However, after changing to the latest level and starting again, I have a fully working solution for you. See this jsFiddle.
I started again from the beginning but here is the code:
HTML
<fieldset>
<div class="group">
<input type="checkbox" class="parentCheckBox" data-label="Africa"/>
<div class="content">
<input type="checkbox" value="1" class="childCheckBox" data-label="Algeria" />
<br />
<input type="checkbox" value="2" class="childCheckBox" data-label="Angola" />
<br />
<input type="checkbox" value="3" class="childCheckBox" data-label="Benin" />
<br />
</div>
</div>
</fieldset>
JavaScript
$(function () {
$('input:checkbox').each(function () {
$(this).prettyCheckable();
});
$(".parentCheckBox").change(function (e) {
var checked = $(this).prop("checked");
$(".childCheckBox", $(this).closest(".group")).each(function (i, e) {
$(e).prettyCheckable(checked?"check":"uncheck");
});
});
$(".childCheckBox").change(function(e) {
var checkedCount = unCheckedCount = 0;
$(e.currentTarget).closest(".content").find(".childCheckBox").each(function(i,e2) {
if ($(e2).prop("checked")) {
checkedCount++;
} else {
unCheckedCount++;
}
});
if (unCheckedCount == 0) {
$(e.currentTarget).closest(".group").find(".parentCheckBox").prettyCheckable("check");
} else {
$(e.currentTarget).closest(".group").find(".parentCheckBox").prettyCheckable("uncheck");
}
});
});
I'll be delighted to answer any questions you may have.
The semantics of checking or unchecking all children could have an alternate solution shown in this jsFiddle. It talks to when the parent checkbox should be checked or unchecked as a function of the children.
What prettyCheckable does behind the scenes, is it hides the checkboxes and adds an a tag to the page, and updates the hidden checkboxes when the a tag is clicked. The a tag also gets a style of checked when the checkbox is checked. There appears to be a bug though, that the checked class is not added to or removed from the a tag when the state of the checkboxes is manipulated through code. Anyway, your JavaScript was correctly updating the state of the checkboxes, but prettyCheckable wasn't detecting that and failed to update its classes.
Anyway, I rewrote your script so all the logic is handled in 1 event handler, and I included a work-around for the prettyCheckable bug, but I left your HTML alone so you should only have to replace your JavaScript code. See below for a runnable example:
$('input:checkbox').prettyCheckable();
$("input:checkbox").on("change", function() {
var checkbox = $(this);
var parent = checkbox.closest("fieldset");
if (checkbox.hasClass("parentCheckBox")) {
//this is a parent, check or uncheck all children
var isChecked = checkbox.is(":checked");
//add checked attribute in the DOM and add the class for prettyCheckable on all children
parent.find("input.childCheckBox:checkbox").prop("checked", isChecked).each(function() {
if (isChecked)
$(this).next("a").addClass('checked');
else
$(this).next("a").removeClass('checked');
});
} else {
//this is a child, check or uncheck the parent
var parentCheckbox = parent.find("input.parentCheckBox:checkbox");
var isChecked = !parent.find("input.childCheckBox:checkbox").get().some(function(item) {
return !$(item).is(":checked");
});
//add the checked attribute to the dom and add the class for prettyCheckable
parentCheckbox.prop("checked", isChecked);
if (isChecked)
parentCheckbox.next("a").addClass('checked');
else
parentCheckbox.next("a").removeClass('checked');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://qfuse.com/js/utils/prettyCheckable/prettyCheckable.js"></script>
<link href="http://arthurgouveia.com/prettyCheckable/js/prettyCheckable/dist/prettyCheckable.css" rel="stylesheet"/>
<fieldset>
<input type="checkbox" class="parentCheckBox" /> Africa
<div class="content">
<input type="checkbox" value="1" name="cntrs[]" class="childCheckBox" data-label="" /> Algeria<br />
<input type="checkbox" value="2" name="cntrs[]" class="childCheckBox" data-label="" /> Angola<br />
<input type="checkbox" value="3" name="cntrs[]" class="childCheckBox" data-label="" /> Benin<br />
</div>
</fieldset>
Please let me know how to open a pop-up on click of a radio button using JQuery.
Currently Im using a the following code for a radio button using Spring MVC and JSTL
<label class = "">
<form:radiobutton path = "" value = "" onchange= ""/>
<label class = "" style = ""> <spring:message code ="" /></label>
</label>
Many Thanks
I am assuming you mean a new window by pop-up?
The following code will open a new window with the URL when the status of the radio button changes. You can use click if you like...
$("#pop").change(function() {
window.open("http://www.google.com");
});
<input type="radio" id="pop" value="yes">
JSFiddle Example
I hope this will solve your problem.
onchange= "window.open("http://www.stackoverflow.com",width=200,height=100); "/>
EDIT1: Removing the hide class does the trick.
jQuery:
$(document).ready(function () {
$('input[type="radio"]').click(function () {
$('#r').removeClass("hide");
});
});
HTML:
<input type='radio'>SO
<div id="r" selectOption="#" class="modal hide" tabindex="-1" role="dialog" style=" background-color:#ccc; height: 100px;width: 350px"></div>
EDIT2:
If you check my html code, you will see an id for div named as "r" (unique selector) and class name "hide" prevent the div to be displayed. Therefore the div is hidden.
When the radio button is click, using removeClass we're removing the class "hide" this make the div visible.
Check this JSFiddle
Hope you understand.
you mean like this? CLICK HERE
HTML
<input type='radio' id='myRadio'>Radio button
JQuery
$(document).ready(function()
{
$('#myRadio').click(function()
{
alert("Clicked");
});
});
I'm trying to select dynamic ids when a user types something into the input fields. My app spits out the input fields in the following format:
<input id="student_1_first_name" />
<input id="student_1_last_name" />
<input id="student_2_first_name" />
<input id="student_2_last_name" />
<input id="student_3_first_name" />
<input id="student_3_last_name" />
etc.
For example, I tried doing this to select the end of the id string:
<script type="text/javascript">
$(document).ready(
function (){
$("input[id$=_first_name]").bind("keyup", run_some_function_here);
run_some_function_here();
$("input[id$=_last_name]").bind("keyup", run_some_function_here);
run_some_function_here();
}
);
</script>
When I do that, Jquery can't seem to select the input ids, so the functions don't run. Do you have any ideas on how I can select the ids correctly?
assign class to each input e.g <input id="student_1_first_name" class="input-class" />
then try this
$(function() {
$('input.input-class').each(function() {
var id = $(this).attr('id');
});
});
$("input[id$=_first_name]") looks like it should work.
Does this give them red borders?
$("input[id$=_first_name]").css({ border: '2px solid red' });
If it does, then the function is probably not being called properly. Are you using anonymous functions or passing a reference to an existing function?
Update
Does this work as intended?
$("input[id$=_first_name]")
.bind("keyup", function() { run_some_function_here(); });