Display value of checkbox in textarea - javascript

I have here a code that will display the value of the checkbox when checked. My problem is I don't know how I will add up all the numbers, that when I checked a checkbox the number or value will display automatically to the text area and when I checked another checkbox it will add up to the first checkbox that I checked and when I checked another checkbox it should also add up from the first two checkbox. How will I do that?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function add_sub(el)
{
if (el.checked)
{
var total = el;
total.form.elements['type'].value+=el.value;
}
else
{
var re=new RegExp('(.*)'+el.value+'(.*)$');
el.form.elements['type'].value=el.form.elements['type'].value.replace(re,'$1$2');
}
}
</script>
</head>
<body>
<form name="form1" method=post>
<textarea name="type" rows="5" cols="35" onclick="this.focus();this.select();"></textarea><br>
<input type="checkbox" name="mis1" id="id1" value="1" onclick="add_sub(this);"><label>1</label><br>
<input type="checkbox" name="mis2" id="id2" value="2" onclick="add_sub(this);"><label>2</label><br>
<input type="checkbox" name="mis6" id="id3" value="3" onclick="add_sub(this);"><label>3</label><br>
<input type="checkbox" name="mis6" id="id4" value="4" onclick="add_sub(this);"><label>4</label>
</form>
</body>

Please check this fiddle if this is what you meant:
http://jsfiddle.net/zyfmt4at/5/
this is the script:
var currNum = 0;
var txtArea = document.getElementById("txtArea");
var form = document.getElementById("mainForm");
function add_sub(el){
debugger;
if (el.checked)
{
currNum += parseInt(el.value,10);
}
else
{
currNum -= parseInt(el.value,10);
}
txtArea.value = currNum;
}
form.addEventListener("click", function(ev){
if(ev.target.getAttribute("type") == "checkbox"){
add_sub(ev.target);
}
},false);
this is the HTML:
<body>
<form id="mainForm" name="form1" method=post>
<textarea id="txtArea" name="type" rows="5" cols="35" onclick="this.focus();"></textarea><br>
<input type="checkbox" name="mis1" id="id1" value="1"><label>1</label><br>
<input type="checkbox" name="mis2" id="id2" value="2"><label>2</label><br>
<input type="checkbox" name="mis6" id="id3" value="3"><label>3</label><br>
<input type="checkbox" name="mis6" id="id4" value="4"><label>4</label>
</form>
</body>

The solutions proposed above are based on an assumption that the checkbox values are numbers, in case you are in need of string values. You may suggest this.
function add_sub(el)
{
var cbs = document.getElementById('checkboxes').getElementsByTagName('input');
var textareaValue = '';
for (var i = 0, len = cbs.length; i<len; i++) {
if ( cbs[i].type === 'checkbox' && cbs[i].checked) {
textareaValue += cbs[i].value + ' ';
}
}
document.getElementById('textarea').value = textareaValue;
}
and
<textarea id="textarea" name="type" rows="5" cols="35" onclick="this.focus();this.select();"></textarea><br>
<div id="checkboxes">
<input type="checkbox" name="mis1" id="id1" value="1" onclick="add_sub(this);"><label>1</label><br>
<input type="checkbox" name="mis2" id="id2" value="2" onclick="add_sub(this);"><label>2</label><br>
<input type="checkbox" name="mis6" id="id3" value="3" onclick="add_sub(this);"><label>3</label><br>
<input type="checkbox" name="mis6" id="id4" value="4" onclick="add_sub(this);"><label>4</label>
</div>
And the working plunker:
http://plnkr.co/edit/HWHRsBn7s7vJ9KI4UauU

Some tips:
Don't listen to click events to detect changes in checboxes. They can change in other ways, e.g. with the keyboard. You can listen to change events instead.
Don't use event handler content attributes in the HTML source. Add event listeners using JS.
Don't add the same event listener to all events. Delegate it to a common ancestor instead.
br elements are ugly. Better use display: block.
var sum = 0,
form = document.forms.form1,
text = form1.elements.type;
text.addEventListener('focus', text.select.bind(text));
form.addEventListener('change', function(e) {
if(e.target.type == 'checkbox') {
sum += e.target.value * (e.target.checked ? 1 : -1);
text.value = sum;
}
});
label { display: block; }
<form name="form1" method="post">
<textarea name="type" rows="5" cols="35">0</textarea>
<label><input type="checkbox" name="mis1" id="id1" value="1">1</label>
<label><input type="checkbox" name="mis2" id="id2" value="2">2</label>
<label><input type="checkbox" name="mis6" id="id3" value="3">3</label>
<label><input type="checkbox" name="mis6" id="id4" value="4">4</label>
</form>

Related

How to get Selected Checkbox value by ID

Currently my code works well with the input name, I can get the input value by input name
But I want my script to retrieve the input value with id input and not with name input?
here my code :
$(document).ready(function () {
$('input[type="checkbox"]').click(function () {
getSelectedCheckBoxwithValueText("test")
});
var getSelectedCheckBoxwithValueText = function (name1) {
var data = $('input[name="' + name1 + '"]:checked');
if (data.length > 0) {
var resultdata='' ;
data.each(function () {
var selectedValue = $(this).val();
resultdata += $('label[for="cb-' + selectedValue + '"]').text() + "<br/>";
});
$("#divchecked").html(resultdata);
}
else {
$("#divchecked").html("No Check box selected");
}
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<body>
checked:
<input type="checkbox" id="c1" name="test" value="cricket" />
<label for="cb-cricket">Cricket</label>
<input type="checkbox" id="c2" name="test" value="swimming" />
<label for="cb-swimming">Swimming</label>
<input type="checkbox" id="c3" name="test" value="blog" />
<label for="cb-blog">Blog</label>
<input type="checkbox" id="c4" name="test" value="coding" />
<label for="cb-coding">Coding</label>
<br/>
<br/>
Selected checkbox:<br />
<div id="divchecked"></div>
</body>
jsfiddle: https://jsfiddle.net/showcode/L64nauo0/5/
You can use
var data = $('input[id=^"c"]:checked');
Only if the IDs not pseudos (so you really this IDs use), and do not use IDs thagt starts with c
This is a little hacker solution, but works!
There is no need to use id or name to select the checkboxes and/or their related labels. You can simplify your code like so
Select all the checkboxes from the DOM and listen to change event on them.
When the value of a checkbox changes, you get all selected checkboxes
using .filter().
And then get the text of the related labels using .map() and .get().
$(document).ready(function () {
let $checkboxes = $('input[type="checkbox"]');
$checkboxes.change(function () {
let labels = $checkboxes.filter(':checked').map(function(){
return $(this).next('label').text().trim();
}).get();
$("#divchecked").html(labels.join('<br />') || "No Check box selected");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
checked:
<input type="checkbox" id="c1" name="test" value="cricket" />
<label for="c1">Cricket</label>
<input type="checkbox" id="c2" name="test" value="swimming" />
<label for="c2">Swimming</label>
<input type="checkbox" id="c3" name="test" value="blog" />
<label for="c3">Blog</label>
<input type="checkbox" id="c4" name="test" value="coding" />
<label for="c4">Coding</label>
<br/>
<br/>
Selected checkbox:<br />
<div id="divchecked"></div>

Need help on Checkbox onclick jquery

trying to learn jquery and made a simple checkbox with a function where you can make all the options read-only checking on "none of the above" button.
<html>
<body>
<form id="diagnosedForm">
<div>
<input type="checkbox" value="1"/>1
<br/>
<input type="checkbox" value="2"/>2
<br/>
<input type="checkbox" value="3"/>3
<br/>
</form><br/>
<input type="checkbox" value="" onclick="enableDisableAll(this);"/>None of the above
<script src="script.js">
</script>
</body>
</html>
function enableDisableAll(e) {
var own = e;
var form = document.getElementById("diagnosedForm");
var elements = form.elements;
for (var i = 0 ; i < elements.length ; i++) {
if(own !== elements[i] ){
if(own.checked == true){
elements[i].disabled = true;
elements[i].checked = false;
}else{
elements[i].disabled = false;
}
}
}
}
this will be the output
and the last checkbox will make it read-only
I want the same result but not putting onclick on the html file, instead using jquery to work it out.
You can assign an id to "none of the above" checkbox and then in your script.js you can do something like this:
// script.js
// Run enableDisableAll() on toggle click
$('#toggle').click(enableDisableAll)
function enableDisableAll() {
// Find all input elements inside "diagnosedForm"
const elements = $('#diagnosedForm input')
// Map thru inputs and toggle enable/disable state
elements.map((_, el) => {
$(el).prop('checked', false) // Reset checkboxes
$(el).prop('disabled', (i, v) => !v)
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<form id="diagnosedForm">
<div>
<input type="checkbox" value="1" />1
<br/>
<input type="checkbox" value="2" />2
<br/>
<input type="checkbox" value="3" />3
<br/>
</div>
</form>
<br/>
<input id="toggle" type="checkbox" value="" /> None of the above
</body>
</html>

addEventListener to multiple checkboxes

Below, I have a simple form that has 4 checkboxes acting as seats. What I am trying to do is when a visitor chooses, say, seat checkboxes with IDs A2 and A4, I want those IDs and their total value to be shown instantly after clicking inside a paragraph with which have a name called id="demo". When a button [Reserve Now] has been clicked, the total value should be assigned to a variable called $TotalCost.
How can I accomplish this? Here's my code:
<!DOCTYPE html>
<html>
<body>
<h2>Please choose a seat to book</h2>
<form action="/action_page.php" method="post">
<input type="checkbox" name="vehicle" id="A1" value="$100">$100<br>
<input type="checkbox" name="vehicle" id="A2" value="$65"> $65<br>
<input type="checkbox" name="vehicle" id="A3" value="$55"> $55<br>
<input type="checkbox" name="vehicle" id="A4" value="$50"> $50<br>
<p id="demo">
Selected Seat(s)
<br>
<br>
Total: USD <input type="submit" value="Reserve Now">
</form>
</p>
<script>
document.getElementById("A1").addEventListener("click", displayCheck);
function displayCheck() {
document.getElementById("demo").innerHTML = ;
}
</script>
</body>
</html>
Here's one approach to setting up event listeners on checkboxes. I used document.querySelectorAll("input[type='checkbox']"); to fetch all of the checkbox elements from the DOM and a loop to add a listener to each checkbox. A selections object can keep track of which items have been checked. When a checkbox is clicked on, the item values are added to the object by key. When the checkbox is off, the item is deleted from the object. Whenever an action happens, the DOM is updated with all relevant information based on the contents of selections.
This example is just a quick sketch to give you the idea. You'll need another event listener for your submit button to handle sending the form data to your PHP script. I'll leave that as an exercise.
Note that the HTML you've provided is invalid because nesting is broken. A HTML validator can be helpful for fixing these sort of problems.
var selections = {};
var checkboxElems = document.querySelectorAll("input[type='checkbox']");
var totalElem = document.getElementById("seats-total");
var seatsElem = document.getElementById("selected-seats");
for (var i = 0; i < checkboxElems.length; i++) {
checkboxElems[i].addEventListener("click", displayCheck);
}
function displayCheck(e) {
if (e.target.checked) {
selections[e.target.id] = {
name: e.target.name,
value: e.target.value
};
}
else {
delete selections[e.target.id];
}
var result = [];
var total = 0;
for (var key in selections) {
var listItem = "<li>" + selections[key].name + " " +
selections[key].value + "</li>";
result.push(listItem);
total += parseInt(selections[key].value.substring(1));
}
totalElem.innerText = total;
seatsElem.innerHTML = result.join("");
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>...</title>
</head>
<body>
<h2>Please choose a seat to book</h2>
<form action="/action_page.php" method="post">
<input type="checkbox" name="vehicle" id="A1" value="$100">$100<br>
<input type="checkbox" name="vehicle" id="A2" value="$65"> $65<br>
<input type="checkbox" name="vehicle" id="A3" value="$55"> $55<br>
<input type="checkbox" name="vehicle" id="A4" value="$50"> $50<br>
<p>Selected Seat(s)</p>
<!-- container for displaying selected seats -->
<ul id="selected-seats"></ul>
<div>
Total: $<span id="seats-total">0</span> USD
<input type="submit" value="Reserve Now">
</div>
</form>
</body>
</html>
Often, you'll want to generate the elements dynamically and add event listeners. Here's a toy example:
for (let i = 0; i < 1000; i++) {
const checkbox = document.createElement("input");
document.body.appendChild(checkbox);
checkbox.type = "checkbox";
checkbox.style.margin = 0;
checkbox.addEventListener("mouseover", e => {
e.target.checked = !e.target.checked;
});
checkbox.addEventListener("mouseout", e =>
setTimeout(() => {
e.target.checked = !e.target.checked;
}, 1000)
);
}
See also event delegation which lets you add a single listener on many child elements.
Here is a starter... About the math addition.
Since your question was tag with jQuery, It's a jQuery way.
Notice that the form will only send something like {vehicle:['on','','on','on']}... Which is way far from anyone would want to send to the server. But that is another question.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<h2>Please choose a seat to book</h2>
<form action="/action_page.php" method="post">
<input type="checkbox" name="vehicle" id="A1" value="100">$100<br>
<input type="checkbox" name="vehicle" id="A2" value="65"> $65<br>
<input type="checkbox" name="vehicle" id="A3" value="55"> $55<br>
<input type="checkbox" name="vehicle" id="A4" value="50"> $50<br>
Selected Seat(s): <span id="seats"></span>
<br>
<br>
Total: $<span id="demo">0.00</span> USD <input type="submit" value="Reserve Now">
</form>
<script>
$(document).ready(function(){
var total=0;
var seats=[];
$("form input").on("click",function(){
var id=$(this).attr("id");
if($(this).is(":checked")){
total+=parseInt($(this).val());
seats.push(id);
}else{
total-=parseInt($(this).val());
seats.splice(seats.indexOf(id),1);
}
$("#demo").text(total.toFixed(2));
$("#seats").html(seats.sort().join(","));
});
});
</script>
</body>
</html>

How to access the value of a radio button

I am trying to access the value of a radio button using HTML and Javascript to make a simple quiz but it does not seem to be working. Here is my code:
function check() {
var a = document.getElementById("test").value
if (a === "one") {
alert("Correct!")
} else {
alert("Wrong!")
}
}
<h1><center>Simple Quiz</center></h1>
<br>
1) What is 1 + 1?
<br>
<form>
<input type="radio" name="one" id="test" value="one">1<br>
<input type="radio" name="one" id="test" value="two">2<br>
<input type="radio" name="one" id="test" value="three">3<br>
<button onclick="check()">Check</button>
</form>
It always says "Correct!" even when it is not. Does anyone know how to fix this?
Some points you are missing:
An id must be unique on the whole page
To check if a radio button is checked, use its checked attribute
function check() {
var two = document.getElementById("two");
if (two.checked) {
alert("Correct!")
} else {
alert("Wrong!")
}
}
<h1>
<center>Simple Quiz</center>
</h1>
<br> 1) What is 1 + 1?
<br>
<form>
<input type="radio" name="one" id="one" value="one">1<br>
<input type="radio" name="one" id="two" value="two">2<br>
<input type="radio" name="one" id="three" value="three">3<br>
<button onclick="check()">Check</button>
</form>
First, you cannot have the same id on multiple elements. Make to give your elements a unique id and if you need to give them all the same style you could use class instead.
Instead of checking the value of the radio button, you should check whether the radio button is checked.
Take a look at the example below.
function check() {
if (document.getElementById('test2').checked) {
alert('correct');
} else {
alert('wrong');
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Example</title>
</head>
<body>
<h1><center>Simple Quiz</center></h1>
<br>
1) What is 1 + 1?
<br>
<form>
<input type="radio" name="one" id="test1" value="one">1<br>
<input type="radio" name="one" id="test2" value="two">2<br>
<input type="radio" name="one" id="test3" value="three">3<br>
<button onclick="check()">Check</button>
</form>
</body>
</html>
you should not define more than one element with the same id that's a bad practice, you could improve your code function check() {
for (elemnt of document.getElementByClassName('test') ) { if (element.checked ) alert('correct');
else alert ("incrrect");}}
Them in the html you can do this
<input type="radio" class="test" value="1">
<input type="radio" class="test" value="2">
<input type="radio" class="test" value="3">

Function that hides a label depending on radio button

I'm trying to get a function working that hides a label in the form depending on the radio button option selected. Here's my code so far.
HTML
<form action="">
<input type="radio" id="test" value="first"> first<br>
<input type="radio" id="test" value="second"> second<br>
<input type="radio" id="test" value="third"> third
</form>
<label class="hidden">Hide this</label>
Javascript
var rbtn = document.getElementById("test");
var x = document.getElementsByClassName("hidden");
function hidelabel() {
if (rbtn == 'third') {
x.style.display='none';
}
}
You must fire your hide function after radio button clicked like this:
document.mainForm.onclick = function(){
var radVal = document.mainForm.rads.value;
if (radVal == 'third') {
document.getElementsByClassName("hidden")[0].style.display = 'none';
}
}
ps: document.getElementsByClassName returns an array. So you cannot use x.style.display='none';.
Working example: https://jsfiddle.net/5ts0dak4/
First name the radio button ID's with something decent:
<form action="">
<input type="radio" id="first" value="first"> first<br>
<input type="radio" id="second" value="second"> second<br>
<input type="radio" id="third" onclick="hide();" value="third"> third
</form>
<label class="hidden" id="hidden">Hide this</label>
Then try this:
function hide(){
var x = document.getElementById('hidden');
if(document.getElementById('third').checked) {
x.style.display='none';
}
}
You can test it here https://jsfiddle.net/o54mzrk5/
Try this one.
CSS:
<style type="text/css">
.hidden{ display:none; }
</style>
HTML:
<form action="">
<input type="radio" name="test" value="first" onclick="func(this, true);"> first<br>
<input type="radio" name="test" value="second" onclick="func(this, true);"> second<br>
<input type="radio" name="test" value="third" onclick="func(this, false);"> third
</form>
<label class="hidden">Hide this</label>
Script:
<script type="text/javascript">
func = function(ctrl, visible) {
if(visible)
document.getElementsByClassName("hidden")[0].style.display='block';
else
document.getElementsByClassName("hidden")[0].style.display='none';
};
</script>

Categories

Resources