Good and CLEAN way to check this? (JS + HTML) - javascript

I am trying to make a system that will check what radio button is pushed. (Side note there WILL always be 1 checked.) The code I have so far is rather lacking and I'm not entirely sure how to improve. Any help??
NOTE: I have multiple 'systems' that look just like this, so I'll give you just 1 chunk. That being said, there are multiple chunks like this. I need a way to make this easy on my end.
HTML:
<div class="panel">
<div class="panel-header">Storage</div>
<div class="panel-body">
<div class="container-fluid">
<div class="row">
<div class="col-sm-4 col-md-2">
<input name="STORAGE" type="radio" id="STORAGE" checked>
<label class="radio" for="STORAGE">
<center>
<img src="../images/Parts/Western_Digital_Caviar_Blue_320GB.png" class="comp-img"><br><br>
<p>320GB Western Digital Caviar Blue 3.5" 7200RPM HDD</p>
</center>
</label>
</div>
<div class="col-sm-4 col-md-2">
<input name="STORAGE" type="radio" id="STORAGE2">
<label class="radio" for="STORAGE2">
<center>
<img src="../images/Parts/Western_Digital_Caviar_Blue_320GB.png" class="comp-img"><br><br>
<p>500GB Western Digital WD5000AAKX 3.5" 7200RPM HDD</p>
<p class="money">+$55</p>
</center>
</label>
</div>
<div class="col-sm-4 col-md-2">
<input name="STORAGE" type="radio" id="STORAGE3">
<label class="radio" for="STORAGE3">
<center>
<img src="../images/Parts/Western_Digital_Caviar_Blue_320GB.png" class="comp-img"><br><br>
<p>1TB Western Digital WD10EZEX 3.5" 7200RPM HDD</p>
<p class="money">+$55</p>
</center>
</label>
</div>
</div>
<div class="row">
<div class="col-sm-4 col-md-2">
<input name="SSD" type="radio" id="SSD" checked>
<label class="radio" for="SSD">
<center>
<img src="../images/Parts/None.png" class="comp-img"><br><br>
</center>
</label>
</div>
<div class="col-sm-4 col-md-2">
<input name="SSD" type="radio" id="SSD2">
<label class="radio" for="SSD2">
<center>
<img src="../images/Parts/A-DATA_SSD.png" class="comp-img"><br><br>
<p>120GB A-Data ASP550SS3-120GM-C SSD</p>
<p class="money">+$40</p>
</center>
</label>
</div>
</div>
</div>
</div>
</div>
JS:
function Check(){
if(document.getElementById('STORAGE3').checked & HDD3Clicked==0){
if (HDD2Clicked>0) {
HDD2Clicked = 0;
HDD3Clicked = 1;
}else{
HDD3Clicked = 1;
Adding(+55);
console.log("Adding");
}
}else if (document.getElementById('STORAGE2').checked & HDD2Clicked==0) {
if (HDD3Clicked>0) {
HDD2Clicked = 1;
HDD3Clicked = 0;
}else{
HDD2Clicked = 1;
Adding(+55);
console.log("Adding");
}
}else if (document.getElementById('STORAGE').checked & HDD3Clicked>0) {
HDD3Clicked = 0;
Adding(-55);
console.log("Subtracting");
}else if(document.getElementById('STORAGE').checked & HDD2Clicked>0){
HDD2Clicked = 0;
Adding(-55);
console.log("Subtracting");
}
setTimeout(function() {Check()}, 5000);
}

If you can use jQuery it's fairly simple...
var clickedID;
$(document).ready(function(){
$('radio').on('click'),function(){
clickedID = $(this).attr("id");
});
});
That will give you the id of whichever radio element has been clicked. Then you can do with it what you'd like.

var radioButtons = selectorQueryAll("input[type=radio]:checked");
for (button in radioButtons) {
console.log(button.id);
}
1) Return all checked radio buttons
2) Output their ID to console.

If you don't want to use jQuery, this is a pure javascript solution:
<input type="radio" name="radioGroup" onclick="handleClick(this);" value="1"/>
<input type="radio" name="radioGroup" onclick="handleClick(this);" value="2" />
<script>
var handleClick = function(e){
alert(e.value);
}
</script>

Related

Onclick mutiple switch button not working

Here I want to add multiple switch buttons on the same page. I had added but querySelector is not working. Can anyone guide me on what might be the reason the switch is not working.
allOnOffButtons = document.querySelectorAll("div.case-inner-info input");
allOnOffButtons.forEach(button => {
button.addEventListener('click', handleVisibility);
})
function handleVisibility(e) {
// check if the button was on or off
const clickedButtonId = e.srcElement.id;
const clickedinnerDiv = e.srcElement.closest(".case-inner-info").querySelector(".inner_div");
// find all divs inside the given inner_div
const allDivsInsideInnerDiv = clickedinnerDiv.querySelectorAll("div");
// check if they should be shown or hidden
allDivsInsideInnerDiv.forEach(div => {
if (div.id === clickedButtonId) {
div.style.display = "block";
} else {
div.style.display = "none";
}
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="case-inner-info">
<div class="case-switch-wrap">
<div class="inner_div">
<div class="case-info" id="on">
<p> Paragrapgh1</p>
</div>
<div class="case-code-wrap" style="display: none;" id="off">
<p> Paragrapgh2</p>
</div>
</div>
<div class="case-switch">
<input type="radio" class="switch-input" id="on" checked>
<label for="on" class="switch-label switch-label-on">On</label>
<input type="radio" class="switch-input" id="off">
<label for="off" class="switch-label switch-label-off">Off</label>
<span class="switch-selection"></span>
</div>
</div>
</div>
<div class="case-inner-info">
<div class="case-switch-wrap">
<div class="inner_div">
<div class="case-info" id="on1">
<p> Paragrapgh1</p>
</div>
<div class="case-code-wrap" style="display: none;" id="off1">
<p> Paragrapgh2</p>
</div>
</div>
<div class="case-switch">
<input type="radio" class="switch-input" id="on1" checked>
<label for="on1" class="switch-label switch-label-on">On</label>
<input type="radio" class="switch-input" id="off1">
<label for="off1" class="switch-label switch-label-off">Off</label>
<span class="switch-selection"></span>
</div>
</div>
</div>
The jQuery import wasn't needed, so I removed it. You can easily get the relative paths to switch your display using data-attributes (I used data-ref) instead of IDs with:
e.target.closest('.case-inner-info')
.querySelectorAll('.inner_div [data-ref]')
.forEach(i => i.style.display = i.dataset.ref === e.target.dataset.ref ? 'block' : 'none');
const handleVisibility = (e) => {
e.target.closest('.case-inner-info').querySelectorAll('.inner_div [data-ref]').forEach(i => i.style.display = i.dataset.ref === e.target.dataset.ref ? 'block' : 'none');
}
const allOnOffButtons = document.querySelectorAll("div.case-inner-info input");
allOnOffButtons.forEach(button => {
button.addEventListener('click', handleVisibility);
})
<div class="case-inner-info">
<div class="case-switch-wrap">
<div class="inner_div">
<div class="case-info" data-ref="on">
<p> Paragrapgh1</p>
</div>
<div class="case-code-wrap" style="display: none;" data-ref="off">
<p> Paragrapgh2</p>
</div>
</div>
<div class="case-switch">
<label class="switch-label switch-label-on">
<input type="radio" class="switch-input" name="switch-toggle" data-ref="on" checked>
On</label>
<label class="switch-label switch-label-off">
<input type="radio" class="switch-input" name="switch-toggle" data-ref="off">
Off</label>
<span class="switch-selection"></span>
</div>
</div>
</div>
<div class="case-inner-info">
<div class="case-switch-wrap">
<div class="inner_div">
<div class="case-info" data-ref="on">
<p> Paragrapgh1</p>
</div>
<div class="case-code-wrap" style="display: none;" data-ref="off">
<p> Paragrapgh2</p>
</div>
</div>
<div class="case-switch">
<label class="switch-label switch-label-on">
<input type="radio" class="switch-input" name="switch-toggle" data-ref="on" checked>
On</label>
<label class="switch-label switch-label-off">
<input type="radio" class="switch-input" name="switch-toggle" data-ref="off">
Off</label>
<span class="switch-selection"></span>
</div>
</div>
</div>

JavaScript show/hide div based on radio button. First instance conflicts with other one. When I select true/false on one, it applies to both

I would like it to function separately. I've been toying with this for a while, and I have tried putting them in separate tags, changing the $(this).attr("value") to $(this).attr("name"), and applying the changes in the HTML, but I cannot figure out how I would fix this. I am using ASP.NET MVC, with jquery-3.5.1.
Note: This is not the entire file, only the relevant parts. If I am incorrect about something and the whole file is needed, it is here: https://pastebin.com/YXp1Msj3.
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<div>
<script>
$(document).ready(function () {
$('input[type="radio"]').click(function () {
var inputValue = $(this).attr("value");
var targetBox = $("." + inputValue);
$(".box").not(targetBox).hide();
$(targetBox).show();
});
});
</script>
<div>
<span>Enable Two Factor Authentication? (Strongly Recommended) </span>
<label><input id="TwoFactorEnabled" type="radio" name="TwoFactorEnabled" value="true"> Yes</label>
<label><input id="TwoFactorEnabled" type="radio" name="TwoFactorEnabled" value="false"> No</label>
</div>
<div style="display:none" class="true box">
<span>What implementation of 2FA would you like?</span>
<select class="form-control" id="TotpEnabled" name="TotpEnabled">
<option value="true">Google Authenticator</option>
<option value="false">Email</option>
</select>
</div>
<div style="display:none" class="false box">
<label>If you choose not to enable Two Factor Authentication, you can turn it on later by visiting account settings.</label>
</div>
</div>
<!--End JQUERY magic/start of next-->
<div>
<script>
$(document).ready(function () {
$('input[type="radio"]').click(function () {
var inputValue = $(this).attr("value");
var targetBox = $("." + inputValue);
$(".box").not(targetBox).hide();
$(targetBox).show();
});
});
</script>
<div>
<label><input id="CoachEnabled" type="radio" name="athlete" value="false"> Athlete</label>
<label><input id="CoachEnabled" type="radio" name="coach" value="true"> Coach</label>
</div>
<div style="display:none" class="true box">
<div class="form-group">
<label asp-for="CoachCode"></label>
<input asp-for="CoachCode" class="form-control" />
<span asp-validation-for="CoachCode" class="text-danger"></span>
</div>
</div>
<div style="display:none" class="false box">
<!--code left in case needed in future-->
</div>
<!--End JQUERY-->
<div>
How about putting each block in a div having same class, here i have used js_option_container and using closest() to select closest parent, so that it can show or hide only div inside that container
$(document).ready(function() {
$('input[type="radio"]').click(function() {
var inputValue = $(this).attr("value");
var targetBox = $("." + inputValue);
$(this).closest(".js_option_container").find(".box").not(targetBox).hide();
$(this).closest(".js_option_container").find(targetBox).show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div class="js_option_container">
<div>
<span>Enable Two Factor Authentication? (Strongly Recommended) </span>
<label><input id="TwoFactorEnabled" type="radio" name="TwoFactorEnabled" value="true"> Yes</label>
<label><input id="TwoFactorEnabled" type="radio" name="TwoFactorEnabled" value="false"> No</label>
</div>
<div style="display:none" class="true box">
<span>What implementation of 2FA would you like?</span>
<select class="form-control" id="TotpEnabled" name="TotpEnabled">
<option value="true">Google Authenticator</option>
<option value="false">Email</option>
</select>
</div>
<div style="display:none" class="false box">
<label>If you choose not to enable Two Factor Authentication, you can turn it on later by visiting account settings.</label>
</div>
</div>
<div class="js_option_container">
<div>
<label><input id="CoachEnabled" type="radio" name="game" value="false"> Athlete</label>
<label><input id="CoachEnabled" type="radio" name="game" value="true"> Coach</label>
</div>
<div style="display:none" class="true box">
<div class="form-group">
<label asp-for="CoachCode"></label>
<input asp-for="CoachCode" class="form-control" />
<span asp-validation-for="CoachCode" class="text-danger"></span>
</div>
</div>
<div style="display:none" class="false box">
<!--code left in case needed in future-->
<span>Hello world</span>
</div>
<!--End JQUERY-->
<div>

How do i find the selected id and name of radiobutton list

How do I find the selected id of radiobutton in list.
Here is the radiobutton:
<input name="1" id="1" type="radio">
Radiobutton are dynamics.
Here is the dynamic radio button list.
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>1. Here is the question??</label>
<div class="icheck-list">
<label class="icheck-list" id="1">
<input name="1" id="1" type="radio">Strongly Disagree
<span></span>
</label>
</div>
<div class="icheck-list">
<label class="icheck-list" id="2">
<input name="1" id="2" type="radio">Disagree
<span></span>
</label>
</div>
<div class="icheck-list">
<label class="icheck-list" id="3">
<input name="1" id="3" type="radio">Neither Agree or Disagree
<span></span>
</label>
</div>
<div class="icheck-list">
<label class="icheck-list" id="4">
<input name="1" id="4" type="radio">Agree
<span></span>
</label>
</div>
<div class="icheck-list">
<label class="icheck-list" id="5">
<input name="1" id="5" type="radio">Strongly Agree
<span></span>
</label>
</div>
</div>
</div>
</div>
There is 5 possible answers for a question.
I am using mvc 4.
For next question the i.e. for question 2.
The answer radiobutton is just like
<input name="2" id="11" type="radio">Strongly Disagree
So how do I find the selected radio button id and name???
here is the html i am using in view page.
<div class="tab-pane active" id="tab1">
#foreach (var items in Model.ParentList)
{
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>#items.QuestionText</label>
#foreach (var ch in Model.ChildList)
{
if (items.QuestionId == ch.QuestionId)
{
<div class="icheck-list">
<label class="icheck-list" id="#ch.AnswerId">
#*<input type="checkbox"> #Html.DisplayFor(model => model.Answers[j].AnswerText)*#
<input name="#ch.QuestionId" id="#ch.AnswerId" type="radio">#ch.AnswerText
<span></span>
</label> </div>
}
}
</div>
</div>
}
</div>
there is total 10 questions and each questions having 5 multiple choice answers.
so Model.ParentList i got total 10 questions with id
in Model.ChildList i got 50 answers.
so how do i bind and got the selected radio button value??
This piece of code will return the value of the checked radio button in jQuery:
$('input[name=<name of radio>]:checked').val();
In your case with a radio named '1' it would be:
$('input[name=1]:checked').val();
I hope I have understood the question correctly, and that this might be of use for you.
Please use value instead of id with each input, then you can try below code
$('input[type=radio]').on('change',function(event){
console.log($(this).val());
});
First attach an event listener which detects the change in selection.
jQuery( "input[name='1']" ).on( "click", function() {
var id = jQuery(this).attr("id");
var name = jQuery(this).attr("name");
alert("Id:"+ id);
alert("Name: "+name);
});
A similar method can be used where input[name='2']

Increment input name using javascript

I have a div with some radio buttons, and the input names are cty_1. If i add more div the input names inside that divs should become cty_2, cty_3, etc.respectively.
Here's my code:
<div class="category">
<div class="col-md-6">
<input type="radio" name="cty_1" id="1" value="car">
<label for="1">car</label>
</div>
<div class="col-md-6">
<input type="radio" name="cty_1" id="2" value="bike">
<label for="2">bike</label>
</div>
</div>
If another div is added, i want that like
<div class="category">
<div class="col-md-6">
<input type="radio" name="cty_1" id="1" value="car">
<label for="1">car</label>
</div>
<div class="col-md-6">
<input type="radio" name="cty_1" id="2" value="bike">
<label for="2">bike</label>
</div>
</div>
<div class="category">
<div class="col-md-6">
<input type="radio" name="cty_2" id="3" value="phone">
<label for="3">phone</label>
</div>
<div class="col-md-6">
<input type="radio" name="cty_2" id="4" value="computer">
<label for="4">computer</label>
</div>
</div>
NB: i don't know javascript.
If you're using jQuery then this is pretty easy. Using the following code, every time you click "Go" a new category element will be appended and the name and id attributes will increment:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<body>
<div class="container">
<btn class="btn btn-primary">Go</btn>
<div class="category">
<div class="col-md-6">
<input type="radio" name="cty_1" id="1" value="car">
<label for="1">car</label>
</div>
<div class="col-md-6">
<input type="radio" name="cty_1" id="2" value="bike">
<label for="2">bike</label>
</div>
</div>
</div>
</body>
<script>
$('.btn-primary').on('click',function(){
var idx = parseInt($('.category').last().index())+1;
$('.category')
.last()
.clone()
.find('input[type=radio]')
.each(function(index){
$(this)
.attr('name','cty_' + idx)
.attr('id','cty_' + idx + "_" + index)
.parent()
.find('label')
.attr('for','cty_' + idx + "_" + index)
.end()
})
.end()
.insertAfter($('.category').last());
});
</script>
Try this: updated fiddle
//Html
<div id="divMain">
</div>
//jQuery Code
var valuesArr=["car","bike","truck","Test4","Test5"];
var cityCounter=1;
var idCounter=1;
var addCategoryFlag=false;
function CallHtml(){
var html="";
for(var i=0;i<valuesArr.length;i++){
if(idCounter%2!=0){
html+='<div class="category">';
}
else{
addCategoryFlag=true;
}
html+='<div class="col-md-6">';
html+=' <input type="radio" name="cty_'+cityCounter+'" id="'+idCounter+'" value="'+valuesArr[i]+'">';
html+=' <label for="'+idCounter+'">'+valuesArr[i]+'</label>';
html+='</div>';
if(addCategoryFlag){
html+='</div>';
addCategoryFlag=false;
cityCounter++;
}
idCounter++;
}
$("#divMain").html(html);
}
CallHtml();

Toggle view of DIVs using javascript array and radio button

I am trying to toggle the visibility to div content using javascript, not jquery. I can get it to work using a huge else if, but I am trying to use a for loop.
HTML
<fieldset >
<legend>Please indicate below how you intend to pay any pick-related charges for you shipments.</legend>
<div >
<input id="repl_id" name="repl_name" type="radio" value="111">
<label for="repl_id" >Bill to your Account Number.</label>
</div>
<div >
<input id="repl_id" name="repl_name" type="radio" value="222">
<label for="repl_id" >Bill to a paymentcard.</label>
</div>
<div >
<input id="repl_id" name="repl_name" type="radio" value="333">
<label for="repl_id" >Bill to the reciever or a third party.</label>
</div>
<div >
<input id="repl_id" name="repl_name" type="radio" value="444">
<label for="repl_id" >Pay with check or money order.</label>
</div>
<div >
<input id="repl_id" name="repl_name" type="radio" value="555">
<label for="repl_id" >Pay with cash.</label>
</div>
</fieldset>
<div id="111"><p>This is 111</p></div>
<div id="222"><p>This is 222</p></div>
<div id="333"><p>This is 333</p></div>
<div id="444"><p>This is 444</p></div>
<div id="555"><p>This is 555</p></div>
Javascript
$(":input[type='radio']").on("change", function () {
var choice =[111,222,333,444,555];
if ($(this).prop("checked")) {
for(i=0; i<=choice.length; i++){
if($(this).val() === choice[i]){
$("#"+i).show();
} else {
$("#"+i).hide();
}
}
}
The problem I am having is that it does not seem to recognize the index of the array I am iterating through. So it always reads false. No JQuery please.
Demo - https://jsfiddle.net/of3gm5h8/1/
HTML
<fieldset>
<legend>Please indicate below how you intend to pay any pick-related charges for you shipments.</legend>
<div>
<input id="repl_id" name="repl_name" type="radio" value="111">
<label for="repl_id">Bill to your Account Number.</label>
</div>
<div>
<input id="repl_id" name="repl_name" type="radio" value="222">
<label for="repl_id">Bill to a paymentcard.</label>
</div>
<div>
<input id="repl_id" name="repl_name" type="radio" value="333">
<label for="repl_id">Bill to the reciever or a third party.</label>
</div>
<div>
<input id="repl_id" name="repl_name" type="radio" value="444">
<label for="repl_id">Pay with check or money order.</label>
</div>
<div>
<input id="repl_id" name="repl_name" type="radio" value="555">
<label for="repl_id">Pay with cash.</label>
</div>
</fieldset>
<div id="111" class="hide">
<p>This is 111</p>
</div>
<div id="222" class="hide">
<p>This is 222</p>
</div>
<div id="333" class="hide">
<p>This is 333</p>
</div>
<div id="444" class="hide">
<p>This is 444</p>
</div>
<div id="555" class="hide">
<p>This is 555</p>
</div>
JS
$(function() {
$('.hide').hide();
$("input[type='radio']").on("change", function() {
// Hide all the .hide divs
$('.hide').hide();
var checked = $(this).val();
if (checked == "111") {
$("#111").show();
} else if (checked == "222") {
$("#222").show();
} else if (checked == "333") {
$("#333").show();
} else if (checked == "444") {
$("#444").show();
} else if (checked == "555") {
$("#555").show();
}
});
});
I think this is what you're looking for.
//removed the colon before input
$("input[type='radio']").on("change", function () {
var choice =[111,222,333,444,555];
if ($(this).prop("checked")) {
//get the value of the checked input
var value = $(this).val();
//match the index to the input and show it, hide the others.
$('#'+value).show().siblings().hide();
}
}
This assumes that the choice array has all the values from the the inputs.
Make sure the id's of the radio buttons are unique.(You already have the same name for the radio button to make it behave like a group.)
Then target the div using the value of the radio button.
JS
$(":input[type='radio']").on("change", function() {
// Hide all the divs
$('.div-container div').hide();
if ($(this).prop("checked")) {
$("#" + $(this).val()).show();
}
});
HTML
<fieldset>
<legend>Please indicate below how you intend to pay any pick-related charges for you shipments.</legend>
<div>
<input id="repl_id1" name="repl_name" type="radio" value="111">
<label for="repl_id1">Bill to your Account Number.</label>
</div>
<div>
<input id="repl_id2" name="repl_name" type="radio" value="222">
<label for="repl_id2">Bill to a paymentcard.</label>
</div>
<div>
<input id="repl_id3" name="repl_name" type="radio" value="333">
<label for="repl_id3">Bill to the reciever or a third party.</label>
</div>
<div>
<input id="repl_id4" name="repl_name" type="radio" value="444">
<label for="repl_id4">Pay with check or money order.</label>
</div>
<div>
<input id="repl_id5" name="repl_name" type="radio" value="555">
<label for="repl_id5">Pay with cash.</label>
</div>
</fieldset>
<div class="div-container">
<div id="111">
<p>This is 111</p>
</div>
<div id="222">
<p>This is 222</p>
</div>
<div id="333">
<p>This is 333</p>
</div>
<div id="444">
<p>This is 444</p>
</div>
<div id="555">
<p>This is 555</p>
</div>
</div>
Check Fiddle

Categories

Resources