Using .parent to select divs - javascript

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

Related

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>

add highlight class to the label of a checked check box via a button

I have checked all over stack overflow, but they're not exactly what I need.
I have checkboxes with associated labels
<p>
<input type="checkbox" name="animals" value="dog" id="dg" />
<label for="dg">Dog</label>
</p>
<p>
<input type="checkbox" name="animals" value="cat" id="ct" />
<label for="ct">Cats</label></p>
<p>
<p><input type="button" id='bt' value="Record" /></p>
There is also a button, when the button is clicked, if the checkbox is checked, the label associated with it has a highlight class added to the label. I already have the highlight class written I am just having trouble applying it using the addClass method.
I have:
$(':checkbox:checked').addClass('highlight');
but it does nothing
Let's say this is your HTML:
<p>
<input type="checkbox" name="animals" value="dog" id="dg" />
<label for="dg">Dog</label>
</p>
<p>
<input type="checkbox" name="animals" value="cat" id="ct" />
<label for="ct">Cats</label></p>
<p>
<p>
<button id="btnSubmit">Click Me!</button>
</p>
and this is your CSS class:
.highlight {
background-color: yellow;
}
One thing you could do is loop through each checked checkbox and just apply the class using the label[for=*] property:
$('#btnSubmit').click(function() {
$('input:checked').each(function () {
$("label[for='" + $(this).attr('id') + "']").addClass("highlight");
});
});
However, using the above method, you're not allowing a way to remove the highlight class should you uncheck a box and hit Submit again. I would prefer the below method... which loops through ALL checkboxes, and tests them to determine if they're checked or not:
$('#btnSubmit').click(function() {
$('input[type=checkbox]').each(function () {
if (this.checked) {
$("label[for='" + $(this).attr('id') + "']").addClass("highlight");
} else {
$("label[for='" + $(this).attr('id') + "']").removeClass("highlight");
}
});
});
Try this Fiddle
I'm trying to find a way to just reference the label of all checked checkboxes in one line of code. Because if you could do that, you can just do away with the looping and the if statements. I'll keep researching, and if I find it, I'll edit my post accordingly.
Update: Okay, I think I understand what you need. See updated example.
The trick is knowing how to find the label and checkbox associated with the button. Since the buttons were not included in the question code, I had to guess. If the button is elsewhere, you can experiment using these jQuery traversing methods.
$(document).ready(function(){
$('#mybutt').click(function(){
var chkboxes = $('input[type=checkbox]');
$(chkboxes).each(function(){
if ( $(this).is(':checked') ){
$(this).parent().find('label').addClass('highlight');
}else{
$(this).parent().find('label').removeClass('highlight');
}
});
});
}); //END document.ready
.highlight{background:red;color:yellow;padding:2px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>
<input type="checkbox" name="animals" value="dog" id="dg" />
<label for="dg">Dog</label>
</p>
<p>
<input type="checkbox" name="animals" value="cat" id="ct" />
<label for="ct">Cats</label>
<p>
<button id="mybutt">Go</button>
I guess, what you are trying to do is to change a class, after the value of your checkbox has changed, easiest way to do this is using the onChange event, you can also bind the event with jQuery using $('#your_checkbox').on('change', function(){})
$('[type="checkbox"]').on('change', function() {
if (!$(this).attr('checked')) {
$(this).attr('checked', 'checked');
$(this).parent().addClass('checked');
} else if ($(this).attr('checked') === 'checked') {
$(this).removeAttr('checked', '');
$(this).parent().removeClass('checked');
}
});
$('#btnSubmit').on('click', function() {
var inputs = $(this).parent().parent().find('[type="checkbox"]')
inputs.each(function(){
if ($(this).attr('checked') === 'checked') {
$(this).parent().addClass('iam-checked');
}
else {
$(this).parent().removeClass('iam-checked');
}
});
});
.checked {
border-bottom: 1px solid green;
}
.iam-checked {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<input type="checkbox" name="animals" value="dog" id="dg" />
<label for="dg">Dog</label>
</p>
<p>
<input type="checkbox" name="animals" value="cat" id="ct" />
<label for="ct">Cats</label></p>
<p>
<p>
<button id="btnSubmit">Click Me!</button>
</p>
This is a little late, but I was surprised that no one mentioned the next method. You are trying to style the label after the checkbox, not the checkbox itself. In other words, the label is the next sibling of the checkbox.
I think this is the most jQuery way to solve this so wanted to add my two cents.
$("#bt").on("click", function() {
$(":checked").each(function() {
$(this).next().addClass("highlight");
});
});
.highlight { background: gold; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<input type="checkbox" name="animals" value="dog" id="dg" />
<label for="dg">Dog</label>
</p>
<p>
<input type="checkbox" name="animals" value="cat" id="ct" />
<label for="ct">Cats</label></p>
<p>
<p><input type="button" id='bt' value="Record" /></p>

How do I disable text areas based on what radio button is checked when the page loads?

I want to improve upon this script for disabling text areas by radio button selection. Currently when "yes" is selected the text areas should be disabled and enabled when "no" is selected.
What do I need to change so the text areas are disabled when the page first loads and if the correct radio button is checked?(yes is checked by default if no change has been made)
Please bare in mind this page will be refreshed and redirected to so I will need to check the actual selection on the radio buttons. I was just setting them to all be disabled on load before but this disabled text areas even when I had the correct radio button selected.
HTML
<div class="group">
<input type="radio" name="choice1" value="yes" checked/>Yes
<input type="radio" name="choice1" value="no" />No
</div>
<div class="group">
<input type="radio" name="choice2" value="yes" checked/>Yes
<input type="radio" name="choice2" value="no" />No
</div>
<div class="group">
<input type="radio" name="choice3" value="yes" checked/>Yes
<input type="radio" name="choice3" value="no" />No
</div>
<div>
<textarea data-trigger="choice1" rows="4" cols="20"></textarea>
<textarea data-trigger="choice2" rows="4" cols="20"></textarea>
<textarea data-trigger="choice3" rows="4" cols="20"></textarea>
</div>
Javascript/JQuery
$(function () {
var $choices = $(".group").find(":radio");
$choices.on("change", function () {
var $this = $(this);
var choiceName = $this.attr('name');
var tarea = $('[data-trigger="' + choiceName + '"]');
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');
}
});
});
Hope that's clear enough.
try
$(".group").find(":radio[value=yes]:checked").each(function () {
$('[data-trigger="' + $(this).attr("name") + '"]').prop('readonly', true).css('background-color', '#EBEBE4');
});
DEMO
Add the class attribute to your textarea
<div>
<textarea data-trigger="choice1" rows="4" cols="20" class="group"></textarea>
<textarea data-trigger="choice2" rows="4" cols="20" class="group"></textarea>
<textarea data-trigger="choice3" rows="4" cols="20" class="group"></textarea>
</div>
in your script:-
$( document ).ready(function() {
$("textarea.group").attr("disabled", true);
});

How to toggle div visibility using radio buttons?

I'm working on a project in which I have to toggle the visibility of a <div>.
I've got the following code:
<input type="radio" name="type" value="1"> Personal
<input type="radio" name="type" value="2"> Business
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>
I would like to togle the business-fields div. So, if none of the radio buttons, or the 'personal' radio button is selected: The div should be hidden. If the 'business' radio button is selected, I want it to show.
Currently, I am using this code:
$("input[name='type']").click(function() {
var status = $(this).val();
if (status == 2) {
$(".business-fields").show();
} else {
$(".business-fields").hide();
}
});
However, I was wondering if I can do this using the .toggle() function.
I usually tend not to use JS if possible, therefore here comes a HTML+CSS way approach.
.bussines-type .business-fields {
display: none;
}
.bussines-type input[value="2"]:checked ~ .business-fields {
display: block;
}
<div class="bussines-type">
<input id="bt1" type="radio" name="type" value="1">
<label for="bt1"> Personal</label>
<input id="bt2" type="radio" name="type" value="2">
<label for="bt2"> Business</label>
<div class="business-fields">
<input type="text" placeholder="Company name" name="company-name">
<input type="text" placeholder="Vat number" name="vat-number">
</div>
</div>
The ~ stands for any siblings, that are after the element we defined before the ~ sign.
I'd suggest using the change event, and supplying a Boolean switch to the toggle() method, which will show the jQuery collection of elements if the switch evaluates to true, and hide them if it evaluates to false:
// select the relevant <input> elements, and using on() to bind a change event-handler:
$('input[name="type"]').on('change', function() {
// this, in the anonymous function, refers to the changed-<input>:
// select the element(s) you want to show/hide:
$('.business-fields')
// pass a Boolean to the method, if the numeric-value of the changed-<input>
// is exactly equal to 2 and that <input> is checked, the .business-fields
// will be shown:
.toggle(+this.value === 2 && this.checked);
// trigger the change event, to show/hide the .business-fields element(s) on
// page-load:
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="radio" name="type" value="1">Personal</label>
<label>
<input type="radio" name="type" value="2">Business</label>
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>
Incidentally, note I've also wrapped the associated text, to indicate the radio-button's purpose, inside of a <label> element to directly associate that text with the <input>, so clicking the text checks the <input> automatically.
References:
change().
on().
toggle().
JS Fiddle
Try this one
<input type="radio" name="type" value="1" checked ="true"> Personal
<input type="radio" name="type" value="2"> Business
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>
.business-fields{
display: none;
}
$("input[name='type']").change(function() {
$(".business-fields").toggle();
});
You may use like this:
$("input[name='type']").change(function() {
var status = $(this).val();
if (status != 2) {
$(".business-fields").hide();
} else {
$(".business-fields").show();
}
});
.show and .hide are pretty slow.
https://twitter.com/paul_irish/status/564443848613847040
It's better to toggle a css class on and off with javascript. Set the css of the class to {visibility: hidden} or {display: none}
use the below code
<script>
$(function(){
$(":radio[value=1]").click(function(){
var isVisible = $( ".business-fields" ).is( ":visible" );
if(isVisible==true)
$('.business-fields').toggle();
});
$(":radio[value=2]").click(function(){
var isVisible = $( ".business-fields" ).is( ":visible" );
if(isVisible==false)
$('.business-fields').toggle();
});
});
</script>
AND HTML is-
<input name="type" type="radio" value="1" >Personal
<input type="radio" name="type" value="2" checked="checked"> Business
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>
Possibly a more elegant solution, It's a bit more readable in my opinion, and and as #Ollie_W points out it might be more performant that toggle (show/hide).
$('input[name="type"]').on('change', function(event) {
var radioButton = $(event.currentTarget),
isBusiness = radioButton.val() === 'business' && radioButton.prop('checked');
$('.business-fields').toggleClass('hidden', !isBusiness);
}).change();
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="radio" name="type" value="personal">Personal</label>
<label>
<input type="radio" name="type" value="business">Business</label>
<div class="business-fields hidden">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>

toggle textbox if checkbox is true for CMS

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.

Categories

Resources