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.
Related
I'm a beginner in JavaScript. I have a table row which consist of text input, radio buttons and button to add or delete the row. When I click the add button, it will duplicate the row exactly like the current one. However, when I click any of the radio button in second row (the duplicated row), my choice from the first row is changed/cleared. How can I solved this? And how can I save and export this HTML form to excel?
I have tried all methods that I can find and even watched YouTube videos. Any suggestion to improve my code are welcome. Thank you.
function addRow(row) {
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').insertRow(i + 1);
tr.innerHTML = row.parentNode.parentNode.innerHTML;
var inputs = tr.querySelectorAll("input[type='text']");
for (var i = 0; i < inputs.length; i++)
inputs[i].value = "";
}
function delRow(row) {
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').deleteRow(i - 1);
tr.innerHTML = row.parentNode.parentNode.innerHTML;
var inputs = tr.querySelectorAll("input[type='text']");
for (var i = 0; i < inputs.length; i--)
inputs[i].value = "";
}
<div style="overflow-x:auto;">
<table id="Table" style="width: 100%">
<tr>
<td><input type="text" name="questions" size="80" id="questions" placeholder="Questions" required/><br><br>
<input type="radio" name="smiley" value="rd1">😞 I don't like it at all.<br>
<input type="radio" name="smiley" value="rd2">😕 I maybe like it.<br>
<input type="radio" name="smiley" value="rd3">🙂 I like it.<br>
<input type="radio" name="smiley" value="rd4">😄 I like it very much.<br><br>
<input type="button" id="addBtn" value="Add Questions" onclick="addRow(this)" value="1" />
<input type="button" id="delBtn" value="Delete Questions" onclick="delRow(this)" value="1" />
</td>
</tr>
</table>
</div>
You can see how to download csv from html table here
As for your code, you need to change the name of the input for the new row.
function addRow(row) {
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').insertRow(i + 1);
tr.innerHTML = row.parentNode.parentNode.innerHTML.replace(/smiley/g, "smiley" + i);
var inputs = tr.querySelectorAll("input[type='text']");
for (var i = 0; i < inputs.length; i++)
inputs[i].value = "";
}
function delRow(row) {
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').deleteRow(i - 1);
tr.innerHTML = row.parentNode.parentNode.innerHTML;
var inputs = tr.querySelectorAll("input[type='text']");
for (var i = 0; i < inputs.length; i--)
inputs[i].value = "";
}
<div style="overflow-x:auto;">
<table id="Table" style="width: 100%">
<tr>
<td><input type="text" name="questions" size="80" id="questions" placeholder="Questions" required/><br><br>
<label><input type="radio" name="smiley" value="rd1">😞 I don't like it at all.</label><br>
<label><input type="radio" name="smiley" value="rd2">😕 I maybe like it.</label><br>
<label><input type="radio" name="smiley" value="rd3">🙂 I like it.</label><br>
<label><input type="radio" name="smiley" value="rd4">😄 I like it very much.<br></label><br>
<input type="button" id="addBtn" value="Add Questions" onclick="addRow(this)" value="1" />
<input type="button" id="delBtn" value="Delete Questions" onclick="delRow(this)" value="1" />
</td>
</tr>
</table>
</div>
Different radio button groups need different names. I tweaked your JS to add a unique timestamp to the radio button name when adding a new row.
function addRow(row) {
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').insertRow(i + 1);
tr.innerHTML = row.parentNode.parentNode.innerHTML;
var inputs = tr.querySelectorAll("input[type='text']");
for (var i = 0; i < inputs.length; i++)
inputs[i].value = "";
const unique= Date.now();
const radios = tr.querySelectorAll("input[type='radio']");
for (var i = 0; i < radios.length; i++)
radios[i].name = `${radios[i].name}${unique}`;
}
function delRow(row) {
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').deleteRow(i);
}
<div style="overflow-x:auto;">
<table id="Table" style="width: 100%">
<tr>
<td><input type="text" name="questions" size="80" id="questions" placeholder="Questions" required/><br><br>
<input type="radio" name="smiley" value="rd1">😞 I don't like it at all.<br>
<input type="radio" name="smiley" value="rd2">😕 I maybe like it.<br>
<input type="radio" name="smiley" value="rd3">🙂 I like it.<br>
<input type="radio" name="smiley" value="rd4">😄 I like it very much.<br><br>
<input type="button" id="addBtn" value="Add Questions" onclick="addRow(this)" value="1" />
<input type="button" id="delBtn" value="Delete Questions" onclick="delRow(this)" value="1" />
</td>
</tr>
</table>
</div>
I would delegate and clone
NOTE I changed the id to a class for the buttons and added a tbody
You must have unique IDs
I renumber all the radios from 1 to n even when you delete a row in the middle
I also hide the first delete using CSS
const tb = document.getElementById("Table");
const firstRow = tb.querySelector("tr")
tb.addEventListener("click", e => {
const tgt = e.target;
if (!tgt.type === "button") return; // not a button
if (tgt.matches(".addBtn")) tb.append(firstRow.cloneNode(true)); // clone the first row
else if (tgt.matches(".delBtn")) tgt.closest("tr").remove();
// rename radios
tb.querySelectorAll("tr").forEach((tr,i) => {
tr.querySelectorAll("input[type=radio]").forEach(rad => rad.name = `question${i+1}`)
})
})
#Table tr:first-child .delBtn { display: none; }
<div style="overflow-x:auto;">
<table style="width: 100%">
<tbody id="Table">
<tr>
<td><input type="text" name="questions" size="80" placeholder="Questions" required/><br><br>
<input type="radio" name="question1" value="rd1">😞 I don't like it at all.<br>
<input type="radio" name="question1" value="rd2">😕 I maybe like it.<br>
<input type="radio" name="question1" value="rd3">🙂 I like it.<br>
<input type="radio" name="question1" value="rd4">😄 I like it very much.<br><br>
<input type="button" class="addBtn" value="Add Questions" value="1" />
<input type="button" class="delBtn" value="Delete Questions" value="1" />
</td>
</tr>
</tbody>
</table>
</div>
I want to compare the two items(text and checkbox) and output the result.
for example, 164cm and style S is A, 186cm and style B is XL
input number is height and radio button value are 3 styles(small,normal,big)
output is 164s 186b
I use a if and == display result are 'S, M, L, XL)
If user enter height and select a style, want to output a value that matches the size table prepared in advance.
I'm a beginner, so this is my plan.
this time, I want output text+radio button value
<script>
$(window).load(function(){
$(".height, .style, .style_2").keyup(function() {
var row = $(this).closest('tr');
var height = parseInt(row.find('.height').val(), 10);
var total = "height" + "style";
row.find('.total').val(isNaN(total) ? '' : total);
});
});
</script>
<table>
<tbody>
<tr id="person_total">
<td><input name="height" type="number" class="span1 height" maxlength="5"></td>
<td>
<input type="radio" id="stylebox" name="stylebox" class="style" value="s" onClick="document.getElementById('hidfield').value=this.value" />
<label for="kjc-small">S</label>
<input type="radio" id="stylebox" name="stylebox" class="style" value="n" onClick="document.getElementById('hidfield').value=this.value" />
<label for="kjc-normal">N</label>
<input type="radio" id="stylebox" name="stylebox" class="style" value="b" onClick="document.getElementById('hidfield').value=this.value" checked/>
<label for="kjc-big">B</label>
</td>
<td><input name="total" type="text" class="span1 total" readonly></td>
</tr>
</tbody>
</table>
Don't use onClick in html when you use other script controller.
You can insert input in label, when id and for no need
id can't duplicate (id="stylebox")
$(document).ready(function(){
/* get nodes */
var totalNode = $('.total');
var heightNode = $('.height');
var styleNode = $('input[name="stylebox"]');
/* initial state */
var currentTotal = 0;
var currentHeight = heightNode.val();
var currentStyle = styleNode.val();
calcTotal(); // calc state
// when [input] Height change
heightNode.on('input propertychange', function() {
currentHeight = this.value;
console.log('now height', currentHeight)
calcTotal();
})
// when [radio] Style change
styleNode.change(function() {
currentStyle = this.value;
console.log('now style', currentStyle)
calcTotal();
})
// calc.
function calcTotal() {
currentTotal = currentHeight + currentStyle;
totalNode.val(currentTotal);
console.log('now total:', totalNode.val())
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<table>
<tbody>
<tr id="person_total">
<td>
<label>
<b>Height:</b>
<input name="height" type="number" class="span1 height" value="0" maxlength="5">
</label>
</td>
<!-- radio START -->
<td>
<label>
<input type="radio" name="stylebox" class="style" value="s" />
S
</label>
<label>
<input type="radio" name="stylebox" class="style" value="n" />
N
</label>
<label>
<input type="radio" name="stylebox" class="style" value="b" checked/>
B
</label>
</td>
<!-- radio END -->
<td>
<label>
<b>Total:</b>
<input name="total" type="text" class="span1 total" readonly>
</label>
</td>
</tr>
</tbody>
</table>
</body>
</html>
You can do it like this:
$('.height,.style').on('change, input',
function(){
$('.total').val($('.height').val() + $('.style:checked').val());
});
and please note that id should be unique in the document but all your radios has the same id (stylebox).
Live Demo
You can create a new input field which is set to read only and call a javascript function to set the value
which will append the input text and radio button field there
Total :
var size = document.getElementsById('stylebox');
var height = document.getElementsByName('height');
var size_value;
for(var i = 0; i
I'm trying to add the radio button and the checkboxes, but I'm either getting a nan value from the checkboxes or nothing is displayed if I add them both. I'm not sure why I am not getting the answer I thought I've understood through my code, especially on javascript.
function calculatePrice() {
var i;
var resultmessage = "";
var pizzamount = parseFloat(0);
var radval;
var radval2;
var chckbox;
var totalvalue = parseInt(0);
for (i = 0; i < document.cost.typed.length; i++) {
if (document.cost.typed[i].checked) {
radval = document.i.typed[i].value;
}
}
if (document.cost.cheese.checked) {
pizzamount += 150 / 100;
}
if (document.cost.pepperoni.checked) {
pizzamount += 150 / 100;
}
radval = parseFloat(radval);
pizzamount = parseFloat(pizzamount)
var resultmessage = "Total cost: $" + pizzamount;
document.getElementById("result").innerHTML = resultmessage;
}
<form name="cost" autocomplete="on">
<table class="left" border="1px">
<tr>
<th>
Choose a Pizza Size
</th>
</tr>
<tr>
<td>
<input type="radio" name="typed" value="18" checked>Extra Large
<br>
<input type="radio" name="typed" value="15">Large
<br>
<input type="radio" name="typed" value="10">Medium
<br>
<input type="radio" name="typed" value="8">Small
<br>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="cheese" checked>Extra Cheese<br>
<input type="checkbox" name="pepperoni">Pepperoni<br>
</td>
</tr>
</table>
<input type="button" value="Place Order" onClick="calculatePrice()">
</form>
Made a few small changes, but largely cosmetic -- firstly, note that I'm still storing the check and radio as variables, and accessing them. But when I use the radio, I simply use that to get the size, then (using its index) reference the price/size array to get the actual pizza price. Other than that, it's working exactly the same.
calculatePrice = function calculatePrice() {
var resultmessage = "";
var pizzamount = parseFloat(0);
var radval;
var radval2;
var chckbox;
var totalValue = parseInt(0);
var priceTable = [
{
size: "18",
price: 12.00
}, {
size: "15",
price: 10.75
}, {
size: "10",
price: 9.90
}, {
size: "8",
price: 9.25
}];
var size = document.getElementsByName("size");
var extras = document.getElementsByName("extras");
// First, calculate the size. This is a radio, so
// we should only get one value.
for (var i=0; i<size.length; i++) {
if(size[i].checked){
radVal = priceTable[i].size;
totalValue += priceTable[i].price;
}
}
// next, the extras. This may be multiple options
for (var i=0; i<extras.length; i++) {
if (extras[i].checked) {
totalValue += (150/100);
}
}
//radval = parseFloat(radval);
totalValue = parseFloat(totalValue);
var resultmessage = "Total cost: $" + totalValue;
document.getElementsByClassName("running-total")[0].innerHTML = resultmessage;
}
label {
font-weight: bold;
display: block;
}
form {
width: 250px;
border: 1px dotted green;
}
<form name="cost" autocomplete="on">
<fieldset>
<label for="size">Choose a Pizza Size:</label>
<input type="radio" name="size" value="18" checked>Extra Large
<input type="radio" name="size" value="15">Large
<input type="radio" name="size" value="10">Medium
<input type="radio" name="size" value="8">Small
</fieldset>
<fieldset>
<label for="specials">Pizza Special:</label>
</fieldset>
<fieldset>
<label for="extras">Extras:</label>
<input type="checkbox" name="extras" value="cheese">Cheese
<input type="checkbox" name="extras" value="pepperoni">Pepperoni
</fieldset>
<input type="button" onClick="calculatePrice()" value="Calculate Price!" /> <span class="running-total"></span>
</form>
Your html is incomplete. You don't have the specials or extras columns filled out, and you have some pizza sizes on there twice.
What you'll want to do is have things that you cannot have more than one of as a set of radio buttons (e.g. pizza sizes), and things you can have multiple of as a set of check boxes.
Then, you need to iterate through each checkbox and radio button to see if it's checked, and if it is, add it's value to the total.
It will also make it easier to work with if you add a border to the table and it's children.
I wasn't really able to make much sense of the code you had, so I hope that you find this helpful.
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
I would like to build a javascript so a user can choose only one option between the the mentioned below. Could you give me some pointers how to do this since I am a javascript noob.
Thank you!
This is the picture of the part of a menu
<td><label for="dock_books_search_visible_online"> Visible online?</label></td>
<td><input type="checkbox" name="option" value="checkedVisibleOk" id="dock_books_visible_ok" /> </td>
<td><label for="dock_books_search_visible_online_yes"> Yes</label></td>
<td><input type="checkbox" name="option" value="checkedVisibleNok" id="dock_books_visible_nok" /> </td>
<td><label for="dock_books_search_visible_online_no"> No</label></td>
For single selection from multiple options we use Radio Buttons not CheckBoxes.
You should use some thing like this.
<input type="radio" name="option" value="Yes" id="yes" />
<input type="radio" name="option" value="No" id="no" />
But still if you want to go the other way round, Just add the following script in your head tag:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(':checkbox').bind('change', function() {
var thisClass = $(this).attr('class');
if ($(this).attr('checked')) {
$(':checkbox.' + thisClass + ":not(#" + this.id + ")").removeAttr('checked');
}
else {
$(this).attr('checked', 'checked');
}
});
});
</script>
Here is the fiddle for above.
Hope this helps.
This looks like a job for radio buttons, not checkboxes.
you got a point to use radio buttons any way here is the javascript solution
i used it in my project when there is search criteria and search result in data grid by
ajax having 13 records when i check one record it disables the rest
code for javascript enable disable check boxes jsfiddle
<form name="mainForm" method="GET">
Visible online?
<input type="checkbox" name="option" value="checkedVisibleOk" id="option" onclick="changeCheckBox();"/>
yes
<input type="checkbox" name="option" value="checkedVisibleNok" id="option" onclick="changeCheckBox();"/>
no
</form>
<script>
var serNoChecked="";
function changeCheckBox() {
try {
var max = document.mainForm.option.length;
var count = 0;
for (var i = 0; i < max; i++) {
if (document.mainForm.option[i].checked == true) {
count++;
serNoChecked = i;
}
}
if (count == 1) {
for (var i = 0; i < max; i++) {
if (document.mainForm.option[i].checked == false) {
document.mainForm.option[i].disabled = true;
}
}
}
else if (count == 0) {
for (var i = 0; i < max; i++) {
document.mainForm.option[i].disabled = false;
}
}
if (null == max) return false;
if (count == 0) {
return true;
}
else if (count > 0) {
return false;
}
}
catch (e) {
alert(e.message);
}
}
</script>
Try using Radio Button's, Give them the same name to group them and only allow 1 to be selected:
<td>
<label for="dock_books_search_visible_online"> Visible online?</label>
</td>
<td>
<input type="radio" name="option" value="checkedVisibleOk" id="dock_books_visible_ok" />
</td>
<td>
<label for="dock_books_search_visible_online_yes"> Yes</label>
</td>
<td><input type="radio" name="option" value="checkedVisibleNok" id="dock_books_visible_nok" />
</td>
<td>
<label for="dock_books_search_visible_online_no"> No</label>
</td>
Check this JSFiddle.
Hi why are you using checkbox? Checkboxes are not for the functionality that you want. Radio buttons are exact what you want to use.
<form>
<input type="radio" name="sex" value="male" /> Male<br />
<input type="radio" name="sex" value="female" /> Female
</form>
For further details look here
function toggle(chkBox, field) {
for ( var i = 0; i < field.length; i++) {
field[i].checked = false;
}
chkBox.checked = true;
}
<td>
<INPUT type="checkbox" name="xyz" onClick="toggle(this,document.myform.xyz);" value="${incident.incidentID}">
</td>
Use radio buttons and ensure that the name tag is consistent with all options and it'll automatically select just one w/o the need for additional code or JS.