toggle textbox if checkbox is true for CMS - javascript

I try to make something like that work, implementing it in my CMS:
Fixed CMS part:
<div class="RadioList" id="radioListId">
<div class="TxtLbl" id="textLblId"> Question </div>
<span id="spanId">
<input value="yes"></input>
<input value="no"></input>
</span>
</div>
<div class="TxtBox" id="txtBoxId">
some text
</div>
own JS part someting like:
function EnableTextbox(radioListId,spanId)
{
if(document.getElementById(radioListId).inputValue == "yes")
document.getElementById(textBoxId).visibility = visible;
else
document.getElementById(textBoxId).visibility = hidden;
}
But I am not quite sure how to put it correctly - my understanding of js is not really high enough.
Any helping comments are highly appreciated!

try this
HTML
<div class="RadioList" id="radioListId">
<div class="TxtLbl" id="textLblId">Question</div> <span id="spanId">
<input type="radio" value="yes" name="showhide"> Show</input>
<input type="radio" value="no" name="showhide"> Hide</input>
</span>
</div>
<div class="TxtBox" id="txtBoxId">some text</div>
Script
$(document).ready(function () {
$("#txtBoxId").hide();
$("input[name='showhide']").on("click", function () {
var option = $(this).attr('value');
if (option == "yes") {
$("#txtBoxId").show();
} else {
$("#txtBoxId").hide();
}
});
});
Fiddle Sample

There are a few changes you need to make:
the inputs need to have a type="radio" to indicate that those are radio buttons.
the inputs need to have a common name="whatever" to indicate that both belong to same group and cannot be checked simultaneously.
the inputs need to have a text between the opening/closing tags, this text appears next to the radio button.
you need to call the javascript function when you click/change the buttons, and inside you check which radio was selected.
you pass the radio button reference into the javascript function by writing this as the function variable.
inside the function you retrieve the radio button reference, you can name the variable whatever you want.
you are using visible and hidden as variables, but those are not defined. it supposed to be either a string, or a boolean value. i prefer to use css for that purpose.
here is an Example Fiddle
HTML:
<div class="RadioList" id="radioListId">
<div class="TxtLbl" id="textLblId">Question</div> <span id="spanId">
<input type="radio" value="yes" onclick="EnableTextbox(this);" name="Answer">Yes</input>
<input type="radio" value="no" onclick="EnableTextbox(this);" name="Answer">No</input>
</span>
</div>
<div class="TxtBox" id="txtBoxId">some text</div>
JS:
function EnableTextbox(radioList) {
if (radioList.value == "yes") document.getElementById("txtBoxId").style.visibility = "visible";
else document.getElementById("txtBoxId").style.visibility = "hidden";
}

Since onclick="" is outdated you should use the element.addEventListener();!
Here is an Example in Fiddle!
HTML:
<div class="RadioList" id="radioListId">
<div class="TxtLbl" id="textLblId"> Question </div>
<span id="spanId">
<label><input type="radio" name="answer" id="yes" value="yes" />Yes</label>
<label><input type="radio" name="answer" id="no" value="no"/>No</label>
</span>
</div>
<div class="TxtBox" id="txtBoxId">
some text
</div>
JS:
var yes = document.getElementById('yes');
var no_ = document.getElementById('no');
if (yes.addEventListener) {
yes.addEventListener ("RadioStateChange", OnChange, false);
no_.addEventListener ("RadioStateChange", OnChange, false);
}
function OnChange(){
if (yes.checked) {
document.getElementById('txtBoxId').style.display = 'inline';
}
else {
document.getElementById('txtBoxId').style.display = 'none';
}
}
Greetings from Vienna

In jQuery
<span id="spanId">
<input type="radio" name="radiobutton" value="yes" />
<input type="radio" name="radiobutton" value="no" />
</span>
$('#spanId input:radio[name="radiobutton"]').change(function(){
if($(this).val() === 'yes'){
$('#txtBoxId').show();
} else {
$('#txtBoxId').hide();
}
});
Explanation
$('#txtBoxId').show() = display:block;
$('#txtBoxId').hide() = display:none;
If you want visibility instead.
$('#txtBoxId').css('visibility','visible');
$('#txtBoxId').css('visibility','hidden');
Let me know if you have any question.

Related

How to use Javascript/JQuery to verify that at least two fields in a checkbox are selected?

I am trying to create Javascript verification code for a form, so that each section of the form is verified after hitting "submit". I am having trouble writing the code so that the checkbox section of the form verifies that two or more boxes have been selected. I tried to start simple by writing the code so that a div, errorcheckbox, would display a message if no checkbox is selected at all. However it does not work. Here is the HTML and script for the code pertaining to the checkbox:
HTML:
<form action="#" method="POST">
<div class="contactForm">
<label for="checkbox" id="checkbox" name="checkbox">Contactee Type: </label><br>
<div id="errorcheckbox" class="error"></div>
<input type="checkbox" name="type1" value="Individual">Individual<br>
<input type="checkbox" name="type2" value="Catering">Business:Catering<br>
<input type="checkbox" name="type3" value="Partner">Business:Partner<br>
</div>
<div class="button"><input type="button" name="submit" id="submit" value="Submit"></div>
</form>
and the Javascript:
$("document").ready(function(){
console.log("Loaded");
$("#submit").click(function(){
checkContactee();
});
$("#checkbox").change(function(){
console.log("Something in contactee changed");
checkContactee();
});
function checkContactee(){
if (document.getElementById("checkbox").checked == false){
$("#errorcheckbox").html("<p>You missed this field</p>");
$("#errorcheckbox").addClass("showerror");
}
else{
$("#errorregarding").html("");
$("#errorregarding").removeClass("showerror");
}
}
Right now, the code does nothing. The errorcheckbox div doesn't appear, and there is no change in the console log if a checkbox item is selected. So, this is one problem I'm having. I still need to verify that two or more of the boxes are checked. I'm hoping to do this by adding an if else statement to the checkContactee function, but am not sure how.
Looking at your code I would recommend a couple of things. Your check boxes look like you want to capture multiple values for a contact type, so they should have the same name attribute. Each check box should have it's own label and where you have a label now you should use a fieldset and legend.
By wrapping the checkboxes in a fieldset we can then use that as part of the validation process.
$("document").ready(function() {
console.log("Loaded");
$("fieldset[data-mincheckboxchecked] [type=checkbox]").on("click", function() {
console.log("Click")
//Get the parent fieldset
let $parent = $(this).closest("fieldset[data-mincheckboxchecked]");
validateMultiCheckBox($parent);
});
});
function validateMultiCheckBox($parent) {
console.log($parent)
//Get minimum checked from the data attribute
let minCheked = $parent.data("mincheckboxchecked");
minChecked = parseInt(minCheked, 10);
//Get the number of checked checkboxes in the parent
let numCheked = $parent.find("[type=checkbox]:checked").length;
//Validation Logic
if (numCheked < minCheked) {
$parent.find(".error").html("<p>Please select at least " + minChecked + " option" + (minCheked !== 1 ? "s" : "") + "</p>");
$parent.find(".error").addClass("showerror");
return false;
} else {
$parent.find(".error").html("");
$parent.find(".error").removeClass("showerror");
return true;
}
}
$("#submit").click(function() {
var isValid = false;
var multiCheckValid = true;
//Validate each group of multi checkboxes
$("fieldset[data-mincheckboxchecked]").each(function() {
console.log(this);
if (!validateMultiCheckBox($(this))) {
multiCheckValid = false;
}
})
//Normally you'e set this to return false, leaving like
//this for demo purposes
console.log(multiCheckValid);
return isValid;
});
.error {
display: none;
color: red;
}
.error.showerror {
display: block;
}
fieldset label {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" method="POST">
<div class="contactForm">
<fieldset data-mincheckboxchecked="2">
<legend>Contactee Type: </legend>
<div id="errorcheckbox" class="error"></div>
<label><input type="checkbox" name="contactType" value="Individual">Individual</label>
<label><input type="checkbox" name="contactType" value="Catering">Business:Catering</label>
<label><input type="checkbox" name="contactType" value="Partner">Business:Partner</label>
</fieldset>
<fieldset data-mincheckboxchecked="1">
<legend>One Required: </legend>
<div id="errorcheckbox" class="error"></div>
<label><input type="checkbox" name="oneReq" value="1">A Thing</label>
<label><input type="checkbox" name="oneReq" value="2">Another Thing</label>
<label><input type="checkbox" name="oneReq" value="3">Yet another thing</label>
</fieldset>
<fieldset data-mincheckboxchecked="3">
<legend>Top 3 Movies: Three required</legend>
<div id="errorcheckbox" class="error"></div>
<label><input type="checkbox" name="movie" value="Top Gun">Top Gun</label>
<label><input type="checkbox" name="movie" value="Terminator">Terminator</label>
<label><input type="checkbox" name="movie" value="Sound Of Music">Sound OF Music</label>
<label><input type="checkbox" name="movie" value="Mission Impossible">Mission Impossible</label>
</fieldset>
</div>
<div class="button"><input type="button" name="submit" id="submit" value="Submit"></div>
</form>
This way it's extensible and not reliant on Ids.
You can use the :checked which the selector to get the checked items.
function validate() {
console.log('Total Checked = ' + $('.contactForm input[type="checkbox"]:checked').length);
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<div class="contactForm">
<label for="checkbox" id="checkbox" name="checkbox">Contactee Type: </label><br>
<div id="errorcheckbox" class="error"></div>
<input type="checkbox" name="type1" value="Individual">Individual<br>
<input type="checkbox" name="type2" value="Catering">Business:Catering<br>
<input type="checkbox" name="type3" value="Partner">Business:Partner<br>
<button onclick="validate()">Validate</button>
</div>
use a class for your checkboxes and select that or use tag name and type to select tags,
you are using the id of a label tag for checking checkboxes
, use .is() method in jquery to check is checked
$("document").ready(function(){
console.log("Loaded");
$("#submit").click(function(){
checkContactee();
});
$("input[type='checkbox']").change(function(){
console.log("Something in contactee changed");
checkContactee();
});
function checkContactee(){
if ($("input[type='checkbox']").is(':checked'){
$("#errorcheckbox").html("<p>You missed this field</p>");
$("#errorcheckbox").addClass("showerror");
}
else{
$("#errorregarding").html("");
$("#errorregarding").removeClass("showerror");
}
}
var checkedCount=$("input[name^='type']:checked).length - this pulls all inputs, looks for those with the name beginning with "type", keep the ones that are checked, and returns how many are check (here, assigned to the checkedCount variable). I'll leave further validation/scolding of the user up to you

How to find which radio Button is selected after a div

How can I find which radio button is selected after a precise div?
This is an Example:
<div class="largelines">
<p class="line">OPTION 1</p>
<div class="delete">
</div>
<fieldset>
<input type="radio" id="option1" name="option1" value="option1"><label for="option1">option1 </label><br>
<input type="radio" id="option2" name="option2" value="option2"><label for="option2">option2 </label>
</fieldset>
</div>
Here, when I click on the class .delete I would like to check (with jQuery) if one of the radio button below (inside the fieldset) has been selected. Do you have any hints?
Thanks in advance.
If there is just bunch of radio button you would like to check are checked or not you can do something like this
$(document).ready(function(){
$('.delete').on('click', function(){
$(document).find('input[type=radio]').each(function(){
if($(this).get(0).checked){
//do something
}
});
});
});
Ofc in line 3 you can specify more about the radio button location. For exp $(document).find('.largelines input[type=radio]') "OR" if you need to find radio butons based on delete button you can modify the code like this:
$(document).ready(function(){
$('.delete').on('click', function(){
var $parent = $(this).parents('.largelines');
$parent.find('input[type=radio]').each(function(){
if($(this).get(0).checked){
//do something
}
});
});
});
There is bunch of other ways to do that, another one is using next() or siblings() function:
$(document).ready(function(){
$('.delete').on('click', function(){
var $fieldset= $(this).next('fieldset');
//var $fieldset= $(this).siblings('fieldset');// i comment this out [its alternative way]
$fieldset.find('input[type=radio]').each(function(){
if($(this).get(0).checked){
//do something
}
});
});
});
This find only checked radio under .largelines scope of clicked .delete element.
$(function () {
$(document).on('click', '.delete', function () {
var isChecked = $('input:radio:checked', $(this).parent()).length > 0
alert(isChecked)
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="largelines">
<p class="line">OPTION 1</p>
<div class="delete">
Check 1
</div>
<fieldset>
<input type="radio" id="option1" name="option1" value="option1"><label for="option1">option1 </label><br>
<input type="radio" id="option2" name="option2" value="option2"><label for="option2">option2 </label>
</fieldset>
</div>
<hr>
<div class="largelines">
<p class="line">OPTION 2</p>
<div class="delete">
Check 2
</div>
<fieldset>
<input type="radio" id="option21" name="option1" value="option1"><label for="option1">option1 </label><br>
<input type="radio" id="option22" name="option2" value="option2"><label for="option2">option2 </label>
</fieldset>
</div>

Why can't I get the status of this radio button in jquery?

I have this piece of code from a salesforce visualforce page.
<div id="testId" class="row mb25 mt15">
<div class="col-md-6 plr0">
<p class="en">Would you like to add a co-applicant?<span class="asteriskField">*</span> </p>
<p class="fr">Would you like to add a co-applicant?<span class="asteriskField">*</span> </p>
</div>
<div class="col-md-4 mt-5r">
<apex:selectRadio id="innerTestId" value="{!client.Would_you_like_to_recieve_future_promo__c}" styleClass="radio">
<div class="row">
<div class="col-sm-6">
<div class="radio pa-cus">
<apex:selectOption itemLabel="Yes" itemValue="Yes"/>
</div>
</div>
<div class="col-sm-6">
<div class="radio pa-cus">
<apex:selectOption itemLabel="No" itemValue="No"/>
</div>
</div>
</div>
</apex:selectRadio>
</div>
</div>
When the Submit button is clicked I need to have a JQuery script to check weather the radio button is selected Yes or No so that I can perform some custom validation. I call this function by adding onclick="validateInnerTestId();" to Submit button.
My problem is that I am unable to read/check whether the radio button is chosen Yes or No or True or False. If I can find out what state they are in then I can do my
Here is my goal
<script type="text/javascript">
<script>
function validateInnerTestId()
{
if(innerTestId is Selected as Yes)
{
execute fucntionX()
}
else
{
execute functionY()
}
}
<script>
Here is some examples of how I have tried to read the value of the radio button:
alert($("#innerTestId").itemValue()); this line doesn't return anything
alert($("#innerTestId").val()); this line also doesn't return anything
and this if else always return no
if ($('innerTestId').is(':checked'))
{
alert("yes");
}
else
{
alert("no");
}
Does anyone has any idea on how to check for the radio button in this case?
Thanks
As #Andrea mentioned in the comments, you simply forgot the # in your selector. There is a simple example below demonstrating the usage. If your code still isn't working we will need more info.
Are you sure validateInnerTestId() is being called?
How is it being called?
$('#doit').on('click',function() {
var str = "";
if ($('#test').is(':checked')) {
str += "Toggle checked? YES\n"
} else {
str += "Toggle checked? NO\n"
}
if ($('#option1').is(':checked')) {
str += "Option checked: 1";
} else if ($('#option2').is(':checked')) {
str += "Option checked: 2";
} else {
str += "Option checked: NONE";
}
alert(str);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input id="test" name="toggle" type="checkbox" value="" />
<label for="toggle">Toggle</label>
</div>
<div>
<input type="radio" id="option1" name="options" value="1">
<label for="option1">Option 1</label>
<input type="radio" id="option2" name="options" value="2">
<label for="option1">Option 2</label>
</div>
<br />
<input id="doit" type="button" name="test" value="Tell me!" />
It might also be something to do with the ASP/SalesForce implementation? Perhaps some of the answers in this question might help: How to check if an option is selected?
VF tags use dynamic ids, you should do following:
function validateInnerTestId(){
if($('#{!component.innerTestId}').is(':checked')){
execute fucntionX()
}
else{
execute functionY()
}
}

how to hide and show named divs according to radio value?

This one is quite similar to my other question on:
how to hide and show named divs according to enum value?
Idea here is slightly different, though. The toggle() jQuery function is related to a radio button which is coded below:
<div id="recurrent">
<label for="recurrent">Recurrent? </label>
<input type="radio" id="idtrue" name="recurrent" value="true">Yes
<input type="radio" id="idfalse" name="recurrent" value="false" checked>No
</div>
The div to toggle is:
<div id="ifRecurrentTrue">
/// something
</div>
And the adapted jQuery from the other question is:
$('#recurrent select').on('change', function () {
var value = this.value;
$('#ifRecurrentTrue').toggle(value == true);
}).change();
I bet it's just a matter of different functions, right?
Again, thanks in advance!
You need to find the input elemetns by its name, so use the attribute equals selector instead of the element selector select
$('#recurrent input[name="recurrent"]').on('change', function() {
$('#ifRecurrentTrue').toggle(this.checked && this.id == 'idtrue');
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="recurrent">
<label for="recurrent">Recurrent?</label>
<input type="radio" id="idtrue" name="recurrent" value="true">Yes
<input type="radio" id="idfalse" name="recurrent" value="false" checked>No
</div>
<div id="ifRecurrentTrue">
/// something
</div>
Did't see the element with select tag on provided code, could be input. Replace select with input like following:
$('#recurrent input').on('change', function () {
var value = this.value;
$('#ifRecurrentTrue').toggle(value == true);
}).change();
$(document).ready(function() {
$('input:radio[name=recurrent]').on('change', function () {
var values = this.value;
$('#ifRecurrentTrue').toggle(values =='true');
}).change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="recurrent">
<label for="recurrent">Recurrent? </label>
<input type="radio" id="idtrue" name="recurrent" value="true">Yes
<input type="radio" id="idfalse" name="recurrent" value="false" checked>No
</div>
<div id="ifRecurrentTrue">
/// something
</div>

Using .parent to select divs

I have a script which greys out a text area whenever the yes radio button is selected. I would like to modify the jquery script so that the textarea can be in a different div and still be disabled as before.
Looking through the jquery docs it looks to me I can do this using .parent but I'm having trouble getting it to work.
<div class="group">
<input type="radio" name="choice2" value="yes" />Yes
<input type="radio" name="choice2" value="no" />No
</div>
<div class="group">
<textarea rows="4" cols="20"></textarea>
</div>
How can I do this? Or is there a better way?
Edit:
$(function () {
var $choices = $(".group").find(":radio");
$choices.on("change", function () {
var $this = $(this);
var tarea = $this.closest(".group").next(".group").find("textarea");
if ($this.val() === "yes") {
tarea.val('');
tarea.prop('readonly', true);
tarea.css('background-color', '#EBEBE4');
} else {
tarea.prop('readonly', false);
tarea.css('background-color', '#FFFFFF');
}
});
});
Added to each <textarea> the attribute "trigger". Determinates it's trigger element by name. For example <textarea data-trigger="choice2"> means <input name="choice2"/> change's it's stare (gray/or not).
This way you can add your textarea elements anywhere inside your page without worries.
Here is an example: http://jsfiddle.net/r0gw8t1b/2/
var tarea = $this.closest(".group").next(".group").find("textarea");
You can use next() to achieve that. It finds the parent group and then looks at immediate sibling and looks for textarea.
<div class="group">
<input type="radio" name="choice1" value="yes" />Yes
<input type="radio" name="choice1" value="no" />No
</div>
<div class="group">
<textarea rows="4" cols="20"></textarea>
</div>
DEMO
This jsFiddle shows how it could be done.
$($(this).parent().siblings('div.group')[0]).find('textarea');
Find the text area inside the parents siblings of type div.group, and then you can set the css or whichever attributes you want to set as seen in the jsFiddle.
The below code works well for the selection and disabling the desired text area:
HTML:
<div class="group">
<input type="radio" name="choice2" value="yes" />Yes
<input type="radio" name="choice2" value="no" />No
</div>
<div class="group">
<textarea rows="4" cols="20"></textarea>
</div>
JQUERY:
$(function () {
$( "input[type='radio']" ).click(function () {
if ($(this).val()=='yes') {
$('.group textarea').attr('readonly',true);
$('.group textarea').css('background-color', '#f1f1f1');
} else {
$('.group textarea').attr('readonly',false);
$('.group textarea').css('background-color', '#fff');
}
});
});

Categories

Resources