I have a jsp page which shows the radio button content(on clicking it,select box will appear ) of a table.But here I'm unable select one radio button(with select box) at a time.I'm showing you the code.
<table>
<tr>
<td><input type="radio" onclick="document.getElementById('select1000').style.display=(this.checked)?'inline':'none';" name="license" value="1000"> 1-1000</td>
<td>
<div id="select1000" style="display: none">
<select id="">
<option test="l25" value="25">25</option>
<option test="l100" value="100">100</option>
</select>
</div>
</td>
</tr>
<tr>
<td><input type="radio" onclick="document.getElementById('select3000').style.display=(this.checked)?'inline':'none';" name="license" value=""> 1001-3000</td>
<td>
<div id="select3000" style="display: none">
<select id="">
<option test="l1001" value="1001">1001</option>
<option test="l1075" value="1075">1075</option>
</select>
</div>
</td>
</tr>
<tr>
<td><input type="radio" onclick="document.getElementById('select5000').style.display=(this.checked)?'inline':'none';" name="license" value=""> 3001-5000</td>
<td>
<div id="select5000" style="display: none">
<select id="">
<option test="l3001" value="3001">3001</option>
<option test="l3075" value="3075">3075</option>
</select>
</div>
</td>
</tr>
</table>
Where I am going wrong ..... any valuable input will be appreciated.
Could you try to change the input element's name:
<td><input type="radio" onclick="change(this, 'select1000')" name="license[1]" value="1000"> 1-1000</td>
and create a function:
function change(t, div){
var ele = document.getElementsByTagName("div");
var radios = document.getElementsByName("license[1]");
for (var i = 0, radio; radio = radios[i]; i++) {
if (!radio.checked) {
if(ele[i].id != div){
ele[i].style.display = 'none';
}
}else{
document.getElementById(div).style.display='inline';
}
}
}
I'm not sure if this is what you want, but HERE you can see an example.
You just need to change your parenthesis:
document.getElementById('select5000').style.display = (this.checked ? 'inline':'none');
Here is your inputs
<input type="radio" onchange="hideElem(this,'select1000')" name="license" value="1000">
<input type="radio" onchange="hideElem(this,'select3000')" name="license" value="">
<input type="radio" onchange="hideElem(this,'select5000')" name="license" value="">
and the function:
<script type="text/javascript">
function hideElem(self,divId){
var divs = ['select1000','select3000','select5000'];
if(self.checked){
for(var i=0; i < divs.length; i++){
if (divs[i] === divId){
document.getElementById(divs[i]).style.display = 'inline';
} else{
document.getElementById(divs[i]).style.display = 'none';
}
}
}
}
</script>
DEMO
because when you click an input(radio), this is the current radio and you don't know the previous one, you need to record the previous select, use jQuery, code like:
(function () {
var oldSel = null;
$('input:radio').click(function () {
// get the current select
var sel = $('#select' + this.value);
// show current select
sel.show();
// if old select is exist, hide it
oldSel && oldSel.hide();
// store the current select when radio on click
oldSel = sel;
});
})();
see the demo
Related
I'm trying to get the span text when looping over table cells with no success.
<td>
<select name="newStatus" class="stChange">
<option value="0-596">active</option>
<option value="2-596">logout</option>
</select>
</td>
<td class="CellWithComment">
<input id="c57" type="checkbox" name="tfoza" value="1">
<label for="c57">
<span></span>
</label>
<span class="CellComment">960</span>
</td>
<td class="CellWithComment">
<input id="c58" type="checkbox" name="tfoza" value="1">
<label for="c58">
<span></span>
</label>
<span class="CellComment">901</span>
</td>
</tr>
jquery:
$('.stChange').on('change', function ()
{
var st = $(this).val();
var vls = st.split('-');
if( vls[0] == 0){
console.log('0',st);
$(this).closest('tr').find('input[type=checkbox]:checked').each(function(){
console.log($(this).find('.CellComment').text()) ;
});
}
if( vls[0] == 2){
}
});
I'm trying to find the span text when the checkbox is checked (JSFiddle).
What is wrong with the code?
This line of code $(this).find('.CellComment').text() was the problem. The find function looks for children and grand children etc inside of a parent element. That line of code is looking for .CellComment inside the checkbox, which the .each function is iterating through.
I have change that line of code to $(this).parent().find('.CellComment').text(). I have selected the parent of the checkbox using the parent() function, which selects the .CellWithComment element and then find the .CellComment element inside.
$('.stChange').on('change', function (event)
{
var st = $(this).val();
var vls = st.split('-');
if( vls[0] == 0){
$(event.target).closest('tr').find('input[type=checkbox]:checked').each(function() {
console.log($(this).parent().find('.CellComment').text());
});
}
if( vls[0] == 2){
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<table>
<tr>
<td class="test">
<select name="newStatus" class="stChange">
<option value="0-596">active</option>
<option value="2-596">logout</option>
</select>
</td>
<td class="CellWithComment">
<input id="c57" type="checkbox" name="tfoza" value="1">
<label for="c57">
<span></span>
</label>
<span class="CellComment">960</span>
</td>
<td class="CellWithComment">
<input id="c58" type="checkbox" name="tfoza" value="1">
<label for="c58">
<span></span>
</label>
<span class="CellComment">901</span>
</td>
</tr>
</table>
Consider the following radio buttons in html:
<tr>
<td> Lighting </td>
<td> <label for="lighting1"> Off </label>
<input id = "lighting1" name="lighting" type="radio" value="0"> </td>
<td> <label for="lighting2"> Low </label>
<input id = "lighting2" name="lighting" type="radio" value="1"> </td>
<td> <label for="lighting3"> High </label>
<input id = "lighting3" name="lighting" type="radio" value="2"> </td>
</tr>
I need a javascript statement that will assign the radio button's label on a variable instead of its value, ie 'Off', 'Low' or 'High' instead of '0', '1' or '2'. when the radio button is checked.
It seems so simple and straightforward yet I fail to achieve it no matter what I try. I haven't found any working answers on the forum either. Please spare me of stating all non workable trials and enlighten me with just a single line of code that works.
You can fetch radios using common name and update values using input.value = newValue
function updateValues(){
var radios = document.querySelectorAll('[name="lighting"]');
for(var i = 0; i< radios.length; i++){
var id = radios[i].getAttribute('id');
radios[i].value = document.querySelector('label[for="'+id+'"]').textContent.trim()
}
}
function registerEvents(){
var radios = document.querySelectorAll('[name="lighting"]');
for(var i = 0; i< radios.length; i++)
radios[i].addEventListener("change", handleChange)
}
function handleChange(){
console.log(this.value)
}
registerEvents();
<tr>
<td> Lighting </td>
<td> <label for="lighting1"> Off </label>
<input id="lighting1" name="lighting" type="radio" value="0"> </td>
<td> <label for="lighting2"> Low </label>
<input id="lighting2" name="lighting" type="radio" value="1"> </td>
<td> <label for="lighting3"> High </label>
<input id="lighting3" name="lighting" type="radio" value="2"> </td>
</tr>
<p id="selectedValues"></p>
<button onclick="updateValues()" >Update Values</button>
var radioButtons = document.querySelectorAll("input[type='radio']");
for(var i = 0; i< radioButtons.length; i++)
{
radioButtons[i].addEventListener("click", (e)=>{
var radioButton = e.target || e.srcElement;
var label = document.querySelector("label[for='" + radioButton.id + "'");
alert(label.innerText.trim());
});
}
EDIT: Removed the jquery snippet that I initially added. As the user is looking only for a javascript solution, retaining that alone.
Im getting uncaught type error for estimateCost, also im having issues with how to double the price with spouse. I'm suppose to have an alert window that displays the estimate cost based on selections made from city, number of days, and other options. TY!
<html>
<head>
<script language="JavaScript">
var city_prices = new Array();
city_prices["New York City"] = 0;
city_prices["Boston"] = 0;
city_prices["San Francisco"] = 200;
city_prices["Los Angeles"] = 200;
// getCityPrice() finds the price based on the city .
// Here, we need to take user's the selection from radio button selection
function getCityPrice() {
var cityPrice = 0;
//Get a reference to the form id="cakeform"
var theForm = document.forms["form1"];
//Get a reference to the cake the user Chooses name=radCity":
var selectedCity = theForm.elements["radCity"];
//Here since there are 4 radio buttons selectedCity.length = 4
//We loop through each radio buttons
for (var i = 0; i < selectedCity.length; i++) {
//if the radio button is checked
if (selectedCity[i].checked) {
//we set cityPrice to the value of the selected radio button
//i.e. if the user choose NYC we set to 0
//by using the city_prices array
//We get the selected Items value
//For example city_prices["New York City".value]"
cityPrice = city_prices[selectedCity[i].value];
//If we get a match then we break out of this loop
//No reason to continue if we get a match
break;
}
}
//We return the cityPrice
return cityPrice;
}
var number_days = new Array();
number_days["3"] = 450;
number_days["4"] = 600;
number_days["5"] = 750;
number_days["6"] = 900;
number_days["7"] = 1050;
number_days["8"] = 1350;
number_days["9"] = 1500;
number_days["10"] = 1650;
number_days["11"] = 1800;
number_days["12"] = 1950;
number_days["13"] = 2100;
number_days["14"] = 2250;
number_days["15"] = 2400;
//This function finds the day price based on the
//drop down selection
function getDayPrice() {
var dayPrice = 0;
//Get a reference to the form id="form1"
var theForm = document.forms["form1"];
//Get a reference to the select id="selNumberDays"
var selectedDays = theForm.elements["selNumberDays"];
//set dayPrice equal to value user chose
//For example number_days["3".value] would be equal to 450
dayPrice = number_days[selectedDays.value];
//finally we return dayPrice
return dayPrice;
}
//chksFirst() finds the candles price based on a check box selection
function chksFirst() {
var chkFirst = 0;
//Get a reference to the form id="form1"
var theForm = document.forms["form1"];
//Get a reference to the checkbox id="chkFirst"
var includeFirst = theForm.elements["chkFirst"];
//If they checked the box set first class to 500
if (includeFirst.checked == true) {
chkFirst = 500;
}
//finally we return the firstClass
return chkFirst;
}
//chksSpouse() finds the candles price based on a check box selection
function chksSpouse() {
var chkSpouse = 0;
//Get a reference to the form id="form1"
var theForm = document.forms["form1"];
//Get a reference to the checkbox id="chkSpouse"
var includeSpouse = theForm.elements["chkSpouse"];
//If they checked the box set Total 2x
if (includeSpouse.checked == true) {
totalPrice = totalPrice * 2;
}
//finally we return the firstClass
return totalPrice;
}
function estimateCost() {
//Here we get the estimate price by calling our function
//Each function returns a number so by calling them we add the values they return together
var totalPrice = getCityPrice() + getDayPrice() +
chksFirst() + chksSpouse();
alert(totalPrice);
}
</script>
</head>
<body>
<table align="left" width="600px" border="0" cellpadding="5px">
<tr>
<td>
<form name="form1" id="form1">
<table border="0">
<tr>
<td width="300px"><strong>Last Name: </strong>
</td>
<td width="300px">
<input type="text" name="txtFirstName" value=" " size="20" />
</td>
</tr>
<tr>
<td><strong>First Name: </strong>
</td>
<td>
<input type="text" name="txtLastName" value=" " size="20" />
</td>
</tr>
<tr>
<td><strong>Nationality: </strong>
</td>
<td>
<select name="selNationality">
<option value="amer">USA</option>
<option value="can">Canada</option>
<option value="mex">Mexico</option>
<option value="ger">Germany</option>
<option value="fra">France</option>
</select>
</td>
</tr>
<tr>
<td><strong>City you wish to visit: </strong>
</td>
<td>
<input type="radio" name="radCity" value="New York City" />New York City
<br />
<input type="radio" name="radCity" value="Boston" />Boston
<br />
<input type="radio" name="radCity" value="San Francisco" />San Francisco ($200 surcharge)
<br />
<input type="radio" name="radCity" value="Los Angeles" />Los Angeles ($200 surcharge)
<br/>
</td>
</tr>
<tr>
<td><strong>Number of days ($150 per day): </strong>
</td>
<td>
<select name="selNumberDays" id="selNumberDays">
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
</td>
</tr>
<tr>
<td><strong>Other options: </strong>
</td>
<td>
<input type="checkbox" name="chkFirst" id="chkFirst" />First Class Only ($500 surcharge)
<br />
<input type="checkbox" name="chkSpouse" id="chkSpouse" />Traveling with Spouse (All costs doubled)
<br />
</td>
</tr>
<tr>
<td align="right">
<input type="button" value="Give me an estimate!" onClick="estimateCost()" id="estimateCost" />
</td>
<td align="left">
<input type="reset" />
</td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
On the button input with the onClick="estimateCost()" code, remove the id="estimateCost". It's causing the error for some reason. You should really be using an onClick listener though instead of an inline onclick:
Inline onclick JavaScript variable
For the total with spouse, you might want to rework it to something like this where you pass the pre-spouse price into the chksSpouse function and use it's return as the total price.
//chksSpouse() finds the candles price based on a check box selection
function chksSpouse(totalPrice) {
var chkSpouse = 0;
//Get a reference to the form id="form1"
var theForm = document.forms["form1"];
//Get a reference to the checkbox id="chkSpouse"
var includeSpouse = theForm.elements["chkSpouse"];
//If they checked the box set Total 2x
if (includeSpouse.checked == true) {
totalPrice = totalPrice * 2;
}
//finally we return the firstClass
return totalPrice;
}
function estimateCost() {
//Here we get the estimate price by calling our function
//Each function returns a number so by calling them we add the values they return together
var preSpouseTotal = getCityPrice() + getDayPrice() + chksFirst();
var totalPrice = chksSpouse(preSpouseTotal);
alert(totalPrice);
}
I have a section with a lot of blocks (I'll use only two on this example). The situation is: I have a <div> with a <input>, a <select> group and <radio> buttons. After filling all of them and clicking on "Grab" button, the script will show an alert with this values.
But if you fill more then one block, the last one doesn't grab the radios. It always returns "undefined". If you leave the first blocks with empty radios and fill the last one, the info on the alert screen will show the last one, however it's wrong.
What I'm doing wrong?
Here is the JSFiddle
JavaScript
$(document).ready(function(){
var contentArray = '';
$('button').click(function() {
$('.option_group').each(function(i) {
var NotEmptyTextBoxes = $('input:text').filter(function() { return this.value !== ""; });
var NotEmptyCombo = $('option:selected').filter(function() { return this.text !== ""; });
NotEmptyTextBoxes.each(function() {
name = this.name;
val = this.value;
var combo = $('#c_'+name).val();
var radio = $('input[name=r_'+name+']:checked', '#theform').val();
contentArray = contentArray+name+'='+"'"+val+"'"+","+"'"+combo+"'"+","+radio+";"+"|";
radio = '';
});
alert(contentArray);
contentArray = '';
return false;
});
});
});
HTML
<form id ="theform">
<div class="option_group" id="bloco">
<input type="text" placeholder="Cargo" name="cargo" id="carga"/>
<select class="filtercombo" id="c_cargo">
<option>like</option>
<option>=</option>
<option>!=</option>
<option><</option>
<option><=</option>
<option>></option>
<option>>=</option>
<option>is null</option>
<option>is not null</option>
<option>in</option>
<option>not in</option>
<option>between</option>
<option>contains</option>
<option>not like</option>
</select>
<input type="radio" value="up" name="r_cargo">
<input type="radio" value="down" name="r_cargo">
<input type="radio" value="flat" name="r_cargo">
</div><!-- #end of option_group -->
<div class="option_group" id="bloco">
<input type="text" placeholder="provider" name="provider" id="provider"/>
<select class="filtercombo" id="c_provider">
<option>like</option>
<option>=</option>
<option>!=</option>
<option><</option>
<option><=</option>
<option>></option>
<option>>=</option>
<option>is null</option>
<option>is not null</option>
<option>in</option>
<option>not in</option>
<option>between</option>
<option>contains</option>
<option>not like</option>
</select>
<input type="radio" value="up" name="r_provider1" />
<input type="radio" value="down" name="r_provider2" />
<input type="radio" value="flat" name="r_provider3" />
</div><!-- #end of option_group -->
<button type="button">grab</button>
</form>
You have different names for your last group of radios r_provider1, r_provider2, r_provider3, they should all have the same name 'r_provider'.
I have this code:
<div id="star-rating">
<script type="text/javascript">
$(function(){
$('#star-rating form').submit(function(){
$('.test',this).html('');
$('input',this).each(function(){
if(this.checked)
//$('.test',this.form).append(''+this.name+': '+this.value+'<br/>');
$('.test',this.form).append(this.value);
});
return false;
});
});
</script>
<form name="form1" method="post" action="<?=base_url();?>rate/student">
<div class="dbtable">
<table cellpadding="0" cellspacing="0" border="0"><tbody>
<th colspan="4" align="left">Personal Appearance</th>
<tr><td width="10px"></td><td width="60%">Neatness</td>
<td width="20%">
<input name="neat" type="radio" class="neat-star" value="1" title="Poor"/>
<input name="neat" type="radio" class="neat-star" value="2" title="Fair"/>
</td>
</tr>
<tr><td></td><td>Health</td>
<td>
<input name="health" type="radio" class="health-star" value="1" title="Poor"/>
<input name="health" type="radio" class="health-star" value="2" title="Fair"/>
</td>
</tr>
<tr><td></td><td align="right"></td>
<td><input type="submit" value="Submit scores!" /></td>
<td><div class="test Smaller">
<span style="color:#FF0000">Results</span>
</div>
</td></tr>
So now I have 2 radio star rating. What I want is when I click the submit score it will add up the 2 selected radio box. E.g when click radio button neat with the value of 1 and radio button health with the value of 2 then the result will show 3 coz 1+2=3 in my div class=test. Could anyone help me with this.
$('#star-rating form').submit(function() {
$('.test', this).html('');
var total = 0;
$('input', this).each(function(){
if(this.checked) {
total += parseInt(this.value, 10);
}
}
//Do something with total
return false;
});
You need to use parseInt to convert a String into a Number. Otherwise, you'll just be concatenating values onto a string.
$('#star-rating form').submit(function() {
var score = $(this).find('.neat-star').val()
+ $(this).find('.health-star').val();
$(this).find('.test').html(score);
return false;
});
Try this
(function(){
$('#star-rating form').submit(function(){
var neatVal, healthVal;
neathVal = $(this).find("input[name=neat]:checked").val();
healthVal = $(this).find("input[name=health]:checked").val();
$('.test', this).append(praseInt(neatVal) + parseInt(healthVal ));
return false;
});
});