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.
Related
I have the following Material Design Lite switch in my HTML and is looking for some javascript help.
<label class="mdl-switch mdl-js-switch mdl-js-ripple-effect" for="switch-1">
<input type="checkbox" id="switch-1" class="mdl-switch__input" checked />
<span class="mdl-switch__label">USEREMAIL Subscribed</span>
</label>
Upon clicking the switch, I'd like to add:
Toggle functionality to update the checked to unchecked - like on and off switch, but is looking for JavaScript help here.
I would like to really have values of "subscribed" and "unsubscribed" as text that is displayed next to it as shown (but hardcoded in the html). Is this feasible to change dynamically?
Thanks for your time. I did find this as a reference, but it was using CheckBox.
If you refer to the mdl's source code, you will find that the check and uncheck functions are bound with label tag.
You can specify an id to label like below:
<label id="check" class="mdl-switch mdl-js-switch mdl-js-ripple-effect" for="switch-1">
<input type="checkbox" id="switch-1" class="mdl-switch__input"/>
<span class="mdl-switch__label">Subscribed</span>
</label>
<input type="button" value="test switch" id="btn"/>
MDL natively supports on/off status switch on button click. You can also control the status by another button.
$("#btn").click(function() {
if($('#check').is('.is-checked')) {
$('#check')[0].MaterialSwitch.off();
}
else {
$('#check')[0].MaterialSwitch.on();
}
});
To update the switch label dynamically, the code can be put like below. Bind the input's change event on page load and update label text if the on/off status changes.
//toggle label
$('#check input').change(function(){
if($(this).is(':checked'))
$(this).next().text("Unsubscribed");
else
$(this).next().text("Subscribed");
});
Here is the jsFiddle code. The answer comes a bit late for you but I hope it still helps.
Referring to the code in above question:
var myCheckbox = document.getElementById('switch-1');
myCheckbox.parentElement.MaterialSwitch.off();
…
myCheckbox.parentElement.MaterialSwitch.on();
Below code maybe solve your problem:
var isChecked = $('#switch-1').is(':checked');
if(isChecked) {
alert("subscribed");
} else {
alert("not subscribed");
}
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 am using the following code to route click events on an img tag to an input radio below it. The code works perfectly on Chrome and other browsers, but on IE (specifically IE 11) I must double click to get the radio selected instead of just single click to get the radio input selected. Can someone please tell me what I am doing wrong, missing here? Thanks
<script type="text/javascript">
$(document).ready(function() {
$('#Img1').click(function() {
$('#radio1').trigger('click');
});
});
</script>
<div class="imagesPrev col four center">
<label class="label_radio images" for="radio1">
<div class="labelText">
<img id="Img1"src="image1.gif" alt="Image 1" />
<input type="radio" id="radio1" name="radio1" value="image1"/>
</div>
<div style="height:10px;"></div>
Image Title <br/>
</label>
</div>
Notes:
- I also noticed that I don't have to double click as normal double click, but it has to be two clicks. Meaning one click then I can wait for like 10-15 seconds then do the 2nd click to get the click event routed to the radio input.
http://jsfiddle.net/89wTk/
You should use .prop(); when dealing with checkbox/radio inputs.
$(document).ready(function() {
$('#Img1').click(function() {
var checkBox = $("#radio1");
checkBox.prop("checked", !checkBox.prop("checked"));
});
});
Have you tried using a label tag with a for attribute for this feature instead, this could solve your problem and be more browser compatible.
<label for="radio1"><img id="Img1"src="image1.gif" alt="Image 1" /></label>
<input type="radio" id="radio1" name="radio1" value="image1"/>
I can understand if this doesn't achieve what you need, but using this method should work using HTML markup instead of jQuery
relatively horrible jsfiddle demoing this:
http://jsfiddle.net/andyface/d25KS/
I remember that some version of IE don't support clicking objects other than links or buttons :(
Perhaps try using:
$("#radio1").checked(true);
or
$("#radio1").selected(true);
as a work around
Just simple, you don't have to use any Jquery for this, just keep everything inside the label:
<label for="radio_btn">
<img id="img"src="image1.gif" alt="Image here" />
<input type="radio" id="radio_btn" name="radio1" value="image1"/>
</label>
Working here: http://jsfiddle.net/fals/3phf4/
Your code example works fine in IE11 (desktop and metro). Is it possible that there is another click event on the page that is capturing and preventing the click event on the image? Maybe something is causing the page to lose focus (first click gets window focus second clicks the image)? Try putting an alert in the click function to see if the click is getting registered. If that's not the issue, try running the body of the function in the console to see if that is the issue. You might try other ways to trigger the event, as suggested by others. Or try the jQuery .triggerHandler("click") method.
I think your problem may be with your markup. You have your image and click events inside a label.
According to w3schools:
"...if the user clicks on the text within the element, it toggles the control."
http://www.w3schools.com/tags/tag_label.asp
That toggle is perhaps messing with your javascript. Try moving the markup outside of the label and see if that helps.
That's an easy one :).
The #img1 is encapsulated inside the
<label class="label_radio images" for="radio1">
So, without the jQuery part it's already working. Now when having the jQuery part, a single click will become a double click:
1) 'for' element of label_radio
2) the trigger in jQuery part
So, for x-browser, you should not wrap the img inside the label.
Or try to cancel the event in $('#Img1').click(function(event) { ...
You have both your img and radio wrapped in label.
HTML's default behavior is that click on label triggers radio/checkbox inside.
There are two ways you can solve your problem:
Remove javascript function altogether.
If there's additional reason for javascript, change your html markup, and move radio outside of the label. Also remove for attribute, cause it triggers radio selection. Something like this:
<div class="imagesPrev col four center">
<label class="label_radio images">
<div class="labelText">
<img id="Img1"src="image1.gif" alt="Image 1" />
</div>
</label>
<input type="radio" id="radio1" name="radio1" value="image1"/>
<div style="height:10px;"></div>
Image Title
</div>
<script type="text/javascript">
$(document).on('click','.Img1',function()
{
var checkBox = $(".radio1");
checkBox.prop("checked", !checkBox.prop("checked"));
});
</script>
<img class="Img1" src="image1.gif" alt="Image 1" />
<input type="radio" class="radio1" name="radio1" value="image1"/>
I am facing the same issue and its very weird .... the workaround that is working for me is that instead of using the trigger function .. put the code which is executed in the trigger click event in a javascript function and call that function instead of trigger event ... example is given below.
For this example i will use an alert in case of a click on the element with id radio1.
Event definition
$('#radio1').on('click',function () {
alert("Hi");
})
So Instead of using $('#radio1').trigger('click'); we can put the alert in a javascript function and call the javascript function where ever i am calling the trigger click event.
Javascript function
function triggerClick(){
alert("Hi")
}
and just call this function(triggerClick()) where ever you are using $('#radio1').trigger('click');
Please let me know if this is helpfull
Try to use .click() instead of .trigger('click'):
<script>
$(document).ready(function() {
$('#Img1').click(function() {
$('#radio1').click();
});
});
</script>
it should work, see here for more info
I want to disable an input Box AND a button when a checkbox is clicked .
My markup :
<h4>Random or Not </h4>
<!-- Use Random Image -->
<label><input name="o99_aufu_options[o99_aufu_random]" id="o99_aufu_options[o99_aufu_random]" value="1" checked="checked" type="checkbox">Use Random Image ? <em></em></label><br>
<!-- If the above not checked - needs to be enabled -->
Upload Image <label for="upload_image"> <input id="upload_image" size="36" name="o99_aufu_options[o99_aufu_upload_image]" value="" type="text"> <input id="upload_image_button" value="Choose Image or upload" type="button"> </label>
jQuery :
if (jQuery('#o99_aufu_options[o99_aufu_random]').is(':checked')) {
jQuery('#upload_image :input').attr('disabled', true);
} else {
jQuery('#upload_image_button,#upload_image :input').removeAttr('disabled');
}
well - obviously, if i am asking here - it is not working :-)
Fiddle :
http://jsfiddle.net/obmerk99/6jFMf/3/
Also as a bonus question - is it possible to do that only with the NAME of the input, omitting the ID from the markup ?
UPDATE I - working solution :
http://jsfiddle.net/obmerk99/6jFMf/20/
bonus question - is it possible to do that only with the NAME of the input, omitting the ID from the markup ?
You can use any attribute in a jQuery selector, including name:
$('[name="foo"])
Since your names have brackets, you'll probably have to escape them:
$('[name="o99_aufu_options\[o99_aufu_random\]"]')
You can also qualify them to specific elements if you want, or combine them with other selectors:
$('input.someClass[name="o99_aufu_options\[o99_aufu_random\]"]')
As for your actual question, my first guess ... is wrong is that your problem is whitespace; have you tried:
#upload_image:input
instead?
My second guess is also wrong that the problem is:
.prop('disabled', true);
Have you tried:
.prop('disabled', 'disabled');
?
Ok, I actually looked at your fiddle, and there were a few things wrong; here's a working example, let me know if you have questions, but hopefully it's self-explanatory:
jQuery(function() {
jQuery('input[name="o99_aufu_options\[o99_aufu_random\]"]').click(function(){
var isChecked = jQuery(this).is(':checked') ;
jQuery('#upload_image:input').prop('disabled', isChecked? 'disabled' : null);
})
});
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).