Showing <p> when radio button selected - javascript

I'm quite new to JS + HTML but basically i want 4 radio buttons, each with a different name like this
o PS4
o Xbox
o Nintendo DS
When one of these is clicked/checked, i want to output the price which will be held in a "p" next to them, as shown
o PS4 £400
""
""
The price is then hidden when the next is clicked, and the corresponding price for that is then shown, ive spent hours and hours trying to search for this and test things, but nothing seems to work, so ANY help is greatly appreciated
Thanks,
Dan

Here is a plain JavaScript example:
<form id="form">
<label>
<input name="console" type="radio" value="400">PS4</label>
<label>
<input name="console" type="radio" value="350">XBox</label>
<label>
<input name="console" type="radio" value="200">Nintendo DS</label>
</form>
<br>
<div>Price:
<div id="price"></div>
</div>
JavaScript (Using ES6)
document.getElementById('form').addEventListener('change', () => {
const radios = document.getElementsByName('console');
Object.keys(radios).forEach((obj, i) => {
if (radios[i].checked) {
price = document.getElementById('price');
price.innerHTML = `<p>£${radios[i].value}</p>`;
}
});
});
Sample:
JsFiddle

Here is the code that works perfectly fine:
$(document).ready(function(){
$(".price").hide();
$("input").click(function(){
$(".price").hide();
$(this).siblings().show();
});
});
<form id="form">
<span>
<input type="radio" name="drink" value="vodka"/>Vodka <span class="price">$40</span><br />
</span>
<span>
<input type="radio" name="drink" value="beer"/>Beer <span class="price">$50</span><br />
</span>
<span>
<input type="radio" name="drink" value="juice"/>Juice <span class="price">$20</span><br />
</span>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
or try this jsfiddle directly here:
https://jsfiddle.net/balyancoder/dbgkfw0f/

Here is an example using plain javascript and paragraph tag along with every radio button:
HTML:
<ul>
<li class="element"><input type="radio" class="radio_btn" name="my_radio">my radio 1
<p class="parag">price 1</p>
</li>
<li class="element"><input type="radio" class="radio_btn" name="my_radio">my radio 2
<p class="parag">price 2</p>
</li>
<li class="element"><input type="radio" class="radio_btn" name="my_radio">my radio 3
<p class="parag">price 3</p>
</li>
<li class="element"><input type="radio" class="radio_btn" name="my_radio">my radio 4
<p class="parag">price 4</p>
</li>
</ul>
Javascript:
var radios = document.getElementsByClassName("radio_btn");
for (var i = 0; i < radios.length; i++) {
radios[i].addEventListener(
'click',
function() {
var parags = document.getElementsByClassName("parag");
for (var i = 0; i < parags.length; i++) {
parags[i].style.display = "none";
}
this.nextElementSibling.style.display = "inline-block";
}
);
}
Here is the sample on JSFiddle

Related

Show next div when button pressed

I am trying to create a list with five list items. By default there is only the first item shown and if i press a button "Next one" it shows next list item (and so on).
After reaching to the last item button shoud be disabled because there is no list items left.
How can i achieve this kind of behavior?
I have found this example here: JavaScript - show next div and hide previous
but this one hides previous one.
Maybe it can be combined with "addclass" function to add class ul siblings that haveent got a class?
Thanks for help.
According with the link you attach, if you use the same code and removes the line qElems[i].style.display = 'none'; it works as you like. But will be better if you learn javascript before coding.
Complete example (extracted from JavaScript - show next div and hide previous with some editions )
var showing = [1, 0, 0];
var questions = ['q0', 'q1', 'q2'];
function next() {
var qElems = [];
for (var i = 0; i < questions.length; i++) {
qElems.push(document.getElementById(questions[i]));
}
for (var i = 0; i < showing.length; i++) {
if (showing[i] == 1) {
showing[i] = 0;
if (i == showing.length - 1) {
document.getElementById("buttonNext").disabled = "disabled";
} else {
qElems[i + 1].style.display = 'block';
showing[i + 1] = 1;
}
break;
}
}
}
<div id="questions">
<div id="q0">
<h3>1. The color of the sky is... </h3>
<input type="radio" name="question0" value="A">Green<br>
<input type="radio" name="question0" value="B">Blue<br>
<input type="radio" name="question0" value="C">Red<br>
<input type="radio" name="question0" value="D">Purple<br>
</div>
<div id="q1" style="display: none">
<h3>2. Paper comes from... </h3>
<input type="radio" name="question1" value="A">Water<br>
<input type="radio" name="question1" value="B">Cement<br>
<input type="radio" name="question1" value="C">Trees<br>
<input type="radio" name="question1" value="D">The Sky<br>
</div>
<div id="q2" style="display: none">
<h3>3. How many hours in a day? </h3>
<input type="radio" name="question2" value="A">24<br>
<input type="radio" name="question2" value="B">22<br>
<input type="radio" name="question2" value="C">16<br>
<input type="radio" name="question2" value="D">48<br>
</div>
</div>
<button onclick="next()" id="buttonNext">Next Question</button>
I just made it using jquery:
$(document).on('click','button.next', function(){
var childID = $('#list li').index($('li.display'));
$('#list li:eq(' + childID + ')').toggleClass('display')
$('#list li:eq(' + ( childID + 1 ) + ')').toggleClass('display')
})
li{
display: none;
}
li.display{
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="list">
<li class="display">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<button class="next">Next One</button>
Here is the HTML in which you create a list of five items, with first item is displayed by default and the rest is hidden.
html code
<div class='demo'>1</div>
<div class='demo' style='display:none;'>2</div>
<div class='demo' style='display:none;'>3</div>
<div class='demo' style='display:none;'>4</div>
<button class='next'>Next</button>
Here the button in action is next whenever you click the next button, it displays the next list item i.e on first click it would display second item and hides the rest. This will go on until the length of your list.
js code
var n = 2
$('.next').click(function(e){
$('.demo').hide();
$('.demo:nth-child('+n+')').show();
var demo_l = $('.demo').length;
if(n == demo_l){
$('.next').attr('disabled', 'disabled');
}
n++;
});
Here is the jsfiddle

show one div and hide another div onclick of list of checkboxes

div1 = Top 10 Listings
div2 = Send Selected
am looking for functionality that will be having n no. of contacts each with a checkbox when checkbox checked div2 has to be displayed otherwise div1 should have to be displayed... Am entirely new to this forum sry if my qtn is confusing below is what I've achieved upto now... http://jsfiddle.net/0p5cf4be/
now checkbox is working as a toggle
but I need that div2 to display if one/multiple checkbox checked it should stay at div2
at default it should have to show div1
if no checkbox is checked then it have to show div1
<script>
x=false;
function Check(){
if(x){
document.getElementById("div1").style.display='inline';
document.getElementById("div2").style.display='none';
x=false;
}
else{
document.getElementById("div1").style.display='none';
document.getElementById("div2").style.display='inline';
x=true;
}
}
</script>
<div>
<h2>Top 10 Listings</h2>
<h2>Send Selected</h2>
</div>
<div class="contacts">
Contact 1<input type="checkbox" id="check" onclick="Check()">
<br>
Contact 2<input type="checkbox" id="check" onclick="Check()">
<br>
Contact 3<input type="checkbox" id="check" onclick="Check()">
</div>
What about using jquery to manage the state of div2 based on the state of the checkboxes:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div>
<a href="#" id="div1">
<h2>Top 10 Listings</h2> </a>
<a href="#" id="div2" style="display: none;">
<h2>Send Selected</h2> </a>
</div>
<div class="contacts">
Contact 1<input type="checkbox" id="check1">
<br>
Contact 2<input type="checkbox" id="check2">
<br>
Contact 3<input type="checkbox" id="check2">
</div>
<script>
var allCheckboxes = $("input[type=checkbox]");
allCheckboxes.click(
function () {
var showSendSelected = $("input[type=checkbox]:checked").length > 0;
var sendSelectedLink = $("#div2");
if (showSendSelected) {
sendSelectedLink.show();
} else {
sendSelectedLink.hide();
}
}
);
</script>
Since you have used jQuery tag, use a jQuery handler like
jQuery(function($) {
var $checks = $('.contacts input:checkbox').click(function() {
var checked = $checks.is(':checked');
$('#div1').toggle(!checked);
$('#div2').toggle(checked);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<h2>Top 10 Listings</h2>
<h2>Send Selected</h2>
</div>
<div class="contacts">
Contact 1<input type="checkbox"/>
<br/>
Contact 2<input type="checkbox"/>
<br/>
Contact 3<input type="checkbox"/>
</div>
Without jQuery, you can use a counter like
var counter = 0;
function Check(el) {
if (el.checked) {
counter++;
} else {
counter--;
}
document.getElementById("div1").style.display = counter ? 'none' : 'block';
document.getElementById("div2").style.display = counter ? 'block' : 'none';
}
<div>
<h2>Top 10 Listings</h2>
<h2>Send Selected</h2>
</div>
<div class="contacts">
Contact 1<input type="checkbox" onclick="Check(this)"/>
<br/>
Contact 2<input type="checkbox" onclick="Check(this)"/>
<br/>
Contact 3<input type="checkbox" onclick="Check(this)"/>
</div>
Since you have tagged JQUERY try this,
function Check()
{
var y=$("input[type='checkbox']:checked").length;
if(y!=0)
{
document.getElementById("div2").style.display='inline';
document.getElementById("div1").style.display='none';
}
else
{
document.getElementById("div1").style.display='inline';
document.getElementById("div2").style.display='none';
}
}
Fiddle link : http://jsfiddle.net/0p5cf4be/11/

Getting all child input elements within a div

I am trying to get all the values of the input fields. The issue is all of the <input type=radio/> are dynamic and can increase or decrease at any time.
So I am starting with the main DI and going from there. The problem I have now is I am not getting the input radio buttons values.
So here are the steps I am intending to accomplish:
If any radio button is selected, pass its value to the checkbox value,
If the radio button is selected and the checkbox is not selected, do not pass to the checkbox value
I am looking for a solution in JavaScript only - do not use jQuery
Here is my jsFiddle code
HTML
<div style="display: block;" id="mymainDiv" class="fullFloat">
<input type="hidden" value="1" id="startIdxShMdeCarWisevId" name="startIdxShMdeCarWise">
<div class="subTitle">UPS<a class="fRight" onclick="localG('10',false,0,false,'UPS','1','$');" href="javascript:void(0);">Show Prices</a></div>
<div style="display:none;" id="Wheel_UPS"><div class="loadingcheckout"></div></div>
<div id="Price_UPS">
</div>
<div class="wrapLeft wrapClear">
<div class="wrapleft">
<label class="">
<input type="radio" value="11098" id="deliveryMethodId_1" name="deliveryMethodId" class="section" data-mask="" data-rev="" data-rel="false" data-carrier="">
<span>
UPS Ground (Order by 9:30 PM EST)
</span>
<div class="wrapRight">
<div id="UPS_11098">
</div>
</div>
</label>
</div>
<input type="text" value="1" id="UPS">
</div>
<input type="hidden" value="2" id="startIdxShMdeCarWisevId" name="startIdxShMdeCarWise">
<div class="subTitle">Standard<a class="fRight" onclick="localG('20',false,0,false,'Standard','2','$');" href="javascript:void(0);">Show Prices</a></div>
<div style="display:none;" id="Wheel_Standard"><div class="loadingcheckout"></div></div>
<div id="Price_Standard">
</div>
<div class="wrapLeft wrapClear">
<div class="wrapleft">
<label class="">
<input type="radio" value="11117" id="deliveryMethodId_2" name="deliveryMethodId" class="section" data-mask="" data-rev="" data-rel="false" data-carrier="">
<span>
Standard Delivery - 2-3 Day Delivery at Ground Rate (Order by 9:30 PM EST)
</span>
<div class="wrapRight">
<div id="Standard_11117">
</div>
</div>
</label>
</div>
<input type="text" value="1" id="Standard">
</div>
<input type="hidden" value="3" id="startIdxShMdeCarWisevId" name="startIdxShMdeCarWise">
<div class="subTitle">FedEx<a class="fRight" onclick="localG('190',false,0,false,'FedEx','3','$');" href="javascript:void(0);">Show Prices</a></div>
<div style="display:none;" id="Wheel_FedEx"><div class="loadingcheckout"></div></div>
<div id="Price_FedEx">
</div>
<div class="wrapLeft wrapClear">
<div class="wrapleft">
<label class="">
<input type="radio" value="11088" id="deliveryMethodId_3" name="deliveryMethodId" class="section" data-mask="" data-rev="" data-rel="false" data-carrier="">
<span>
FedEx Ground (Order by 8:00 PM EST)
</span>
<div class="wrapRight">
<div id="FedEx_11088">
</div>
</div>
</label>
</div>
<input type="text" value="1" id="FedEx">
</div>
</div>
<input type="checkbox" name="shipmode" id="shipmode" value="" onclick="getpref('mymainDiv');">Get Value
JS Code
This executes when the checkbox is clicked:
function getpref(val) {
var wr = document.getElementById(val);
childElements = wr.childNodes;
//alert(childElements);
for(var i = childElements.length-1; i>=0; i--){
var elem = childElements[i];
console.log(elem.id);
if(elem.id && elem.id.indexOf(val+'_')==0){
elem.style.display = 'block';
}
}
//alert(val);
}
You can directly access input nodes in your DIV with getElementsByTagName
function getpref(val) {
var divNode = document.getElementById(val);
var inputNodes = divNode.getElementsByTagName('INPUT');
for(var i = 0; i < inputNodes.length; ++i){
var inputNode = inputNodes[i];
if(inputNode.type == 'radio') {
//Do whatever you want
if(inputNode.checked) {
//Do whatever you want
}
}
}
}
Example: http://jsfiddle.net/88vp0jLw/1/
You can use getElementsByName to get you all of the radio buttons by name='deliveryMethodId' and then go from there:
function getpref(val) {
var radioButtons = document.getElementById(val).getElementsByName("deliveryMethodId");
for(var i = radioButtons.length-1; i>=0; i--)
{
var radioButton = radioButtons[i];
if(radioButton.checked)
console.log(radioButton.id + " is selected ");
}
}

Multiple selection checkbox values

I'm having trouble getting my var to accept more than one input.
When I select one checkbox, it shows me the value, however, when I select anymore I got an undefined error.
JavaScript
window.onload = function() {
var input= document.querySelectorAll('input#add2basket');
var radio= document.querySelectorAll('input#hi');
for (var j=0; j < radio.length; ++j){//loops over buttons
radio[j].onclick = function (){// find radio button
var input = findChecked(this.name);
alert (input.value)
return false;
// determine pizza size
//var size = input.value==='1'?‘Small':(input.value==='2'?'Regular':'Large');
// determine pizza price
//var price =Number(input.getAttribute('data‐price'));
// add a ‘new’ pizza to the basket
//addToBasket(newPizza(this.name,size, price));
};
};
function findChecked(name){
var css = 'input#hi[name="'+name+'"]';
var inputs = document.querySelectorAll(css);
var checked = _.filter(inputs, function (input){
document.write('<pre>'+input.checked+'</pre>')
return input.checked;
});
return checked.length===1?checked[0]:null;
}
}
HTML
<div>
<fieldset>
<legend class="Topping">Topping</legend>
<ul>
<li class="lastset"><input class="cbox" id="hi" name=
"top" type="checkbox" value="1"> <label class=
"box">Double Cheese</label></li>
<li class="lastset"><input class="cbox" id="hi" name=
"top" type="checkbox" value="2"> <label class=
"box">Peppers</label></li>
<li class="lastset"><input class="cbox" id="hi" name=
"top" type="checkbox" value="3"> <label class=
"box">Pepperoni</label></li>
<li class="lastset"><input class="cbox" id="hi" name=
"top" type="checkbox" value="4"> <label class=
"box">Olives</label></li>
<li class="lastset"><input class="cbox" id="hi" name=
"top" type="checkbox" value="5"> <label class=
"box">Beef</label></li>
<li class="lastset"><input class="cbox" id="hi" name=
"top" type="checkbox" value="6"> <label class=
"box">Seafood</label></li>
</ul>
</fieldset>
</div><!-- end topping -->
</form>
<div id="actionbtn">
<!--== action buttons==-->
<input class="apply" type="button" value=
"Back To Menu">
<input class="apply" name="top" id="add2basket" id="actionbtn2" type="button"
value="Proceed">
</div><!--==end of action buttons==-->
When I print the input.checked, it shows the selected boxes as true but where do i go from there
JavaScript solutions only please.
The attribute id must be unique across the whole document.
<li class="lastset"><input class="cbox" id="hi" name=
"top" type="checkbox" value="6"> <label class=
"box">Seafood</label></li>
updated code:
<li class="lastset"><input class="cbox" id="hi_1" name=
"top" type="checkbox" value="6"> <label class=
"box">Seafood</label></li>
(do this for every li and give each li its own id, if you really need an id in a li tag
To get all your inputs, use a different selector, like the class-attribute:
var css = 'input.cbox[name="'+name+'"]';
var radio= document.querySelectorAll('input.cbox');
Just select checkboxes by class name (and don't duplicate id's):
window.onload = function () {
var input = document.querySelectorAll('input#add2basket');
var radio = document.querySelectorAll('input.cbox');
for (var j = 0; j < radio.length; j++) {
radio[j].onchange = function () {
var input = findChecked(this.name);
return false;
};
};
function findChecked(name) {
var css = 'input.cbox:checked';
var inputs = document.querySelectorAll(css);
return inputs;
}
}
Pluss you can simplify selection of the checked only using :checked pseudo selector.
http://jsfiddle.net/BPFTp/1/

Javascript and HTML - onclick

Suppose I have the following code which creates two radio buttons:
<li id="foli517" class=" ">
<label class="desc" id="shippingChoice" for="Field517_0">
Shipping Options
</label>
<div>
<input id="shippingChoice" name="Field517" type="hidden" value="" />
<span>
<input id="shipping1" name="Field517" type="radio" class="field radio" value="$2.00 Shipping Fee" tabindex="13" checked="checked" />
<label class="choice" for="Field517_0" >
$2.00 Shipping Fee</label>
</span>
<span>
<input id="Field517_1" name="Field517" type="radio" class="field radio" value="I will pick up the items (free shipping)" tabindex="14" />
<label class="choice" for="Field517_1" >
I will pick up the items (free shipping)</label>
</span>
</div>
</li>
How would I implement a javascript function onclick which updates the inner html of a span with id "mySpan" with the word "FREE" when the 2nd radio button is clicked, and "NOT FREE" otherwise?
document.getElementById(WHAT GOES HERE).onclick = function() {
//what goes here?
};
document.getElementById('foli517').onchange = function(e) {
var e = e || event;
var target = e.target || e.srcElement;
var span = document.getElementById('mySpan');
var span2 = document.getElementById('mySpan2');
if (target.type === "radio") {
span.innerHTML = (target.id === "Field517_1") ? "FREE" : "NOT FREE";
}
if (target.type === "checkbox") {
span2.innerHTML = "Is it checked? " + target.checked;
}
};
Example: http://jsfiddle.net/pEYnm/2/
I would add onclick="setSpan('FREE');" and onclick="setSpan('NOT FREE');" to HTML of the respective radio buttons then add a javascript function as below that sets the HTML of the span.
function setSpan(text) {
document.getElementById('mySpan').innerHTML = text;
}
Please check Working code of Radio button on click !

Categories