Effective hide & show classes - javascript

I'm wondering if the code below can be simplified/normalized into something more efficiently. The code works as it should but im thinking it could be smaller. It basicly hides and shows classes when a radio option is selected.
$("input[type='radio']").click(function () {
if ($("#type1").is(":checked")) {
$("#showstoring").show("fast") &&
$("#showonderhoud").hide("fast") &&
$("#showspoed").hide("fast");
} else if ($('#type2').is(':checked')) {
$("#showstoring").hide("fast") &&
$("#showonderhoud").hide("fast") &&
$("#showspoed").show("fast");
} else if ($('#type0').is(':checked')) {
$("#showstoring").hide("fast") &&
$("#showonderhoud").show("fast") &&
$("#showspoed").hide("fast");
} else {
$("#showstoring").hide("fast") &&
$("#showonderhoud").hide("fast") &&
$("#showspoed").hide("fast");
}
});

Use data-* attributes to cross-reference buttons and elements by that data value:
var $content = $("[data-content]");
$("input[type='radio']").on("change", function() {
$content.hide(260).filter("[data-content='"+ this.dataset.show +"']").show(260);
});
[data-content]{display:none;} /* hide initially */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" data-show="1" name="r">A
<input type="radio" data-show="2" name="r">B
<input type="radio" data-show="3" name="r">C
<input type="radio" name="r" checked> Else?<br>
<div data-content="1">AAA</div>
<div data-content="2">BBB</div>
<div data-content="3">CCC</div>

Related

Checkbox selected tick function

I have 5 checkboxes, I want to tick 1 checkbox then the other 4 checkboxes will disable to tick, if I untick the 1 checkbox, the other 4 checkboxes will able to tick. Hope someone can guide me on how to solve it based on my below the coding:
<div class="form-group" id="taraf_keselamatan_fail">
<label for="cp1" class="control-label col-lg-4">Taraf Keselamatan Fail:</label>
<div class="col-lg-3">
<input type="checkbox" name="rahsia_besar" id="rahsia_besar" value="1"><b> Rahsia Besar</b></input>
<input type="checkbox" name="rahsia" id="rahsia" value="1"><b> Rahsia</b></input>
<input type="checkbox" name="sulit" id="sulit" value="1"><b> Sulit</b></input> <br>
<input type="checkbox" name="terhad" id="terhad" value="1"><b> Terhad</b></input>
<input type="checkbox" name="terbuka" id="terbuka" value="1"><b> Terbuka</b></input>
</div>
</div>
Now my output result like below the picture can tick all the checkboxes:
My expected result like below the sample picture, just can tick 1 box in the checkbox.
This is my try the coding in the javascript, but it cannot work:
<script>
var form = document.getElementById("checkForm");
form.onclick = delegateFormClick;
addChangeHandlers(form);
function addChangeHandlers(form)
{
for(var i=0;i<form.elements.length;i++)
{
var element = form.elements[i];
if(element.tagName === "INPUT" && element.type === "checkbox")
{
if(!element.onchange)
{
element.onchange = checkBoxChanged;
}
}
}
}
function delegateFormClick(evt)
{
var target;
if(!evt)
{
//Microsoft DOM
target = window.event.srcElement;
}else if(evt)
{
//w3c DOM
target = evt.target;
}
if(target.nodeType === 1 && target.tagName === "INPUT" && target.type === "checkbox")
{
if(target.checked)
{
disableCheckBoxes(target.id, document.getElementById("checkForm"));
}else if(!target.checked)
{
enableCheckBoxes(document.getElementById("checkForm"));
}
}
}
function checkBoxChanged()
{
if(this.checked)
{
disableCheckBoxes(this.id, document.getElementById("checkForm"));
}else if(!this.checked)
{
enableCheckBoxes(document.getElementById("checkForm"));
}
}
function disableCheckBoxes(id, form)
{
var blacklist = [];
if(id)
{
switch(id)
{
case "rahsia_besar":
blacklist = ["rahsia", "sulit","terhad","terbuka"];
break;
case "rahsia":
blacklist = ["rahsia_besar", "sulit","terhad","terbuka"];
break;
case "sulit":
blacklist = ["rahsia_besar", "rahsia","terhad","terbuka"];
break;
case "terhad":
blacklist = ["rahsia_besar", "rahsia","sulit","terbuka"];
break;
case "terbuka":
blacklist = ["rahsia_besar", "rahsia","sulit","terhad"];
break;
}
}else
{
throw new Error("id is needed to hard-wire input blacklist");
}
for(var i=0;i<blacklist.length;i++)
{
var element = document.getElementById(blacklist[i]);
if(element && element.nodeType === 1)
{
//check for element
if(element.tagName === "INPUT" && element.type === "checkbox" && !element.checked)
{
element.disabled = "disabled";
}
}else if(!element || element.nodeType !== 1)
{
throw new Error("input blacklist item does not exist or is not an element");
}
}
}
function enableCheckBoxes(form)
{
for(var i=0;i<form.elements.length;i++)
{
var element = form.elements[i];
if(element.tagName === "INPUT" && element.type === "checkbox" && !element.checked)
{
element.disabled = "";
}
}
}
</script>
The intended behavior does (almost ... see EDIT) not need any form of additional scripting for one gets such a behavior for free with any radio group ...
// scripting is just for proofing the behavior of a radio group/collection
function logCurrentlyCheckedFailValue(evt) {
if (evt.target.type === 'radio') {
console.log(`radio name: ${ evt.target.name }\nradio value: ${ evt.target.value }`);
}
}
function mainInit() {
document
.querySelector('#taraf_keselamatan_fail')
.addEventListener('click', logCurrentlyCheckedFailValue)
}
mainInit();
.as-console-wrapper { max-height: 60%!important; }
<form>
<fieldset class="form-group" id="taraf_keselamatan_fail">
<legend class="control-label col-lg-4">Taraf Keselamatan Fail:</legend>
<div class="col-lg-3">
<label>
<input type="radio" name="taraf_keselamatan_fail" value="rahsia_besar"/>
<b>Rahsia Besar</b>
</label>
<label>
<input type="radio" name="taraf_keselamatan_fail" value="rahsia"/>
<b>Rahsia</b>
</label>
<label>
<input type="radio" name="taraf_keselamatan_fail" value="sulit"/>
<b>Sulit</b>
</label>
<label>
<input type="radio" name="taraf_keselamatan_fail" value="terhad"/>
<b>Terhad</b>
</label>
<label>
<input type="radio" name="taraf_keselamatan_fail" value="terbuka"/>
<b>Terbuka</b>
</label>
</div>
</fieldset>
</form>
EDIT
I want to apologize to the OP because of me not reading the question carefully enough. The OP's use case indeed is distinct from what a radio group actually does offer.
Here we go ...
function setControlStateViaBoundConfig(elm) {
const config = this;
if (elm !== config.ignore) {
elm.checked = config.checked;
elm.disabled = config.disabled;
}
}
function toggleBehaviorOfFailureOptions(evt) {
const targetElement = evt.target;
if (targetElement.type === 'checkbox') {
const isDisableOthers = targetElement.checked;
evt.currentTarget // equals element with `id="taraf_keselamatan_fail"`
.querySelectorAll('[type="checkbox"]')
.forEach(setControlStateViaBoundConfig, {
ignore: targetElement,
checked: false,
disabled: isDisableOthers,
});
}
}
function mainInit() {
document
.querySelector('#taraf_keselamatan_fail')
.addEventListener('click', toggleBehaviorOfFailureOptions)
}
mainInit();
[type="checkbox"]:disabled + b { opacity: .4; }
.as-console-wrapper { max-height: 60%!important; }
<form>
<fieldset class="form-group" id="taraf_keselamatan_fail">
<legend class="control-label col-lg-4">Taraf Keselamatan Fail:</legend>
<div class="col-lg-3">
<label>
<input type="checkbox" name="rahsia_besar" value="1"/>
<b>Rahsia Besar</b>
</label>
<label>
<input type="checkbox" name="rahsia" value="1"/>
<b>Rahsia</b>
</label>
<label>
<input type="checkbox" name="sulit" value="1"/>
<b>Sulit</b>
</label>
<label>
<input type="checkbox" name="terhad" value="1"/>
<b>Terhad</b>
</label>
<label>
<input type="checkbox" name="terbuka" value="1"/>
<b>Terbuka</b>
</label>
</div>
</fieldset>
</form>
I created a Stackblitz from you code extract and it is working, could you please check if this is what you expected as solution ?

How to use two different bindingstrings and if one gets selected turn the other one false

So I am forced to use two different bidningstrings because of a tool we use to create a pdf. My goal here is when a user clicks a Yes or No button that the other corresponding bindingstring will be turned "Off" and the one clicked turned to "Yes" I created a Jquery way of doing this but that will become insane because I would have to do this like 100x Is there a way to do this inline with knockout I like I did with the knockout way of styling the opacity of the buttons?
<div class="row" style="margin-top: 80px">
<div class="col-xs-6 EntDisorderTrue" data-bind="style:{ 'opacity' : EntDisorderTrue()=='Off' ? '.5' : '' }" >
<label class="btn btn-success yesbtn">
<input type="radio" value="Yes" data-bind=" checked: EntDisorderTrue " />#Global.Yes
</label>
</div>
<div class="col-xs-6 EntDisorderFalse" data-bind="style:{ 'opacity' : EntDisorderFalse()=='Off' ? '.5' : '' }" >
<label class="btn btn-success nobtn">
<input type="radio" value="Yes" data-bind="checked: EntDisorderFalse" />#Global.No
</label>
</div>
</div>
Jquery way of switching the values
$(".EntDisorderFalse").click(function () {
if (self.EntDisorderFalse() == "") {
self.EntDisorderFalse("Yes")
self.EntDisorderTrue("Off")
} else if (self.EntDisorderFalse() == "Off") {
self.EntDisorderFalse("Yes")
self.EntDisorderTrue("Off")
}
});
$(".EntDisorderTrue").click(function () {
if (self.EntDisorderTrue() == "") {
self.EntDisorderTrue("Yes").css
self.EntDisorderFalse("Off")
} else if (self.EntDisorderTrue() == "Off") {
self.EntDisorderTrue("Yes")
self.EntDisorderFalse("Off")
}
});
I haven't use knockout in many years but can show you a generic approach.
Use a common class for the False/True elements and a data attribute for the entity name
<div class="col-xs-6 true" data-entity="EntDisorder"...
Then use [] notation to dynamically access the appropriate method
$(".true").click(function () {
var ent = $(this).data('entity'),
trueMethodName = ent + 'True',
falseMethodName = ent + 'False';
if (self[trueMethodName]() == "") {
self[trueMethodName]("Yes").css
self[falseMethodName]("Off")
} else if (self[trueMethodName]() == "Off") {
self[trueMethodName]("Yes")
self[falseMethodName]("Off")
}
});

Change the checkbox value using the radio button

If the user selects the category1 radio button, the value of the check boxes must be changed. And display them when the user checks the check box.
If the user selects the category 2 radio button, another set of values assign to the checkboxes.
If the user selects the category 3 radio button, another set of values must assign to the check boxes.
Here is the code:
$(document).ready(function() {
$('input[type="radio"]').click(function() {
if ($('input[id="radio1"]').prop("checked") == true) {
$('input[name="checkbox1"]').attr('value', 5000);
} else if ($('input[id="radio2"]').prop("checked") == true) {
$('input[name="checkbox1"]').attr('value', 10, 000);
} else if ($('input[id="radio3"]').prop("checked") == true) {
$('input[name="checkbox1"]').attr('value', 25, 000);
}
});
$('input[type="checkbox"]').click(function() {
$("#output").show();
if ($('input[name="checkbox1"]').prop("checked") == true) {
type1 = $('input[name="checkbox1"]').val()
$("#output").html(type1);
} else if ($('input[name="checkbox1"]').prop("checked") == false) {
$("#output").hide()
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="radio1">category1<br/>
<input type="radio" id="radio2">category2<br/>
<input type="radio" id="radio3">category3<br/>
<br/><br/>
<input type="checkbox" name="checkbox1">type1<br/>
<input type="checkbox" name="checkbox2">type2<br/>
<input type="checkbox" name="checkbox3">type3<br/>
<span id="output"></span>
You need to give your radio's the same name :
<input type="radio" id="radio1" name="category">category1<br/>
<input type="radio" id="radio2" name="category">category2<br/>
<input type="radio" id="radio3" name="category">category3<br/>
Then you should wrap the value by quotes in the attr() assignment :
if ($('input[id="radio1"]').prop("checked") == true) {
$('input[name="checkbox1"]').attr('value', '5000');
} else if ($('input[id="radio2"]').prop("checked") == true) {
$('input[name="checkbox1"]').attr('value', '10,000');
_________________________________________^______^
} else if ($('input[id="radio3"]').prop("checked") == true) {
$('input[name="checkbox1"]').attr('value', '25,000');
_________________________________________^______^
}
Code:
$(document).ready(function() {
$('input[type="radio"]').click(function() {
if ($('input[id="radio1"]').prop("checked") == true) {
$('input[name="checkbox1"]').attr('value', '5000');
} else if ($('input[id="radio2"]').prop("checked") == true) {
$('input[name="checkbox1"]').attr('value', '10,000');
} else if ($('input[id="radio3"]').prop("checked") == true) {
$('input[name="checkbox1"]').attr('value', '25,000');
}
});
$('input[type="checkbox"]').click(function() {
$("#output").show();
if ($('input[name="checkbox1"]').prop("checked") == true) {
type1 = $('input[name="checkbox1"]').val()
$("#output").html(type1);
} else if ($('input[name="checkbox1"]').prop("checked") == false) {
$("#output").hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="radio1" name="category">category1<br/>
<input type="radio" id="radio2" name="category">category2<br/>
<input type="radio" id="radio3" name="category">category3<br/>
<br/><br/>
<input type="checkbox" name="checkbox1">type1<br/>
<input type="checkbox" name="checkbox2">type2<br />
<input type="checkbox" name="checkbox3">type3<br/>
<span id="output"></span>

Use JQuery To Change Seperate Radio Button State and Run Associated Function

The goal of this code is that when you change the Section Bar radio input to yes two things happen.
JS Fiddle Link
The .bar div is shown
The Section Foo radio button is changed to the No value and the .foo div is hidden
Additionally, would it be possible to have the reverse happen when the Section Bar is changed back to no. The .bar div gets hidden, the .foo section is shown, and the Section Foo button is set back to yes value.
Basically, the state of the second radio button effects the first button and runs the function it would if it was changed, but the first button does not effect the second when it is changed.
<form>
<label>Section Foo</label>
<input class="toggle" data-target=".foo" type="radio" name="enableFoo" value="yes" checked >Yes
<input class="toggle" data-target=".foo" type="radio" name="enableFoo" value="no">No
</form>
<form>
<label>Section Bar</label>
<input class="enable" data-target=".bar" type="radio" name="enableBar" value="yes">Yes
<input class="enable" data-target=".bar" type="radio" name="enableBar" value="no" checked>No
</form>
<div class="foo">Foo</div>
<div class="bar">Bar</div>
div {
width: 500px;
height: 200px;
}
.foo {
display: block;
background: red;
}
.bar {
display: none;
background: black;
}
$('.toggle').change(function () {
var target = $(this).data("target"),
element = $(this),
name = element.val(),
is_checked = element.prop('checked')
if (name == 'yes') {
$(target).slideDown(300);
} else {
$(target).slideUp(300);
}
});
$('.enable').change(function () {
var target = $(this).data("target"),
element = $(this),
name = element.val(),
is_checked = element.prop('checked')
if (name == 'yes') {
$(target).slideDown(300);
$( ".toggle" ).prop("checked", true) // this changes the .toggle check, but does not run the function, also I'm not sure if it will always set it to the value of no.
} else {
$(target).slideUp(300);
$( ".toggle" ).prop("checked", true)
}
});
All you need to do is change the value of the other radio group to no when this one is yes and then trigger its change:
$('.toggle').change(function () {
var foov = $(".toggle:checked").val();
var target = $(this).data("target");
if (foov == 'yes') {
$(target).slideDown(300);
$('.enable[value="no"]').prop('checked', true).trigger('change');
} else {
$(target).slideUp(300);
}
});
$('.enable').change(function () {
var target = $(this).data("target"),
element = $(this),
name = element.val(),
is_checked = element.prop('checked')
if (name == 'yes') {
$(target).slideDown(300);
$('.toggle[value="no"]').prop('checked', true).trigger('change');
} else {
$(target).slideUp(300);
}
});
jsfiddle DEMO
If I understand correctly. Then something like this should do the trick.
jQuery(function($){
var fooRadio = $(':input[name=enableFoo]'),
barRadio = $(':input[name=enableBar]');
function hideShow(el, show) {
el = $(el);
if (show) {
el.slideDown(300);
} else {
el.slideUp(300);
}
}
// bindings
fooRadio.on('change', function(){
var it = $(this),
target = it.data('target');
hideShow(target, it.val()==='yes');
});
barRadio.on('change', function(){
var it = $(this),
target = it.data('target'),
active = it.val()==='yes';
hideShow(target, active);
if (active) {
fooRadio.filter('[value=no]').click();
}
});
});
Here's a fiddle if it http://jsfiddle.net/ccn8f84r/1/
Here following is what you want
$('input[type=radio][name=enableFoo]').change(function() {
var target = $(this).data("target")
if ($(".toggle:radio:checked").val() == 'yes') {
$(target).slideDown(300);
$( ".enable" ).prop("checked", true).trigger('change')
} else {
$(target).slideUp(300);
}
});
$('input[type=radio][name=enableBar]').change(function() {
var target = $(this).data("target")
// alert($(".enable:radio:checked").val())
if ($(".enable:radio:checked").val() == 'yes') {
$(target).slideDown(300);
$( ".toggle" ).prop("checked", true).trigger('change')
} else {
$(target).slideUp(300);
}
});
div {
width: 500px;
height: 200px;
}
.foo {
display: block;
background: red;
}
.bar {
display: none;
background: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label>Section Foo</label>
<input class="toggle" data-target=".foo" type="radio" name="enableFoo" value="yes" checked >Yes
<input class="toggle" data-target=".foo" type="radio" name="enableFoo" value="no">No
</form>
<form>
<label>Section Bar</label>
<input class="enable" data-target=".bar" type="radio" name="enableBar" value="yes">Yes
<input class="enable" data-target=".bar" type="radio" name="enableBar" value="no" checked>No
</form>
<div class="foo">Foo</div>
<div class="bar">Bar</div>
Check Fiddle
Little more simplified using if...elseif and i gave id's to your input type=radio
Working : Demo
HTML : Added id's
<form>
<label>Section Foo</label>
<input id="1" class="toggle" data-target=".foo" type="radio" name="enableFoo" value="yes" />Yes
<input id="2" class="toggle" data-target=".foo" type="radio" name="enableFoo" value="no" />No</form>
<form>
<label>Section Bar</label>
<input id="3" class="enable" data-target=".bar" type="radio" name="enableBar" value="yes" />Yes
<input id ="4" class="enable" data-target=".bar" type="radio" name="enableBar" value="no" />No</form>
<div class="foo">Foo</div>
<div class="bar">Bar</div>
CSS : No Change
JS
$("input[type=radio]").click(function () {
var curClass = this.className;
var curValue = this.value;
if (curClass == "toggle" && curValue == "yes") {
document.getElementById('4').checked = true;
$(".bar").slideUp(300);
$(".foo").slideDown(300);
}
else if (curClass == "toggle" && curValue == "no") {
document.getElementById('3').checked = true;
$(".foo").slideUp(300);
$(".bar").slideDown(300);
}
else if (curClass == "enable" && curValue == "yes") {
document.getElementById('2').checked = true;
$(".foo").slideUp(300);
$(".bar").slideDown(300);
}
else if (curClass == "enable" && curValue == "no") {
document.getElementById('1').checked = true;
$(".bar").slideUp(300);
$(".foo").slideDown(300);
}
});

Checkbox and text field, if one is selected or has value require other(s)

I have two checkboxes in a group and one text input. If one (or both) of the checkboxes are selected I need to have the text input be required, as well as if the text input has text I need at least one of the checkboxes to be required. Another problem I'm having it that it's using a custom templating engine (PHP backend) and is a pain to configure and get the attributes correct, another issue is it's all referenced by the name attribute and this is why I'm using a HTML5 data-group for the checkbox options which I think it working.
Any help in getting this to work, combining functions (if this makes it easier/simpler).
BTW it's running 1.3.2 jQuery
Example: (not working)
http://jsfiddle.net/NYn8e/1/
Any suggestions?
JS:
function checkboxSelectedRequiredAdditionalFields(elem) {
var passedElement = $('input:checkbox[name=' + elem + ']');
passedElement.click(function() {
$('input[name=number]').attr('required', true).append('<span class="required">*</span>');
alert('text is required now?');
});
}
function numberEnteredRequiredAdditionalFields(elem) {
var passedElement = $('input[name=' + elem + ']');
if (passedElement.val().length > 0) {
var boxes = $('input[data-group=cbOptions]').click(function() {
boxes.not(this).attr('required', false);
alert('checkbox is selected so other checkbox is not required');
});
$('input[data-group=cbOptions]').each(function() {
$(this).attr('required', true).next().append('<span class="required">*</span>');
alert('checkbox is required now?');
});
}
}
HTML
<form>
<label>
<input type="checkbox" name="checkbox1" value="t" onclick="checkboxSelectedRequiredAdditionalFields('checkbox1');" data-group="cbOptions">
Checkbox Option 1
</label>
<label>
<input type="checkbox" name="checkbox2" value="t" onclick="checkboxSelectedRequiredAdditionalFields('checkbox2');" data-group="cbOptions">
Checkbox Option 2
</label>
Number <b>
<input type="text" name="number" value="" size="" maxlength="9" onclick="numberEnteredRequiredAdditionalFields('number');">
</b>
</form>
You should separate the JavaScript from the HTML. Fiddle: http://jsfiddle.net/NYn8e/6/. If possible, remove <b> from the HTML source, and extend the style sheet with the right CSS property: font-weight: bold;.
<form>
<label>
<input type="checkbox" name="checkbox1" value="t" data-required="checkbox">
Checkbox Option 1
</label>
<label>
<input type="checkbox" name="checkbox2" value="t" data-required="checkbox">
Checkbox Option 2
</label>
Number <b>
<input type="text" name="number" value="" size="" maxlength="9" data-required="number">
</b>
</form>
JavaScript:
function required(){
//Any checked checkbox? checked == 0 = no, otherwise: yes
var checked = $('input[data-required=checkbox]:checked').length;
var $checkboxes = $('input[data-required=checkbox]');
var $num = $('input[name=number]');
var length = $num.val().length;
//Remove previously added span, if existent.
$num.next('span.required').remove();
$checkboxes.next('span.required').remove();
if(!length && checked){
$num.after('<span class="required">*</span>');
alert("Number required!");
} else if(length && !checked){
$checkboxes.after('<span class="required">*</span>');
alert("Check at least one checkbox.");
}
}
$(document).ready(function(){
$("[data-required]").change(required);
});
=) Would this one help you?
<form id='myForm'>
<input type='checkbox' name='checkbox1' value='t' id='checkbox1' onchange='alertUser()' />
<input type='checkbox' name='checkbox2' value='t' id='checkbox2' onchange='alertUser()' />
<input type='text' name='number' id='number' onchange='alertUser()'/>
</form>
<script type='text/javascrip>
function alertUser() {
var checked1 = $('#checkbox1').attr('checked');
var checked2 = $('#checkbox2').attr('checked');
var number = $('#number').val();
if ((checked1 == true || checked2 == true) && number == '') {
alert('Number is required!');
} else if (number != '' && (checked1 != true && checked2 != true)) {
alert('One of the checkbox need to be checked!');
}
});
</script>
This should hopefully give you an idea on how to accomplish the task. http://jsfiddle.net/NYn8e/8/
var $textbox = $('input[name=number]').hide();
$('input[type=checkbox]').change(function() {
var $this = $(this); //store jquery object
//get the other checkbox
var $other= ($this.attr('name') === 'checkbox1') ? $('input[name=checkbox2]') : $('input[name=checkbox1]');
if (!$other.is(':checked') && !$this.is(':checked')) {
$textbox.val('').hide();
} else{
$textbox.show();
}
});

Categories

Resources