JavaScript to Toggle Material Design Lite Switch - javascript

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");
}

Related

Add required attribute when radio is checked

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/

Unexpected response for checkbox jQuery

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.

JQuery .trigger click event not working under IE

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

JS - jQuery - Enable Disable form fields with checkbox

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);
})
});

Using javascript onClick to style currently selected radio button

I am trying to add the class "current" to whatever radio option is currently selected. I can use
onClick="document.getElementById('volunteering').class += 'current';"
However, this will indeed add the class, but it sticks when you select another radio button (because it's on each button). Any thoughts on how to implement it across all radio buttons?
Here is the code I am using:
<form>
<ul>
<input type="radio" name="category" id="volunteering" value="volunteering"><li class="conversation">
<a href="#" onClick="document.getElementById('volunteering').checked = true;" >Volunteering</a>
</li>
<input type="radio" name="category" value="cityproblems" id="cityproblems"><li class="conversation">
<a href="#" onClick="document.getElementById('cityproblems').checked = true;" >City Problems</a>
</li>
<input type="radio" name="category" value="safety" id="safety"><li class="conversation">
Safety
</li>
</form>
You need to first remove that class from all radio buttons, then add it back to the clicked one. Define a function that does this by receiving the id as a parameter, and bind that to the onclick.
function selectRadioClass(radioId) {
// Note - there are more clever ways, like arrays and loops
// for this, but if it's only 3, this is fine
document.getElementById('volunteering').className = '';
document.getElementById('cityproblems').className = '';
document.getElementById('safety').className = '';
// Then add it back to the node passed in by id
document.getElementById(radioId).className = 'current';
// And check the button
document.getElementById(radioId).checked = true;
}
Then bind each radio button's onclick using:
Safety
There are 2 solutions:
Use CSS3 :checked selector
form input:checked {
/* your style rules here. */
/* No more scripting needed. */
}
http://www.quirksmode.org/css/enabled.html
Use A global function for this purpose.
// check Michael's solution.
Use CSS pseudo selectors and forget the JavaScript. There is one for element:checked.
http://css-tricks.com/pseudo-class-selectors/

Categories

Resources