I'm currently creating a Checkbox and trying to append the selections to a function.
This is what I currently have :
<input type="checkbox" id="Animal" value="Animal" name="langs" checked><label for="UW">UW</label><br>
<input type="checkbox" id="Vegatable" value="Vegetable" name="langs"><label for="OIB">OIB</label><br>
<input type="text" id="Other" value="N/A" name="langs" style="font-size:10px;" style="width: 125px;" /><label for="Other">Other</label><br>
This is what I currently have for the Appendchild Result:
<tr name="checkbox_value"><th>Systems Used: </th>
</tr>
I'm using the option Document.getElementId but I can't get multiple result or a single result
var SysRow = document.getElementById("checkbox_value");
var td4 = document.createElement("td");
td4.innerHTML = document.getElementById("langs").value;
SysRow.appendChild(td4);
from my understanding i can use document.getElementsByClassName() or document.querySelectorAll() but I'm not sure how to implement it .
What if the person selects multiple results like "Animal" and "Vegetable".
Use this code:
var items=document.getElementsByClassName('appendInput');
var checkedItems ="";
for(var i=0; i<items.length; i++){
if(items[i].type=='checkbox' && items[i].checked)
checkedItems+=items[i].value+" ";
}
document.getElementById('result').innerHTML = checkedItems;
<input class="appendInput" type="checkbox" name="langs" value="Animal" checked>
<input class="appendInput" type="checkbox" name="langs" value="Vegetable" checked>
<input class="appendInput" type="checkbox" name="langs" value="N/A">
<div id="result"></div>
Add a class on the elements that you want to append
<input class="toappend" type="text" name="element_1">
<input class="toappend" type="text" name="element_2">
<input class="toappend" type="text" name="element_3">
Then in JS
var allElements = document.querySelectorAll('.toappend');
allElements will become nodeList then you can pass it in the function
function yourFunction(elements) {
// If you want to use forEach method, you have to convert the nodeList to an Array
//ES5
var arrElements = Array.prototype.slice.call(elements);
//ES6
let arrElements = Array.from(elements);
arrElements.forEach(function(currentEl, index, array) {
var appendTo = document.querySelector('#checkbox_value');
appendTo.insertAdjacentHTML('beforeend', currentEl.outerHTML);
});
}
Check this pen
Related
I have a div as follows:
<div class="questionholder" id="question5" style="display:none">
<div>
<h5>Select all that apply</h5>
<input class="input5" type="checkbox" id="ID1elementColor" name="ID1element" value="color"><label for="ID1elementColor"><p class="radioChoice">Color</p></label>
<input class="input5" type="checkbox" id="ID1elementHeight" name="ID1element" value="height"><label for="ID1elementHeight"><p class="radioChoice">Height</p></label>
<input class="input5" type="checkbox" id="ID1elementWeight" name="ID1element" value="weight"><label for="ID1elementWeight"><p class="radioChoice">Weight</p></label>
</div>
</div>
<div class="holdButtons">
<a class="text2button" onclick="displayquestion(6);">Next</a>
</div>
The user is expected to select all the checkboxes that apply to his situation. Let's assume he selects all 3.
When he clicks "Next", the function displayquestion(); will fire.
function displayquestion(a) {
var Elements = '';
var b = a - 1;
Elements = document.querySelector("#question" + b + " input[name=ID1element]").value;
}
Basically, the function is meant to store all the checked values into var Elements, which is meant to be an array.
However, I'm only getting the value of the first selected answer instead of an array of all selected answers.
How do I grab all the selected answers into an array?
No jQuery please.
Use querySelectorAll to get an array-like NodeList instead of querySelector, and then you can use Array.from to transform that NodeList into an array containing only the .value of the selected inputs:
function displayquestion(a) {
const b = a - 1;
const elements = Array.from(
document.querySelectorAll('#question' + b + ' input:checked'),
input => input.value
);
console.log(elements);
}
<div class="questionholder" id="question5">
<div>
<h5>Select all that apply</h5>
<input class="input5" type="checkbox" id="ID1elementColor" name="ID1element" value="color"><label for="ID1elementColor"><p class="radioChoice">Color</p></label>
<input class="input5" type="checkbox" id="ID1elementHeight" name="ID1element" value="height"><label for="ID1elementHeight"><p class="radioChoice">Height</p></label>
<input class="input5" type="checkbox" id="ID1elementWeight" name="ID1element" value="weight"><label for="ID1elementWeight"><p class="radioChoice">Weight</p></label>
</div>
</div>
<div class="holdButtons">
<a class="text2button" onclick="displayquestion(6);">Next</a>
</div>
Here is the script that you can use for that:
I haven't changed anything in your HTML structure. Except I have removed the display: none; from the style attribute of the class questionholder.
<script>
function displayquestion(b) {
let checkboxList = document.querySelectorAll("#question" + b + " input:checked");
let obj = [];
if (checkboxList.length > 0) { //Code works only if some checbox is checked
checkboxList.forEach(function(item) {
obj.push(item.value); //Contains the value of all the selected checkboxes.
});
}
console.log(obj); //array list containing all the selected values
}
</script>
<div class="questionholder" id="question5" style="">
<div>
<h5>Select all that apply</h5>
<input class="input5" type="checkbox" id="ID1elementColor" name="ID1element" value="color"><label for="ID1elementColor"><p class="radioChoice">Color</p></label>
<input class="input5" type="checkbox" id="ID1elementHeight" name="ID1element" value="height"><label for="ID1elementHeight"><p class="radioChoice">Height</p></label>
<input class="input5" type="checkbox" id="ID1elementWeight" name="ID1element" value="weight"><label for="ID1elementWeight"><p class="radioChoice">Weight</p></label>
</div>
</div>
<div class="holdButtons">
<a class="text2button" onclick="displayquestion(5);">Next</a>
</div>
Here is a JSFiddle link for that.
I hope this is helpful.
So first of I would make a variable for your
<a class="text2button">Next</a>. And I have removed the
onclick="displayquestion(6)" from your html.
Here is the variable.
var text2button = document.getElementsByClassName("text2button")[0];
text2button.addEventListener("click", displayquestion);
Here we have the function, so what I've done is.
I have created a variable var elements = []; Which is a empty array.
Then I create this variable var inputs = document.getElementsByClassName("input5");
This variable gets all the inputs with class input5.
Next I would loop through each of the inputs from the var inputs. Like this.
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
elements.push(inputs[i].value);
}
}
So what I do here is loop through each input for (var i = 0; i < inputs.length; i++) and then I check if any of the inputs are checked if (inputs[i].checked), then I push them to the array var elements with elements.push(inputs[i].value);.
And then I use console.log(elements); so show it in the console.
Check out the snippet below to see it in effect.
Hope this helps.
var text2button = document.getElementsByClassName("text2button")[0];
text2button.addEventListener("click", displayquestion);
function displayquestion() {
var elements = [];
var inputs = document.getElementsByClassName("input5");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
elements.push(inputs[i].value);
}
}
console.log(elements);
}
<div class="questionholder" id="question5">
<div>
<h5>Select all that apply</h5>
<input class="input5" type="checkbox" id="ID1elementColor" name="ID1element" value="color"><label for="ID1elementColor"><p class="radioChoice">Color</p></label>
<input class="input5" type="checkbox" id="ID1elementHeight" name="ID1element" value="height"><label for="ID1elementHeight"><p class="radioChoice">Height</p></label>
<input class="input5" type="checkbox" id="ID1elementWeight" name="ID1element" value="weight"><label for="ID1elementWeight"><p class="radioChoice">Weight</p></label>
</div>
</div>
<div class="holdButtons">
<a class="text2button">Next</a>
</div>
I am trying to get the checked value in checkbox and display it in some specific format using javascript but somehow I dont know how to do it
I have tried html and javascript and I dont know ajax or jquery so I am trying javascript only
function Hobby()
{
var checkedValue = null;
var inputElements = document.getElementsByClass('messageCheckbox');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue = inputElements[i].value
document.getElementById("hobbies_value").innerHTML = inputElements;
break;
}
}
}
Hobby <input class="messageCheckbox" type="checkbox" name="painting" id="painting" value="painting">Painting
<input class="messageCheckbox" type="checkbox" name="dancing" id="dancing" value="dancing">Dancing
<input class="messageCheckbox" type="checkbox" name="sports " id="sports " value="sports ">Sports
<input type="button" value="student_submit" onclick="Hobby()"><br/>
If checked values are dancing and painting
then output should be
Hobby:#dancing#painting
and I dont want to display it as alert box instead I want to display it on same page
You need to concatenate the values and display them outside the loop. Something like this:
function Hobby()
{
var checkedValue = "";
var inputElements = document.getElementsByClassName('messageCheckbox');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue += "#"+inputElements[i].value
}
}
document.getElementById("hobbies_value").innerHTML = checkedValue;
}
Hobby <input class="messageCheckbox" type="checkbox" name="painting" id="painting" value="painting">Painting
<input class="messageCheckbox" type="checkbox" name="dancing" id="dancing" value="dancing">Dancing
<input class="messageCheckbox" type="checkbox" name="sports " id="sports " value="sports ">Sports
<input type="button" value="student_submit" onclick="Hobby()"><br/>
Javascript code is
<div id="hobbies_value"></div>
I would like to calculate the sum of checked checkboxes and print the result to the form input value, but this code isn't working:
var calculator = document.querySelector("form");
function extras() {
var extrasPricing = new Array();
extrasPricing["candles"] = 5;
extrasPricing["inscription"] = 10;
extrasPricing["decoration"] = 25;
extrasPricing["special"] = 50;
var extrasCost = 0;
var extras = calculator.elements["extras"];
for (var i = 0; i < extras.length; i++) {
if (extras[i].checked) {
extrasCost = extrasCost + extrasPricing[extras[i].value];
break;
}
}
return extrasCost;
}
function calculateTotal() {
calculator.total.value = "$" + extras();
}
<form>
<fieldset>
<legend>Select Extras</legend>
<label><input type="checkbox" name="extras" value="candles" onclick="calculateTotal()">Candles</label><br>
<label><input type="checkbox" name="extras" value="inscription" onclick="calculateTotal()">Inscription</label><br>
<label><input type="checkbox" name="extras" value="decoration" onclick="calculateTotal()">Decoration</label><br>
<label><input type="checkbox" name="extras" value="special" onclick="calculateTotal()">Special Frosting & Icing</label>
</fieldset>
<input type="text" name="total" readonly>
<input type="submit" value="Submit">
</form>
What am I doing wrong while performing the calculation?
You seem to be coming from PHP.
There are several issues with your code.
In JavaScript, several data structures exist either as primitives or objects. In the case of the array, this is the primitive:
var anArray = [];
and this is the object:
var anArray = new Array();
when both exist, you should never use the object. It should only ever be used internally.
Also, JavaScript does not have associative arrays or dictionaries. It only has what it calls objects. Under the hood, they're the same thing, but what that means is:
colors["blue"]
and
colors.blue
are the same thing. When the second is possible, which is not always the case, the second form is preferred.
Now, for your HTML.
Don't use name. name is obsolete. Use either class or id. Here, you could use class, but really, you don't need to. Putting an id on the fieldset element would probably be enough to get to your input elements.
You should not write JavaScript inside of HTML. There are many solutions to that problem. The simplest is to simply use jQuery. If you do, it will be jQuery that will attach the callback to your HTML to keep the HML and JavaScript nice and separate. An ever better approach would be to use an even more complete framework such as React, Vue or Angular, but those can be more difficult to learn that can be overkill for now.
So, let's try jQuery instead.
Try this on for size: https://jsfiddle.net/8tf25zw9/3/
Remove the break which will stop the for loop. Your for loop is only going to get the value of the first checked checkbox that way. Your logic is flawed; just because you have found one checked checkbox does not mean that your calculations are finished. You need to add the values of all the checked checkboxes.
var calculator = document.querySelector("form");
function extras() {
var extrasPricing = new Array();
extrasPricing["candles"] = 5;
extrasPricing["inscription"] = 10;
extrasPricing["decoration"] = 25;
extrasPricing["special"] = 50;
var extrasCost = 0;
var extras = calculator.elements["extras"];
for (var i = 0; i < extras.length; i++) {
if (extras[i].checked) {
extrasCost = extrasCost + extrasPricing[extras[i].value];
//Do not break here
}
}
return extrasCost;
}
function calculateTotal() {
calculator.total.value = "$" + extras();
}
<form>
<fieldset>
<legend>Select Extras</legend>
<label><input type="checkbox" name="extras" value="candles" onclick="calculateTotal()">Candles</label><br>
<label><input type="checkbox" name="extras" value="inscription" onclick="calculateTotal()">Inscription</label><br>
<label><input type="checkbox" name="extras" value="decoration" onclick="calculateTotal()">Decoration</label><br>
<label><input type="checkbox" name="extras" value="special" onclick="calculateTotal()">Special Frosting & Icing</label>
</fieldset>
<input type="text" name="total" readonly>
<input type="submit" value="Submit">
</form>
Here's a working example of your code. There were a few syntax errors as well noted above by eje211.
var calculator = document.querySelector("form");
function extras() {
// Object vs Array
var extrasPricing = {
candles: 5,
inscription: 10,
decoration: 25,
special: 50
}
var extrasCost = 0;
var extras = document.getElementsByName("extras");
for (var i = 0; i < extras.length; i++) {
if (extras[i].checked) {
var val = extras[i].value;
// Update here to add/remove value of checked item to previous checked item.
extrasCost += extrasPricing[val];
}
}
return extrasCost;
}
function calculateTotal() {
calculator.total.value = "$" + extras();
}
<form>
<fieldset>
<legend>Select Extras</legend>
<label><input type="checkbox" name="extras" value="candles" onclick="calculateTotal()">Candles</label><br>
<label><input type="checkbox" name="extras" value="inscription" onclick="calculateTotal()">Inscription</label><br>
<label><input type="checkbox" name="extras" value="decoration" onclick="calculateTotal()">Decoration</label><br>
<label><input type="checkbox" name="extras" value="special" onclick="calculateTotal()">Special Frosting & Icing</label>
</fieldset>
<input type="text" name="total">
<input type="submit" value="Submit">
</form>
As noted by others, your extrasPricing does need to be an object to more easily access it. You can also you documentQuerySelectorAll with your CSS selectors to select your checked elements.
The '...' is a spread operator that converts a NodeList (which is returned with documentQuerySelectorAll) to an array, which is then able to use the various array methods to map the values to a new array, then reduce the values to a total.
Reduce throws an error if the array is empty, so the ternary operator is used to return the reduce output if the array has an element (extrasCost.length > 0), or to return 0 if the array is empty.
function extras() {
const extrasPricing = {
candles: 5,
inscription: 10,
decoration: 25,
special: 50,
};
let extrasCost = [...document.querySelectorAll('input[name=extras]:checked')]
.map((el) => extrasPricing[el.value])
return extrasCost.length > 0 ? extrasCost.reduce((total, num) => total + num) : 0;
}
function calculateTotal() {
calculator.total.value = '$' + extras();
}
<form>
<fieldset>
<legend>Select Extras</legend>
<label><input type="checkbox" name="extras" value="candles" onclick="calculateTotal()">Candles</label><br>
<label><input type="checkbox" name="extras" value="inscription" onclick="calculateTotal()">Inscription</label><br>
<label><input type="checkbox" name="extras" value="decoration" onclick="calculateTotal()">Decoration</label><br>
<label><input type="checkbox" name="extras" value="special" onclick="calculateTotal()">Special Frosting & Icing</label>
</fieldset>
<input type="text" name="total">
<input type="submit" value="Submit">
</form>
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.
I have 5 textbox in html. I want to merge their values. All of them have one name. How can I do it?
<input type="text" name="textbox1">
<input type="text" name="textbox1">
<input type="text" name="textbox1">
<input type="text" name="textbox1">
<input type="text" name="textbox1">
Get the values as an array, and join it
var val = [].map.call( document.getElementsByName('textbox1'), (el) => el.value ).join('');
var values = [].map.call( document.getElementsByName('textbox1'), (el) => el.value ).join('');
console.log(values)
<input type="text" name="textbox1" value="a1-">
<input type="text" name="textbox1" value="a2-">
<input type="text" name="textbox1" value="a3-">
<input type="text" name="textbox1" value="a4-">
<input type="text" name="textbox1" value="a5-">
If you want to select by the name attribute of your inputs, use getElementsByName like this:
var inputs = document.getElementsByName("textbox1");
var inputValues = "";
for(var index=0; index < inputs.length; index++) {
inputValues += inputs[index].value;
}