I have a checkbox to add and remove a service. Currently it looks like this:
<div class="cknow" align="center" valign="top">Add/Remove to Checkout
<input type="checkbox" id="ckNow_<?php echo $i;?>" name="ckNow[<?php echo $i;?>]"></input>
</div>
I've also got a script that says this:
$('input[id^=ckNow_]').each(function(){
$(this).bind('click',function(){
if($(this).attr('checked'))
{.... does some stuff }
It's working great as a single checkbox but I'd like to the make the text 'Add/Remove' to be text links (without the input box of the checkbox) so that when Add is clicked it registers as CHECKED and when Remove is clicked, it registers as UNCHECKED.
How can I do this?
You can use the label element to assign text to a checkbox, then use CSS to hide the checkbox like so:
HTML
<label>Add/Remove
<input type="checkbox" id="ckNow_" name="ckNow" class="hideme">
</input>
</label>
CSS
.hideme {
display:none;
}
You can use:
$('[type=checkbox]').attr('checked', true); // or false
Note: of jQuery 1.7 you should use .prop('checked', ...) instead:
$('[type=checkbox]').prop('checked', true); // or false
Related
I have a set of radiobuttons called 'price'. When the '€' radio button is selected, I want to focus on a text input field and that text input field should be required.
When I click another option, the requried attribute should be removed.
Is this possible through Javascript or jQuery?
I found a jQuery snippet here, but it doesn't seem to be working. This is what I have now:
<input type="radio" name="price" value="value" id="value_radio" onclick="document.getElementById('value_input').focus()" required>
<label for="value_input">€</label>
<input type="text" name="price_value" id="value_input" pattern="\d+(,\d{1,2})?"
onclick="document.getElementById('value_radio').checked=true">
<script>
$('#value_radio').change(function () {
if($(this).is(':checked')) {
$('#value_input').attr('required');
} else {
$('#value_input').removeAttr('required');
}
});
</script>
<input type="radio" name="price" id="free" value="free">
<label for="free">Free</label>
JSFiddle: http://jsfiddle.net/fhfrzn1d/
According to this answer, you have to monitor the change on both radio inputs. So move your javascript script after the second radio.
Also there was missing a )
Fiddle updated: http://jsfiddle.net/fhfrzn1d/1/
$('input[name="price"]').change(function () {
if($("#value_radio").is(':checked')) {
$('#value_input').attr('required', true);
} else {
$('#value_input').removeAttr('required');
}
});
You have two (really three) mistakes in your code.
First. The syntax is invalid. You should fix the closing brace as #Hushme recommends in the comments.
First (2). Your usage of jsfiddle is invalid too. You should paste the code to the JavaScript section of the site and also enable jQuery library.
Second. $('#value_input').attr('required') is not creating an attribute; it's a getter. You should use the proper setter there:
$('#value_input').attr('required', true);
Third. The radiobutton change event is not firing when user deselects the radiobutton. So you should handle events on all the buttons:
$('input[name="price"]').change(function () { ... });
I've fixed your jsfiddle, see http://jsfiddle.net/fhfrzn1d/4/
I have horizontal jQuery checkbox. It should display some text when it is clicked and remove the text when it is clicked again and unchecked. However, when i first load the page and click on the box nothing happens. Then when i click it again to uncheck the text appears. It seems the opposite behaviour of what i expect is going on. Here is the code:
(I can solve this problem by simply inverting the boolean sign but i want to understand why this is happening).
<form>
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Select your type of Restaurant:</legend>
<input type="checkbox" name="checkbox-h-2a" id="checkbox-h-2a">
<label for="checkbox-h-2a" onclick="onfilter()">Vegetarian</label>
</fieldset>
</form>
<script>
function onfilter(){
if ($("#checkbox-h-2a").prop('checked')){
document.getElementById("hehe").innerHTML = "Yo there";
}
if (!($("#checkbox-h-2a").prop('checked'))){
document.getElementById("hehe").innerHTML = "";
}
}
</script>
You're already loading jQuery , so just use jQuery for everything - it is much easier , works better, really the only downside to jQUery is having to load it - and you're already doing that. So I would suggest using something like this:
$(function(){
$(document).on('click', '#checkbox-h-2a', function(){
if ( $(this).is(':checked') ) {
// Do stuff
}
else{
//Do stuff
}
});
});
Also, I hope you are actually closing your input element in your HTML , and that this is just a typo in your question
<input type="checkbox" name="checkbox-h-2a" id="checkbox-h-2a"
try:
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Select your type of Restaurant:</legend>
<label for="checkbox-h-2a" >Vegetarian
<input type="checkbox" name="checkbox-h-2a" id="checkbox-h-2a" />
</label>
</fieldset>
see how the label goes around the checkbox? also you can get rid on the inline function in HTML with the jQuery I provided
EDIT:
2 problems - one you selectd jQuery 1.6 , to you .on() you need a newer version , if you must use old jQuery let me know ,
the other problem is that all jQuery code must be wrapped in
$(document).ready(function(){
/// code here
});
or for short:
$(function(){
// code here
});
The problem is at the time of clicking on the label, the checkbox's checked has not been changed, so you have to toggle the logic (although it looks weird) or attach the handler to the onchange event of the checkbox input instead:
<!-- add onchange event handler -->
<input type="checkbox" name="checkbox-h-2a" id="checkbox-h-2a"
onchange="onfilter()"/>
<!-- and remove the click handler -->
<label for="checkbox-h-2a">Vegetarian</label>
Demo.
It involves how a label works, when clicking on the label, it looks for the attached input element via the for attribute and trying to change the appropriate property (checked for checkbox, radio, ...) or focusing the element (for textbox fields). So at the clicking time, it processes/calls your handler first. Hence the problem.
Note that this answer just fixes the issue, not trying to improve your code.
Still learning jQuery and will be thankful for any help.
I am currently using this jQuery Switchbutton https://github.com/olance/jQuery-switchButton
It uses a checkbox as an input type, and creates span tags with labels.
How would I say that I want on_label to have data-status="accept", and off_label data-status="decline"?
HTML:
<input type="checkbox" id="accept-offer"/>
JS:
$("input#accept-offer").switchButton({
on_label: "Accept",
off_label: "Ignore"
});
Thanks!!
You can try to do like this:
$('.switch-button-label.on').data('status','accept');
$('.switch-button-label.off').data('status','decline');
or:
$('.switch-button-label.on').attr('data-status','accept');
$('.switch-button-label.off').attr('data-status','decline');
This is a bit of a long question so please bear with me guys.
I needed to make a form submit automatically when a checkbox was ticked. So far I have the code below and it works perfectly. The form must submit when the check box is either checked or unchecked. There is some PHP that reads a database entry and shows the appropriate status (checked or unchecked) on load.
<form method="post" id="edituser" class="user-forms" action="--some php here--">
<input class="lesson" value="l101" name="flesson" type="checkbox" />
</form>
<script>
$('.lesson').change(function() {
$('.user-forms').submit();
});
</script>
However, when I introduce a fancy checkbox script which turns checkboxes into sliders it no longer works. The checkbox jQuery script is below:
<script src="'.get_bloginfo('stylesheet_directory').'/jquery/checkboxes.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$("input[type=checkbox]").tzCheckbox({labels:["Enable","Disable"]});
});
</script>
The contents of the checkboxes.js called to above is as follows:
(function($){
$.fn.tzCheckbox = function(options){
// Default On / Off labels:
options = $.extend({
labels : ['ON','OFF']
},options);
return this.each(function(){
var originalCheckBox = $(this),
labels = [];
// Checking for the data-on / data-off HTML5 data attributes:
if(originalCheckBox.data('on')){
labels[0] = originalCheckBox.data('on');
labels[1] = originalCheckBox.data('off');
}
else labels = options.labels;
// Creating the new checkbox markup:
var checkBox = $('<span>',{
className : 'tzCheckBox '+(this.checked?'checked':''),
html: '<span class="tzCBContent">'+labels[this.checked?0:1]+
'</span><span class="tzCBPart"></span>'
});
// Inserting the new checkbox, and hiding the original:
checkBox.insertAfter(originalCheckBox.hide());
checkBox.click(function(){
checkBox.toggleClass('checked');
var isChecked = checkBox.hasClass('checked');
// Synchronizing the original checkbox:
originalCheckBox.attr('checked',isChecked);
checkBox.find('.tzCBContent').html(labels[isChecked?0:1]);
});
// Listening for changes on the original and affecting the new one:
originalCheckBox.bind('change',function(){
checkBox.click();
});
});
};
})(jQuery);
There is also some CSS that accompanies this script but I am leaving it out as it is not important.
Finally, this is what the jQuery script does to the checkbox:
<input id="on_off_on" class="lesson" value="lesson11-1" name="forexadvanced[]" type="checkbox" style="display: none; ">
<span classname="tzCheckBox checked" class=""><span class="tzCBContent">Disable</span><span class="tzCBPart"></span></span>
When the checkboxes are changed into sliders the .change() function no longer detects the change in the checkboxes status.
How can I make the .change() function work or is their an alternative function I can use?
This plugin changes your checkboxes to span elements and hides the actual checkboxes themselves. Thus, when you click on them, nothing happens. Since span elements don't have onchange events, you can't bind change events to these.
However, span elements do have click events, meaning that you could instead bind a click event to the generated spans, using Firebug or Chrome Debugger to locate the correct element to bind to.
Your click-handler can then take the same action your change event would normally take if the plugin weren't being used.
Here is an example:
HTML (Source):
<!-- This is a checkbox BEFORE running the code that transforms the checkboxes
into sliders -->
<li>
<label for="pelda1">Opció 1:</label>
<input class="pelda" type="checkbox" id="pelda1" name="pelda1" />
</li>
HTML (Generated From Chrome Debugger):
NOTE: This is the generated HTML after running the JavaScript that converts checkboxes to sliders! You must bind your click event AFTER this code is generated.
<li>
<label for="pelda1">Option 1:</label>
<!-- The hidden checkbox -->
<input class="pelda" type="checkbox" id="pelda1" name="pelda1" style="display: none; " />
<!-- the "checked" class on the span gets changed when you toggle the slider
if it's there, then it's checked. This is what you're users are actually
changing.
-->
<span class="tzCheckBox checked">
<span class="tzCBContent">active</span>
<span class="tzCBPart"></span>
</span>
</li>
JavaScript:
NOTE: This must be bound AFTER converting the checkboxes to sliders. If you try it before, the HTML won't yet exist in the DOM!
$('.tzCheckBox').click(function() {
// alert the value of the hidden checkbox
alert( $('#pelda1').attr("checked") );
// submit your form here
});
Listen for change like this:
$('.lesson').bind("tzCheckboxChange",function() {
$('.user-forms').submit();
});
Modify the plugin by adding the line:
$(originalCheckBox).trigger("tzCheckboxChange");
after
checkBox.find('.tzCBContent').html(labels[isChecked?0:1]);
This way, anytime you use this plugin, you can listen for tzCheckboxChange instead of just change. I don't really know what's going on with the plugin, but seems kinda funky for it to be listening for a change event when it would only be fired through trigger (unless it doesn't hide the original checkbox).
What's a good pattern for adding additional data to an HTML element? For example, I'd like to link a checkbox to HTML I'd like to hide when the checkbox is unchecked. Like the for attribute of a label element, I want to specify the linkage in markup so I can write a simple, generic script to iterate through all checkboxes and hook up a jquery event handler to do the hiding/showing.
For example, in this HTML:
<input type="checkbox" id="showFoo" />
<div id="foo">
Some HTML here. Hide this when the checkbox is unchecked.
</div>
What's a good to let my script know that #showFoo is related to #foo? Ideally something that doesn't make my HTML non-validating or and doesn't require me to use a specific naming convention for IDs. Extra credit if it makes my script more efficient.
use a data-[key] attribute to identify what #showFoo should control
example jsfiddle
HTML:
<input type="checkbox" id="showFoo" data-toggles="foo" />
<div id="foo">
Some HTML here. Hide this when the checkbox is unchecked.
</div>
jQuery:
$('#showFoo').change(function() {
$('#' + $(this).data('toggles')).toggle();
});
This seems like a perfect case for data elements.
<input type="checkbox" id="showFoo" data-relateddiv="foo" />
Then in an event handler on the checkboxs:
$('#' + $(this).data("relateddiv")).show();
You can use the "rel" attribute
<input type="checkbox" id="showFoo" rel="foo" />
$('#showFoo').click(function(){
var element_id = $(this).attr('rel');
var element = $('#'+element_id);
if(element.is(':hidden')){
element.slideDown();
//element.show();
}
else{
element.slideUp();
//element.hide();
}
});
I use this currently
element.each(function(i, e) {
var checked = $(e).prop('checked'),
foo = */Relationship betweeen element and foo*/;
foo .toggleClass('invisibleClass', checked)
.toggleClass('visibleClass', !checked);
});
in case you have multiple foos and elements (you have to define the relationship between them first)
Run it on the event of your choice
Try below
if (checkboxIsChecked) {
foo.visibility:visible;
} else {
foo.visibility:hidden;
}