jQuery multiple show hides in one form - javascript

I have a form with a number of questions on it, some are a yes/no. If yes is selected, it will display a text box asking for more info. I've got the show/hide part to work but once I click a button elsewhere on the page it then hides the textarea and i lose the info.
Currently I'm using this:
JQuery
$(document).ready(function () {
$(".text").hide();
$("#r1").click(function () {
$(".text").show();
});
$("#r2").click(function () {
$(".text").hide();
});
});
HTML
<input type="radio" name="radio1" id="r1" value="Yes">
<input type="radio" name="radio1" id="r2" value="No">
<div class="text">
<textarea class="form-control" rows="3" id="comment"></textarea>
</div>

You need to target the textarea relative to the checkboxes being checked.
I've listened for the change event, rather than click (there are other ways of changing a radio button other than clicking it)
I've used .nextAll() and .first() to get the relevant textarea
I've also used toggle() with this.value == 'Yes' which will be expressed as a true or false value and therefore show or hide the element respectively.
$('.text').hide();
$('input[type=radio]').on('change', function(){
$(this).nextAll('.text').first().toggle( this.value == 'Yes' );
});
JSFiddle

OP here, if anyone is looking for the answer using buttons instead I resolved the issue with advice from Norlihazmey Ghazali who mentioned to target the specific id.
For example:
<div class="btn-group btn-toggle">
<input type="button" class="btn btn-default" id="taxliabl1" value="Yes"></input>
<input type="button" class="btn btn-default" id="taxliabl2" value="No"></input>
<br>
<div class="taxliabltext">
<br>
<textarea class="form-control" rows="3" id="comment"></textarea>
<br>
Jquery:
$(document).ready(function () {
$(".taxliabltext").hide();
$("#taxliabl1").click(function () {
$(".taxliabltext").show();
});
$("#taxliabl2").click(function () {
$(".taxliabltext").hide();
});
});

Related

Show Textbox based on RadioButton selection or value when Page Loads

So when I load a page I retrieve info from a DB and will check a radiobutton based on its value...
I need the textboxes to show initially - based on the radiobutton being already checked
works fine when I perform the click event, but I need to show the textboxes when the page loads because the 1st radiobutton is checked from the DB...
<p>
Show textboxes <input type="radio" name="radio1" value="Show" checked="checked">
Do nothing <input type="radio" name="radio1" value="Nothing">
</p>
Wonderful textboxes:
<div class="text"><p>Textbox #1 <input type="text" name="text1" id="text1" maxlength="30"></p></div>
<div class="text"><p>Textbox #2 <input type="text" name="text2" id="text2" maxlength="30"></p></div>
Here is my FIDDLE - DEMO
http://jsfiddle.net/rbla/5fq8q2bj/
here is the jquery using toggle
$(document).ready(function() {
$(".text").hide()
$('[name=radio1]').on('change', function(){
$('.text').toggle(this.value === 'Show');
}).trigger('change');
});
any ideas...
The reason your solution is not working is because you are going through all your radio inputs and then toggling the element based on its value—regardless if it is checked or not. So at runtime, this is what your script does:
Encounters the first radio element, triggers onchange event, fires onchange callback, and shows the .text element
Encounters the second radio element, triggers onchange event, fires onchange callback, and hides the .text element again
If you put a console log in your callback, you will realized that the .text element is shown and hidden in quick succession.
What you really want to do is only to perform the toggling when it is checked. Therefore, your example will work by simply enforcing a check that this.checked is truthy before performing the toggling:
$('[name=radio1]').on('change', function() {
if (this.checked) {
$('.text').toggle(this.value === 'Show');
}
}).trigger('change');
See working example below:
$(document).ready(function() {
$(".text").hide()
$('[name=radio1]').on('change', function() {
if (this.checked) {
$('.text').toggle(this.value === 'Show');
}
}).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
Show textboxes
<input type="radio" name="radio1" value="Show" checked="checked"> Do nothing
<input type="radio" name="radio1" value="Nothing">
</p>
Wonderful textboxes:
<div class="text">
<p>Textbox #1
<input type="text" name="text1" id="text1" maxlength="30">
</p>
</div>
<div class="text">
<p>Textbox #2
<input type="text" name="text2" id="text2" maxlength="30">
</p>
</div>

Show or Hide field when selected radio button codeigniter

I am currently doing a project. I have 2 radio button,1) One way 2) Round trip. When the user tried to select the One way radio button, the return text field will hide.
I've saw a thread and someone comment regarding to this problem. Scenario: I chose the One way radio button, the return field will disappear, yes it is working but there's some problem. What if I change my mind, from one way radio button to Round trip? The problem is the return field didn't came back
**View **
// my radio button
<div class="pure-u-1-1 radiobtn">
<form action="">
<input type="radio" name="flight_type" value="one_way" class="onew" style="" >One Way
<input type="radio" name="flight_type" class="roundw" style="" checked>Round Trip
</form>
</div>
// the return field that will hide/show
<div class="pure-u-1-1 dr" id="try">
<label for="return" class="drr">Return</label>
<input type="text" id="return" name="return" class="departreturn"><br>
</div>
JS
<script type="text/javascript">
$(document).on('change', 'input:radio[name=flight_type]', function(){
$('div[id^="try"]').hide(); // hide all DIVs begining with "my_radio_"
$('#' + $(this).attr('id') + '_text').show(); // show the current one
});
</script>
Just use .toggle()
.toggle()
Description: Display or hide the matched elements.
With no parameters, the .toggle() method simply toggles the visibility of elements:
REF: http://api.jquery.com/toggle/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pure-u-1-1 radiobtn">
<form action="">
<input type="radio" name="flight_type" value="one_way" class="onew" style="">One Way
<input type="radio" name="flight_type" class="roundw" style="" checked>Round Trip
</form>
</div>
<div class="pure-u-1-1 dr" id="try">
<label for="return" class="drr">Return</label>
<input type="text" id="return" name="return" class="departreturn"><br>
</div>
<script type="text/javascript">
$(document).on('change', 'input:radio[name=flight_type]', function() {
$('div[id^="try"]').toggle(); // toggle all DIVs begining with "my_radio_"
$('#' + $(this).attr('id') + '_text').show(); // show the current one
});
</script>

Get the value of a radio button using jquery [duplicate]

This question already has answers here:
How to check a radio button with jQuery?
(33 answers)
Closed 6 years ago.
I have this portion of code:
var checkout_options = $("#checkout").find("input[type='radio']");
$('#button-account').on('click', function () {
alert(checkout_options.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<div id="checkout">
<p>Checkout Options:</p>
<label for="register">
<input type="radio" name="account" value="register" id="register" checked>
<b>Register Account</b></label>
<br>
<label for="guest">
<input type="radio" name="account" value="guest" id="guest">
<b>Guest Checkout</b>
</label>
<input type="button" value="Continue" id="button-account">
</div>
What I want it is to get the value of the selected radio button but with my code I only get the first radio button value, the second radio does not work.
Kindly help me fix the error.
You need to use this to refer the element inside the callback. So get value by using this.value or $(this).val() method. Although avoid :checked pseudo-class selector otherwise it only selects the first element.
var selected = $("#checkout").find("input[type='radio']");
selected.change(function(){
alert(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<div id="checkout">
<p>Checkout Options:</p>
<label for="register">
<input type="radio" name="account" value="register" id="register" checked>
<b>Register Account</b></label>
<br>
<label for="guest">
<input type="radio" name="account" value="guest" id="guest">
<b>Guest Checkout</b>
</label>
</div>
You can make it simpler using :radio pseudo-class selector
$("#checkout :radio").change(function() {
alert(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<div id="checkout">
<p>Checkout Options:</p>
<label for="register">
<input type="radio" name="account" value="register" id="register" checked>
<b>Register Account</b>
</label>
<br>
<label for="guest">
<input type="radio" name="account" value="guest" id="guest">
<b>Guest Checkout</b>
</label>
</div>
Your handler is only being attached to the radio button that is checked, so no handler exists for the second radio button. Attach a handler to both radio buttons:
var $radioBtn = $( "#checkout" ).find( "input[type='radio']" );
$radioBtn.on( 'change', function() {
if ( this.checked ) {
alert( this.value );
}
});
It didn't work, because you register the event handler for the initially checked value only. This is how to make it dynamically reflect the value change:
var selected = $("#checkout").find("input[name='account']");
selected.change(function(){
alert($(this).val());
});
This also makes sure that only the current radio button group is included, so you can have additional ones.
Jsfiddle:
https://jsfiddle.net/sjmhdasw/
Just use
$("input[type='radio']").on("change", function() {
console.log(this.id + " checked !");
});
It binds an event listener on all the inputs of type radio !
No need to store the selectors inside a variable (unless you're doing something with it, somewhere else in your code)

Event Listener for Multiple Radio Button Groups

How would you have a dynamic Javascript/JQuery event listener to know which radio button group is clicked and retrieve the value of the checked element. For example if I have two radio button groups how would I know which one is clicked? How would I do it for a dynamic number of button groups?
Example of two radio button groups:
<div class="btn-group btn-group-vertical" data-toggle="buttons">
<input type="radio" name="input1" value="option1"/>
<input type="radio" name="input1" value="option2"/>
</div>
<div class="btn-group btn-group-vertical" data-toggle="buttons">
<input type="radio" name="input2" value="option1"/>
<input type="radio" name="input2" value="option2"/>
</div>
Edit: For anyone else wondering which of the following question below so far is "more" right, both are correct as .change(function(e) { is a shortcut for .on('click', function(e) {
Edit 2:Removed ID's
This jquery will execute a callback that print in the console the name and the value of the 'clicked' (not changed) radio button.
$('input:radio').on('click', function(e) {
console.log(e.currentTarget.name); //e.currenTarget.name points to the property name of the 'clicked' target.
console.log(e.currentTarget.value); //e.currenTarget.value points to the property value of the 'clicked' target.
});
try it:
Fiddle
To provide a pure JavaScript solution: create a collection for all your radio type inputs and then loop through them all adding an event listener to each. Using this, you can then access any attributes or properties you wish and, if necessary, the parent element as well.
var inputs=document.querySelectorAll("input[type=radio]"),
x=inputs.length;
while(x--)
inputs[x].addEventListener("change",function(){
console.log("Checked: "+this.checked);
console.log("Name: "+this.name);
console.log("Value: "+this.value);
console.log("Parent: "+this.parent);
},0);
Alternatively, as you mention that the number of groups is dynamic, you might need a live node list, which requires a little extra code to check the input type:
var inputs=document.getElementsByTagName("input"),
x=inputs.length;
while(x--)
if(inputs[x].type==="radio")
inputs[x].addEventListener("change",function(){
console.log("Checked: "+this.checked);
console.log("Name: "+this.name);
console.log("Value: "+this.value);
console.log("Parent: "+this.parent);
},0);
Find the name of the input on the change event.
$('input:radio').on('change', function(e){
var name = e.currentTarget.name,
value = e.currentTarget.value;
$('.name').text(name);
$('.value').text(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btn-group btn-group-vertical" data-toggle="buttons">
<input type="radio" name="input1" id="input1" value="option1"/>
<input type="radio" name="input1" id="input1" value="option2"/>
</div>
<div class="btn-group btn-group-vertical" data-toggle="buttons">
<input type="radio" name="input2" id="input2" value="option1"/>
<input type="radio" name="input2" id="input2" value="option2"/>
</div>
<p>Name: <b class="name"></b></p>
<p>Value: <b class="value"></b></p>
Edit: For anyone else wondering which of the following question below so far is "more" right, both are correct as .change(function(e) { is a shortcut for .on('click', function(e) {
Yes, .change(function(e) { is a shortcut for .on('click', function(e) {, but when you are working with partial views for example in MVC, with .change(function(e) { the link or buttons in the page lose the hiperlink or don't work correctly, so you have to work with .on('click', function(e) { where the hiperlink work fine.

jquery in yii: Detecting radiobutton losing check mark (checked state)

Given the following code (yes, i know it is perhaps irrelevant in yii, but I added the tag so I update the question with the actual generated html):
<script>
$(function(){
$('#widgetId-form input[name="valueType"]').change(function(){
if ($(this).is(":checked"))
{
console.log("habilitando "+$(this).data("class"));
$("."+$(this).data("class")).prop("disabled", false);
}
else
{
console.log("deshabilitando "+$(this).data("class"));
$("."+$(this).data("class")).prop("disabled", true);
}
}).change();
});
</script>
<div id="widgetId-dialog">
<form id="widgetId-form" action="/support/test" method="post">
<div>
<input id="valueType-single" value="single" data-class="singleValueField" checked="checked" type="radio" name="valueType" />
<label for="single">Valor simple</label>
<input size="6" class="singleValueField" type="text" value="" name="singleValue" id="singleValue" />
</div>
<div>
<input id="valueType-range" value="range" data-class="rangeValueField" type="radio" name="valueType" />
<label for="range">Rango (inicio:fin:intervalo)</label>
<input size="6" class="rangeValueField" type="text" value="" name="rangeValue_start" id="rangeValue_start" />:<input size="6" class="rangeValueField" type="text" value="" name="rangeValue_end" id="rangeValue_end" />:<input size="6" class="rangeValueField" type="text" value="" name="rangeValue_interval" id="rangeValue_interval" />
</div>
</form>
</div>
It doesn't trigger change() when a radio becomes unchecked. This implies: controls are disabled only on initialization (.ready()). change() is not triggered individually by controls losing the checkmark.
Question: how can I detect when a radio button loses the checkmark?
This is a conceptional problem. The radio buttons are seen somehow like one element. For closer information look at Why does jQuery .change() not fire on radio buttons deselected as a result of a namesake being selected?.
So the change-event will always only fire on the newly selected element and not on the deselected radios. You could fix your code like this:
$(function(){
$('#widgetId-form input[name="valueType"]').change(function(){
//could be also hardcoded :
$('input[name="' + $(this).attr("name") + '"]').each(function(){
if ($(this).is(":checked"))
{
console.log("habilitando "+$(this).data("class"));
$("."+$(this).data("class")).prop("disabled", false);
}
else
{
console.log("deshabilitando "+$(this).data("class"));
$("."+$(this).data("class")).prop("disabled", true);
}
});
});
$('#widgetId-form input[name="valueType"]:first').change();
});
You can check it at http://jsfiddle.net/jg6CC/. Greets another Luis M. ;)

Categories

Resources