Toggle Div visibility upon radion button select issue - javascript

I have managed to create a Div visibility toggle with the following code :
$('input[name="type"]').on('change', function() {
var show = $(this).val();
$(".typechoice").hide();
$("#"+show).show();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="type" value="solo" checked ;> solo<br>
<input type="radio" name="type" value="company" ;> company<br>
<div id="solo" class="typechoice">Solo</div>
<div id="company" class="typechoice">Company</div>
It works perfectly but not when the page is loaded the first time (both Div are visible instead of a single Div only then). I think it is because onchange is used in the JS (I am no expert and grabbed bit on different stack overflow threads)
How can I have this code work when a radio button is already checked on the page before the user action any?

Just trigger the change event of checked checkbox using the following line to hide the other div initially.
$('input[name="type"]:checked').change()
FULL CODE
$('input[name="type"]').on('change', function() {
var show = $(this).val();
$(".typechoice").hide();
$("#" + show).show();
})
$('input[name="type"]:checked').change()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="type" value="solo" checked ;> solo
<br>
<input type="radio" name="type" value="company" ;> company
<br>
<div id="solo" class="typechoice">AAAA</div>
<div id="company" class="typechoice">BBBB</div>

It would be simplest to just call change() on the checked radio in document.ready()
$(function(){
$('input[type=radio]:checked').change();
});
$('input[name="type"]').on('change', function() {
var show = $(this).val();
$(".typechoice").hide();
$("#"+show).show();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="type" value="solo" checked ;> solo<br>
<input type="radio" name="type" value="company" ;> company<br>
<div id="solo" class="typechoice">Solo</div>
<div id="company" class="typechoice">Company</div>

You could use something like this, too:
$('#'+$('input[name="type"]:checked').val()).show();
Looks ugly, but it works.
Demo: https://jsfiddle.net/qnwudaeL/

Maybe you can extract the change function and call it when page is loaded:
function showDiv() {
var show = $("input[name='type']:checked").val();
$(".typechoice").hide();
$("#"+show).show();
}
$(document).ready(function () {
$('input[name="type"]').on('change', showDiv)
showDiv();
});

Related

Make check-boxes becoming one group of radio button

I cannot make the input name same or value same. The second and third inputs come from a loop using c# razor. I have 2 sets of radio inputs first one is one set and second and third are another set. Because the second and third have the same name, checking one makes the other unchecked. I want the same for all of them together so it would be like I have one set of 3 radio buttons. Like I said above I am not able to make the name or value same due to back-end data display issue. Here is my attempt below.
//first radio <br/>
<div class="radio">
<label>
<input id="dcenter-allradio" type="radio" value="0" />All
</label>
</div>
//this radio button is a loop <br>
<input type="radio" name="#Model.Facet.Key" value="#item.Key">tagitem.j
<div class="radio">
<label>
<input id="dcenter-listradio" type="radio" name="#Model.Facet.Key" value="#item.Key" />tagItem.Name
</label>
</div>
<script>
$(document).ready(function () {
if ($('#dcenter-listradio').prop("checked", true)) {
$('#dcenter-allradio').prop("checked", false);
}
if ($('#dcenter-allradio').prop("checked", true)) {
$('#dcenter-listradio').prop("checked", false);
}
});
</script>
If you can give them all the same class, then you can just use jQuery to detect when a change has occurred and then uncheck other items in the same class.
$(document).ready(function() {
var selector = ".groupTogether";
// or if you can't give same class, you could use "#unrelatedRadio, input[name='related']"
$(selector).change(function()
{
if(this.checked)
{
$(selector).not(this).prop('checked', false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="unrelatedRadio" name="unrelated" type="radio" class="groupTogether">unrelated</input>
<input id="relatedA" name="related" type="radio" class="groupTogether">Related A</input>
<input id="relatedB" name="related" type="radio" class="groupTogether">Related B</input>
Or, if you can't give them the same class, just replace the selector with something that selects both sets (in my example, "#unrelatedRadio, input[name='related']")
let radios = document.querySelectorAll("input");
for (let i of radios){
i.name="same"
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
//first radio <br/>
<div class="radio">
<label>
<input id="dcenter-allradio" type="radio" value="0" />All
</label>
</div>
//this radio button is a loop <br>
<input type="radio" name="#Model.Facet.Key" value="#item.Key">tagitem.j
<div class="radio">
<label>
<input id="dcenter-listradio" type="radio" name="#Model.Facet.Key" value="#item.Key" />tagItem.Name
</label>
</div>

When checkbox is clicked, how to know the state of the checkboxes

EDIT:
Please read the end part of the post, I know the part that tells which are unchecked needs to be inside the block of code, the issue here is that the first part of the code is not registering the "click". So can't do anything without that.
E2: May take the suggestion of adding a onclick to the boxes, since the code for boxes is generated with JS, I would add it once and all of them will get the function call, but that feels kinda ugly
I have a set of check boxes, and when one is clicked I need to return the values of the unchecked ones.
HTML:
<div id="myCheckboxList">
<input type="checkbox" name="myList" value="1" checked>1
<input type="checkbox" name="myList" value="2" checked>2
<input type="checkbox" name="myList" value="3" checked>3
</div>
JavaScript:
$(function(){
$("input[name=myList]").on("click",function(){
console.log("triggered");
//code here to find which ones are unchecked
});
});
I have tried to also add this in the code
$boxes = $('input[name=myList]:not(:checked)');
$boxes.each(function(){
// Do stuff with for each unchecked box
});
Unfortunatly the "triggered" in not getting output to console, so unsure why it is so, and how would i get an event to happen when the checkboxes are hit
I copied your code directly to a fiddle, and it works fine. You could be missing the jquery library?
EDIT:
Just to be sure, I updated the snippet to generate the inputs, and it still works fine.
$(function() {
var html = '<input type="checkbox" name="myList" value="1" checked>1'
+'<input type="checkbox" name="myList" value="2" checked>2'
+'<input type="checkbox" name="myList" value="3" checked>3';
$("#myCheckboxList").html(html);
$("input[name=myList]").on("click", function() {
console.log("triggered");
//code here to find which ones are unchecked
$boxes = $('input[name=myList]:not(:checked)');
$boxes.each(function() {
console.log($(this).val());
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myCheckboxList">
</div>
Easiest way would be to:
let v = $(this).attr('value');
if(v === 1){ // box 1 selected
Adding this inside your 'click' handler should work.
You need to add your each script inside your click event.
$(function(){
$("input[name=myList]").on("click",function(){
$("input[name=myList]:not(:checked)").each(function() {
console.log($(this).val());
});
});
});
<div id="myCheckboxList">
<input type="checkbox" name="myList" value="1" checked>1
<input type="checkbox" name="myList" value="2" checked>2
<input type="checkbox" name="myList" value="3" checked>3
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Another solution is to add an "onclick" method in your html. This will call a javascript function whenever the checkbox is clicked. That function can contain any logic for your checkboxes.
<input type="checkbox" name="myList" value="1" checked onclick="checkboxChangeEvent();">1
Then you can implement your javascript function to return a list of unchecked boxes or find the input boxes by name and return the alert as in previous answers.
function checkboxChangeEvent(){
$boxes = $('input[name=myList]:not(:checked)');
$boxes.each(function() {
alert($(this).val());
});
}
Try like this:
$(function(){
$("input[name=myList]").on("click",function(){
var uncheck=[];
//console.log("triggered");
//code here to find which ones are unchecked
$boxes = $("input[name=myList]:not(:checked)");
$boxes.each(function(){
// Do stuff with for each unchecked box
uncheck.push($(this).attr('value'))
console.log(uncheck);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myCheckboxList">
<input type="checkbox" name="myList" value="1" checked>1
<input type="checkbox" name="myList" value="2" checked>2
<input type="checkbox" name="myList" value="3" checked>3
</div>

Displaying particular values on radio select

I'm trying to display particular forms on the selection of particular radio buttons.
Here are the radio buttons :-
<input type="radio" name="condition" value="working" id="condition">
<input type="radio" name="condition" value="workingdamaged" id="condition">
<input type="radio" name="condition" value="notworking" id="condition">
When we select the working radio, a different form needs to be opened up. When we select nonworking a different form needs to be there.
Originally, I was doing it via document.getElementById("demo").innerHTML , but, I was suggested that using too much forms within the innerHTML is not a good idea.
Then what is the best way by which I complete this task?
Any suggestions are welcome.
The simplest way I can think of is using data attributes for referring to the corresponding form elements from the radio button selected.
All we have to do is map a radio button with 'data-form="working"' to a particular form with id 'working'
The sample code looks like:
$("form").hide();
$("input:radio").on("change", function() {
$("form").hide();
$("#" + $(this).attr("data-form") ).show();
});
The html markup should look like:
<input type="radio" data-form="working" value="working" name="condition">
<input type="radio" data-form="workingdamaged" value="workingdamaged" name="condition">
<input type="radio" data-form="notworking" value="notworking" name="condition">
<form id="working">
<h2>working form</h2>
</form>
<form id="workingdamaged">
<h2>workingdamaged form</h2>
</form>
<form id="notworking">
<h2>notworking form</h2>
</form>
Fiddle Demo
Your solution is fine and I don't see any major problems with it.
You can also add all forms to DOM, and switch their visibility.
For instance:
<form id="form-working" style="display: none"></form>
<form id="form-workingdamaged" style="display: none"></form>
<form id="form-notworking" style="display: none"></form>
<input type="radio" name="condition" value="working" id="condition-working">
<input type="radio" name="condition" value="workingdamaged" id="condition-workingdamaged">
<input type="radio" name="condition" value="notworking" id="condition-notworking">
<script>
var forms = ['working', 'workingdamaged', 'notworking'];
function switch(form) {
for (var k in forms) {
forms[k].style.display = 'none';
}
document.getElementById('form-' + name).style.display = 'block';
}
var elements = document.getElementsByName('condition');
for (var k in elements) {
elements[k].onclick = function() {
if (this.cheked) {
switch(this.getAttribute('value'));
}
}
}
</script>
EDIT: you have to change IDs of the elements. ID must be unique
Also you may consider using or external libraries for templating.
You may take a look at this question. It might serves your purpose.
Show form on radio button select
<input type="radio" name="condition" class="selectradio" value="working" selection="select1">
<input type="radio" name="condition" class="selectradio" value="workingdamaged" selection="select2">
<input type="radio" name="condition" class="selectradio" value="notworking" selection="select3">
give them different ids this
create a model like this .
<div class=content>
<div class="subcontent" style="display:none" id="select1">//content</div>
<div class="subcontent" style="display:none" id="select2">//content</div>
<div class="subcontent" style="display:none" id="select3">//content</div>
</div>
<script>
$(function(){
$('.selectradio').change(
function(){
var sourced=$(this).attr("selection") ;
$(".subcontent").hide();
$("#"+sourced).show();
}
);
});
</script>
you have to include jquery library .

how to get the value of the hidden fields in here after the radio button is clicked

Am trying to get the value of the hidden input fields on every click of a radio button. I have just posted a single div. I have a multiple div with same structure. I have successfully obtained the value of radio button but I want to get the value of hidden input now.
<div class="QA">
<h1> First Question</h1>
<input type="radio" id="check" name="q" value="A">Options 1</input>
<input type="radio" id="check" name="q" value="B">Options 2</input>
<input type="radio" id="check" name="q" value="C">Options 3</input>
<input type="radio" id="check" name="q" value="D">Options 4</input>
<input type="hidden" id="result" value="B" />
<br/>
<div id="result"></div>
</div>
<script>
$(document).ready(function() {
$("input:radio").change(function() {
checkResult(this);
});
});
function checkResult(el)
{
$this=$(el).parent("div.QA");
$this.slideUp();
}
</script>
Maybe you could try removing the hidden input entirely and indicate the correct answer using a data-* attribute. Something like:
<div class="QA" data-answer="B">
Then in your checkResult function you could retrieve this value using
function checkResult(el)
{
$this=$(el).parent("div.QA");
var answer = $this.data("answer");
$this.slideUp();
}
function checkResult(el)
{
$this = $(el).parents("div.QA");
$this.slideUp();
var x = $this.find('#result').val(); //find value of hidden field in parent div
}
Change your markup
multiple id's should not be used. Use class instead.
<input type="radio" id="check" name="q" value="A">Options 1</input>
to
<input type="radio" class="check" name="q" value="A">Options 1</input>
var $hidden=$(el).siblings("input[type='hidden']");
BTW you have lot of elements with same ID, not good
You can get the value of the hidden element by it's id.
var hiddenValue = $("#result").val();
You can use this in hidden function
function checkResult(el)
{
var hiddenValue = $("#result").val();
alert(hiddenValue);
}

javascript to jquery conversion for a code that is working fine for dynamic appearance and disappearance of a text field with radio buttons

guys I tried a lot for this code but nothing come up for conversion from javascript to jquery..
This code is irrelevant cuz u find this in working fiddle.. I added this chunk of code cuz stackoverflow dont allow me to post without a code..
<div class="rButtons">
<input type="radio" name="numbers" value="10" onclick="uncheck();" />10
<input type="radio" name="numbers" value="20" onclick="uncheck();" />20
<input type="radio" name="numbers" value="other" onclick="check(this);"/>other
<input type="text" id="other_field" name="other_field" onblur="checktext(this);"/>
</div>
Check this fiddle
http://jsfiddle.net/gDxqj/
It is working well. on clicking "other" radio button the text field comes up and on clicking any other radio button it disappears.. This is the function of this script and it is working well..
Now when i tried changing it to jquery code it died.. I can show what code i made in jquery but to no help..
Fiddle for the same will help a lot..
Thanks in advance..
This is what i did
<script>
var $radios = $('input:radio[name=numbers]');
if ($radios.is(':checked') === true) {
$("#other_field").show();
}
else
{
$("#other_field").hide();
}
</script>
I put it put that in a function and invoke it in "onchange" of radiobutton but not worked
$(':radio').on('change', function () {
$('#other_field')[$(this).val() === 'other' ? 'show' : 'hide']();
});
$('#other_field').on('blur', function () {
var val = $(this).val();
if(isNaN(val)) {
alert('only numbers are allowed..');
}
else if(parseInt(val, 10) % 10 > 0) {
alert('only multiples of 10..');
}
});
with:
<div class="rButtons">
<input type="radio" name="numbers" value="10" /> 10
<input type="radio" name="numbers" value="20" /> 20
<input type="radio" name="numbers" value="other" />other
<input type="text" id="other_field" name="other_field" />
</div>
demo: http://jsfiddle.net/BZGsw/
You just need to remove the onclick and onblur from your inputs and attach the events through jQuery:
$(function(){
$('.rButtons').on('click', 'input[type="radio"]', function(ev){
var val = $(this).val();
val == 'other' ? check(this) : uncheck();
});
$('.rButtons').on('blur', '#other_field', function(ev){
checktext(this);
});
});
See Demo
You can use .change() to bin the change event to check the state of the selected radio button then apply .toggle() on #other_field to show or hide it.
#other_field {
display: none;
}
<div class="rButtons">
<input type="radio" name="numbers" value="10">10
<input type="radio" name="numbers" value="20">20
<input type="radio" name="numbers" value="other">other
<input type="text" id="other_field" name="other_field">
</div>
$("[name=numbers]").change(function() {
$("#other_field").toggle(this.value === "other");
});
$("#other_field").change(checktext);
I modified your CSS to use display set to none instead of visibility.
See it here.

Categories