function javascript for both active label.hasClass - javascript

I have a big problem: I have basically two label
 
<label id="label1" class="btn btn-transparent grey-salsa btn-circle btn-sm label1 active" onclick="showSomething($(this));">
<input type="radio" name="options" class="toggle" id="Radio2" />Label1</label>
<label id="label2" class="btn btn-transparent grey-salsa btn-circle btn-sm label2" onclick="showSomething($(this));">
<input type="radio" name="options" class="toggle" id="Radio3" />Label2</label>
 
and the javascript function showSomething
I have to Show 3 graphics and the problem is that. I want to show one of the graph when two label are activated so the both label should be active
and so I do this:
function showSomething (labelJQ) {
    if (labelJQ.hasClass ('active'))
        return;
    else {
        if (labelJQ.hasClass('label1')) {
            if (labelJQ.hasClass('label2')) {
                $('#Chart1').hide();
                $('#Chart2').hide();
                $('#Chart1,2').show();
            }
}
}
}
but does not give me any results, does not know label.hasClass for both at the same time if I do one and then the other works perfectly but to me I do not need so - is there a way that can I do?

I have tried to interpret your question, so please provide further clarification if this does not do what you had hoped for, but...
I think your jQuery is a significant part of the issue here. I believe it is clearer if you assign the click change handler in a way similar to the following:
$('input[type=radio]').change(function() {
$('.chart').hide();
if (this.id == 'option1') {
$('#chart1').show();
} else if (this.id == 'option2') {
$('#chart2').show();
}
});
I have put together a demo from your original input here:
https://jsfiddle.net/g8wkwdo4/2/
Hope that helps!

Related

Attaching Click event to Bootstrap Toggle Radio Buttons

I have a boostrap toggle with the code below. It is visually working right
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio" name="options" id="showBuildQuantity" autocomplete="off" checked>Build Quantity
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="showNumberOfScreens" autocomplete="off" onclick="showBuildQuantity()">Number of Screens
</label>
</div>
Below it I have some code to handle click events:
$(document).ready(function () {
$('#showBuildQuantity').on('click', function () {
<code here>
});
$('#showNumberOfScreens').on('click', function () {
<code here>
});
});
The issue I am having is that the click event's are never run when I click the toggle buttons.
I have other buttons on the same page using the same kind of jQuery click event and they do not have an issue.
After some research I found I need to use change instead of click. So the code should look like this:
$('#showBuildQuantity').on('change', function () {
if (myChart != null) {
myChart.destroy();
}
setChart(getBuildQuantityData);
});
$('#showNumberOfScreens').on('change', function () {
if (myChart != null) {
myChart.destroy();
}
setChart(getNumScreensData);
});

Disable radio button in bootstrap 3?

How can I disable Bootstrap 3 radio buttons? If I start with the BS3 example and add disabled="disabled" to each input element, there are no changes in appearance or behavior:
<div class="container">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio" name="options" id="option1" autocomplete="off" checked disabled="disabled">Radio 1 (preselected)</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option2" autocomplete="off" disabled="disabled">Radio 2</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option3" autocomplete="off" disabled="disabled">Radio 3</label>
</div>
Demo: JSFiddle.
I guess this is because the disabled attribute is only applied to the now-invisible button and not the clickable text label, but I don't see anything in the BS3 docs about this.
Add disabled class to the label like this
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary disabled">
<input type="checkbox" autocomplete="off"> Checkbox 1 (pre-checked)
</label>
<label class="btn btn-primary active disabled">
<input type="checkbox" autocomplete="off"> Checkbox 2
</label>
<label class="btn btn-primary disabled">
<input type="checkbox" autocomplete="off"> Checkbox 3
</label>
</div>
Here is a demo
As mentioned by #giammin in the comments to the accepted answer, setting 'disabled' on the input elements doesn't work in 3.3.6 of bootstrap. (Current version at time of publication of this answer).
I was having exactly the same issue, and my solution was to use the CSS property "pointer events". This makes sure the element and children are never a target of click events. However this is not a foolproof solution - users can still tab in and use space to click the hidden elements on a desktop browser.
.disabled-group
{
pointer-events: none;
}
If you set this on your '.btn-group' element, you'll completely disable
<div class="btn-group disabled-group" data-toggle="buttons">
<label class="btn btn-primary disabled">
<input type="checkbox" autocomplete="off"> Checkbox 1 (pre-checked)
</label>
<label class="btn btn-primary disabled">
<input type="checkbox" autocomplete="off"> Checkbox 2
</label>
<label class="btn btn-primary disabled">
<input type="checkbox" autocomplete="off"> Checkbox 3
</label>
</div>
The '.disabled' class is then optional - use it for graying out and 'cursor: not-allowed;' property.
The discussion of the fix solution is at this source:
https://github.com/twbs/bootstrap/issues/16703
For radio button groups, add class disabled to the one you wish disabled.
Make sure you have something like this code:
$('.btn-group').on("click", ".disabled", function(event) {
event.preventDefault();
return false;
});
This will get all your .disabled classed buttons inside the button groups also disabled. This works also for radio type button groups.
You can use the above to disable an input[type='radio'] that is inside a label (bootstrap 3 style),
$("input[name='INPUT_RADIO_NAME']").prop("disabled", true);
$("input[name='INPUT_RADIO_NAME']").closest("div").css("pointer-events", "none");
The above to enable again,
$("input[name='INPUT_RADIO_NAME']").prop("disabled", false);
$("input[name='INPUT_RADIO_NAME']").closest("div").css("pointer-events", "auto");
You can also extend JQuery and create a dummy disable method (that you could upgrade with more functionality) like this,
(function ($) {
$.fn.disableMe = function () {
// Validate.
if ($.type(this) === "undefined")
return false;
// Disable only input elements.
if ($(this).is("input") || $(this).is("textarea")) {
// In case it is a radio inside a label.
if ($(this).is("[type='radio']") && $(this).parent().is("label.btn")) {
$("input[name='safeHtml']").closest("label").addClass("disabled");
$(this).closest("div").css("pointer-events", "none");
}
// General input disable.
$(this).prop("disabled", true);
}
};
$.fn.enableMe = function () {
// Validate.
if ($.type(this) === "undefined")
return false;
// Enable only input elements.
if ($(this).is("input") || $(this).is("textarea")) {
// In case it is a radio inside a label.
if ($(this).is("[type='radio']") && $(this).parent().is("label.btn")) {
$("input[name='safeHtml']").closest("label").removeClass("disabled");
$(this).closest("div").css("pointer-events", "auto");
}
// General input enable.
$(this).prop("disabled", false);
}
};
$.fn.toggleDisable = function () {
if ($.type(this) === "undefined")
return false;
// Toggle only input elements.
if ($(this).is("input") || $(this).is("textarea")) {
var isDisabled = $(this).is(":disabled");
// In case it is a radio inside a label.
if ($(this).is("[type='radio']") && $(this).parent().is("label.btn")) {
$("input[name='safeHtml']").closest("label").toggleClass("disabled");
$(this).closest("div").css("pointer-events", isDisabled ? "auto" : "none");
}
// General input enale.
$(this).prop("disabled", !isDisabled);
}
};
}(jQuery));
Usage example,
$("input[name='INPUT_RADIO_NAME']").disableMe();
$("input[name='INPUT_RADIO_NAME']").enableMe();
$("input[name='INPUT_RADIO_NAME']").toggleDisable();
In bootstrap if you want to disabled any input type or button, You just have to add bootstrap's .disabled class then your button become disabled.
Like this
<input type="radio" class="btn btn-primary disabled">Primary Button</button>

Highlight Specific Button Upon Page Load

I'm building a quiz app, and for a certain part of it I would like for some of the answers to be highlighted upon loading of the page.
These are the buttons:
<input type="hidden" name="correct_answer" value="<?php echo (isset($correct_answer)) ? $correct_answer : 'no corect answer';?>">
<button name="answer" value="A" class="btn btn-primary btn-lg">A</button>
<button name="answer" value="B" class="btn btn-primary btn-lg">B</button>
<button name="answer" value="C" class="btn btn-primary btn-lg">C</button>
<button name="answer" value="D" class="btn btn-primary btn-lg">D</button>
<button name="answer" value="E" class="btn btn-primary btn-lg">E</button>
You can see I'm loading a hidden element with the correct answer inside it.
All the back end works just fine, But I can't seem to figure out how to do this.
Is it possible to do this in native JS or is jQuery a must?
Also, how do I go about doing this? How do I make sure the CSS class is added to the right element?
EDIT:
This is the code I ended up using:
<script type="text/javascript">
document.getElementById("<?php echo $correct_answer;?>").style.backgroundColor = "green";
</script>
You can do this with vanila javascript using the backgroundColor,
So your js code would look like:
document.getElementById("answer1").style.backgroundColor = "red";
Working Fiddle
Please note that I have set Id for one element, however you can set for all elements and use that Id whose background is to be changed.
Since you're already rendering the page with PHP, why not just have it add a class to those elements you want highlighted.
<button name="answer" value="A" class="btn btn-primary btn-lg <?php if ($correct_answer === "A") { ?>highlight<?php } ?>">A</button>
Then style that class:
.highlight {
background-color: red;
}
Even if you were to use javascript to solve this, adding a class is far better than adding styles to an element. The class is more semantic and can be easily restyled without having to dig through your code.
Here's a pure JavaScript solution that will work with your existing HTML:
var correct= document.getElementsByName('correct_answer')[0].value;
var buttons= document.getElementsByName('answer');
for(var i = 0 ; i < buttons.length ; i++) {
if(buttons[i].value===correct) {
buttons[i].style.background= 'red';
break;
}
}
Fiddle at http://jsfiddle.net/qw7qhvnq/

Bind element if css class exists

I have a group of 3 bootstrap styled checkboxes like so:
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary btn-sm" data-bind=""><input type="checkbox">Checkbox 1</label>
<label class="btn btn-primary btn-sm"><input type="checkbox">Checkbox 2</label>
<label class="btn btn-primary btn-sm"><input type="checkbox">Checkbox 3</label>
</div>
At runtime if the first checkbox is pressed, when I inspect the element it gets an active css class appended to it:
<label class="btn btn-primary btn-sm active" >
How should my data-bind="" property look like if I want a function to execute when the input receives the active class? I would also want the opposite to happen as well. When the active class is no longer present, a function must also be called.
I can't use a click binding on the checkbox because it doesn't work because of bootstrap's way of "ticking" a checkbox.
Thank you (demo - http://jsfiddle.net/H7Js6/)
knockout is about having a viewmodel that represents your UI. Instead of a click binding, you can have checked binding and use the subscribe function:
<label class="btn btn-primary btn-sm" data-bind="">
<input type="checkbox" data-bind="checked: cb1" />Checkbox 1
</label>
And in the js:
var viewmodel = function () {
this.cb1 = ko.observable();
this.cb1.subscribe(function (newValue) {
//your code here gets called every time the checked status changes
// use newValue to know the new state
});
}
Demo
Update
Thank you for your fiddle, it always helps to have one.
Indeed, in this case the checked is not changed when the bootstrap css is loaded (if you remove the resource, you'll see it works).
To workaround it, you can have a custom binding handler that will check the presence of the css class for you:
ko.bindingHandlers.bootstrapCheckbox = {
init: function (element, valueAccessor, allBindingAccessor, viewModel,
bindingContext) {
if (ko.isObservable(allBindingAccessor().value)) {
$(element).change(function () {
//invert it because called before the class is added/removed :(
allBindingAccessor().value(!$(element).hasClass("active"));
});
}
allBindingAccessor().value($(element).hasClass("active")); //init value
}
}
Usage:
<label class="btn btn-primary btn-sm"
data-bind="bootstrapCheckbox: true, value: cb1">
<input type="checkbox" />Checkbox 1
</label>
Then keep the code from the first part of this answer (the subscribe).
Demo
Understanding there's already a good answer and trying to get how it was done I thought of using the already existing click binding for this, which may be another option (not saying it's better at all)
var vm = function(){
this.checkedButtons = ko.observableArray([]);
this.isActive = function(item, event){
if (!$(event.target).hasClass("active")){
this.checkedButtons.push(event.target);
}
else{
this.checkedButtons.pop();
}
};
};
ko.applyBindings(new vm());
Usage:
<div class="btn-group" data-toggle="buttons">
<label id="label1" class="btn btn-primary btn-sm" data-bind="click: isActive"><input id="input1" type="checkbox">Checkbox 1</label>
<label class="btn btn-primary btn-sm" data-bind="click: isActive"><input type="checkbox">Checkbox 2</label>
<label class="btn btn-primary btn-sm" data-bind="click: isActive"><input type="checkbox">Checkbox 3</label>
</div>
<div>How many buttons are clicked?
<span data-bind="text: checkedButtons().length "></span>
</div>
Fiddle
If you're using jquery, you can bind change event on the radio buttons themselves
$(".btn-group input[type=checkbox]").on("change",function(){
//you can do whatever you want here
});

Change an onclick value with javascript

I'm pretty new to JS and maybe this is a very banal questions but I still can't figure out what's wrong. I have this simple html code:
<span>1</span>
<input id="check1" type="radio" value="a1"/>
<span>2</span>
<input id="check2" type="radio" value="b2"/>
<span>3</span>
<input id="check3" type="radio" value="c3"/>
<span>4</span>
<input id="check4" type="radio" value="a4"/>
<span>5</span>
<input id="check5" type="radio" value="b5"/>
<input id="red" type="button" value="Go" onclick=""/>
What i would like to achieve is, based on the radio checked change the onclick property.
For example, if check1 and check2 are checked go to google.com, if check1 and check3 go to jsfiddle.net etcetera. So I wrote a simple Javascript:
window.onchange = function redirect(){
if (document.getElementById('check1').checked && document.getElementById('check2').checked) {
location.href='www.google.com';
// document.getElementById('red').onclick="www.google.com"
}
else if (document.getElementById('check1').checked && document.getElementById('check3').checked) {
location.href='www.jsfiddle.net';
// document.getElementById('red').onclick="window.open('www.jsfiddle.net')"
}
}
Here You can find a JS Fiddle.
What I thought to do was to set the onclick property like I did with an image, using getElementById and then setting his source, so I wrote document.getElementById('red').onclick="window.open('random page')" but for some reason that I can't understand it doesn't work.
Questions:
1) As you can see in my code i wrote a location.href='address' that obviously doen't wait for the user to click the button, so that's not a solution, how can I make this work?
2)Is there a way to make this piece of code more scalable? What I mean is, in the future if I want to add another radio, I would have to modify manually the code and insert another else if, I thought about something like:
var radio = document.getElementByName('radio') //not sure if this is the right getElement
for (var i=1; i<radio.lenght; i++){
if radio[i].checked{ //is this right?
for (var n=i+1; n<radio.lenght; n++){
if radio[n].checked{
document.getElementById('red').onclick="window.open('random page')"
}
}
}
Any suggestion to my code is welcome.
​
Try out this in JS Fiddle. It contains how you can listen the onclick event of a button and to get the checked value of a radio button.
HTML part:
<form action="">
<input type="radio" name="vehicle" value="Yes" id='yes'>Yes<br>
<input type="radio" name="vehicle" value="No" id='no'>No
</form>
<input id="red" type="button" value="let's go"/>
JS part:
document.getElementById('red').onclick = function() {
if (document.getElementById('yes').checked) {
alert('I have a Vehicle.');
} else if(document.getElementById('no').checked) {
alert('I don\'t have a Vehicle.');
} else {
alert('No answer.');
}
}
If you use radio buttons, and you want only one to be selectable to the user at a time you have to set the same name attribute to them.
You can also make use of the value property of radio buttons for storing the redirection URL.
Here is a more useful example for you.
HTML part:
<form action="">
<input type="radio" name='redirect' value='https://www.google.com/' id='google'>Google<br />
<input type="radio" name='redirect' value='http://www.jsfiddle.net/' id='jsFiddle'>JS Fiddle<br />
<input type="radio" name='redirect' value='https://www.facebook.com/' id='Facebook'>Facebook
</form>
<input id="red" type="button" value="let's go"/>
JS part:
document.getElementById('red').onclick = function() {
var options = document.getElementsByName('redirect'),
length = options.length,
i = 0;
for (i; i < length; i++) {
if (options[i].checked) {
window.open(options[i].value);
}
}
}
if (document.getElementById('check1').checked&&document.getElementById('check2').checked)
{
document.getElementById('red').onclick=function(){
window.location.href ='http://www.google.com';
};
}
This code binds the function to the onclick event of element with id='red'. So add a bunch of such conditions and change the onclick binding whenever any radio button is checked/unchecked.

Categories