Add/remove textbox value when checkbox change - javascript

I have the following jquery code where i want to remove the value from the textfield if the checkbox is unchecked and add if it is checked.
initially all the values comes in the textbox as the ^ seperator. and all checkboxes checked
here is y piece of code:
$(document).on('change','._invoice',function() {
var mystr = $(this).attr('data-id').is(":checked");
if(mystr) {
var returnVal = confirm("Are you sure?");
$(this).attr("checked", returnVal);
}
});
});
Text field values and i also want to remove the separator and add the name at the last with ^ as separator.
Robert Berenson^Nancy Foster^Richard Gourhan^LORI HEDMAN^Pui Hoang^Linda Lee^Kristen McDonald^Matthew Miller^Tricia Roland^Terry West

A simple way is that change text of textbox on checkbox change event. Then means you need to get text of every checked checkbox and set it to textbox, when any checkbox is changed.
$(".check").change(function(){
var text = "";
$(".check:checked").each(function(){
text += text != "" ? "^" : "";
if ($(this).prop("checked"))
text += $(this).val();
});
$(".text").val(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="check" value="Text1" />
<input type="checkbox" class="check" value="Text2" />
<input type="checkbox" class="check" value="Text3" />
<input type="checkbox" class="check" value="Text4" />
<input type="checkbox" class="check" value="Text5" />
<br/>
<input type="text" class="text" />

var txt = document.getElementById( 'droptxt' ),
content = document.getElementById( 'content' ),
list = document.querySelectorAll( '.content input[type="checkbox"]' ),
quantity = document.querySelectorAll( '.quantity' );
txt.addEventListener( 'click', function() {
content.classList.toggle( 'show' )
} )
window.onclick = function( e ) {
if ( !e.target.matches( '.list' ) ) {
if ( content.classList.contains( 'show' ) ) content.classList.remove( 'show' )
}
}
list.forEach( function( item, index ) {
item.addEventListener( 'click', function() {
calc()
} )
} )
function calc() {
for ( var i = 0, arr = []; i < list.length; i++ ) {
let spanArray = [];
document.querySelectorAll('span').forEach(element => {
spanArray.push(element.innerHTML);
});
if ( list[ i ].checked ) arr.push( list[ i ].value + " "+ spanArray)
}
txt.value = arr.join(', ')
}
h1 {
color: #0000ff;
}
#droptxt {
padding: 8px;
width: 300px;
cursor: pointer;
box-sizing: border-box
}
.dropdown {
position: relative;
display: inline-block
}
.content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 200px;
overflow: auto;
box-shadow: 0 8px 16px 0 rgba(0, 0, 0, .2);
z-index: 1
}
.content div {
padding: 10px 15px
}
.content div:hover {
background-color: #ddd
}
.show {
display: block
}
<h1>KIAAT</h1>
<b>Adding/Removing Checkbox Values into TextArea</b>
<br><br>
<input type="text" id="droptxt" class="list" placeholder="Select the values" readonly>
<div id="content" class="content">
<div id="market" class="list">
<label><input type="checkbox" id="market" class="list" value="apple" /> Apple</label>
</div>
<div class="list">
<label><input type="checkbox" id="banana" class="list" value="Banana" /> Banana</label>
</div>
<div class="list">
<label><input type="checkbox" id="pineapple" class="list" value="Pineapple" /> Pineapple</label>
</div>
</div>

Related

How to fix: adlistener for radio button for if else calculation

I'm trying to create a BMR calculation embedded in my site. I have it working except for the gender portion (if male vs female, different calculations)
I understand that I need an adlistener but doesn't seem to be working. I think I am not referencing it properly.
Here's my code:
var theForm = document.forms["RMRform"];
var bmr;
function RMRcalc() {
var weight = document.getElementById("weight").value;
var height = document.getElementById("height").value;
var age = document.getElementById("age").value;
var gender = document.getElementById("gender").value;
var rad = document.myForm.myRadios;
var prev = null;
for (var i = 0; i < rad.length; i++) {
rad[i].addEventListener('change', function() {
(prev) ? console.log(prev.value): null;
if (this !== prev) {
prev = this;
}
console.log(this.value)
});
}
var activitylevel = new Array();
activitylevel["sedentary"] = 1.2;
activitylevel["low"] = 1.3;
activitylevel["moderate"] = 1.5;
activitylevel["high"] = 1.7;
function getActivityLevel() {
var activityLevelamount = 0;
var theForm = document.forms["RMRform"];
var selectedActivity = theForm.elements["activity"];
activityLevelamount = activitylevel[selectedActivity.value];
return activityLevelamount;
}
if (i = this) {
bmr = ((10 * weight) + (6.25 * height) - (5 * age) - 161) * getActivityLevel();
} else {
bmr = ((10 * weight) + (6.25 * height) - (5 * age) + 5) * getActivityLevel();
}
}
document.getElementsByTagName("button")[0].addEventListener("click", function() {
RMRcalc();
document.getElementById('results').innerHTML = bmr;
})
body {
font: 15px gothic, sans-serif;
letter-spacing: 1px;
}
input {
width: 100%;
}
input[type=number] {
border: none;
border-bottom: 1px solid grey;
}
button[type=button] {
background-color: #ddcecb;
border: none;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
color: #95483e;
padding: 16px 32px;
text-decoration: none;
letter-spacing: 1px;
margin: 4px 2px;
}
input[type=text]:focus {
border: 1px solid #555;
}
.form-inline label {
margin: 5px 10px 5px 0;
}
#media (max-width: 800px) {
.form-inline input {
margin: 10px 0;
}
.form-inline {
flex-direction: column;
align-items: stretch;
}
<form action="" id="RMRform">
<label for='gender' class="inlinelabel">
Female </label>
<input type="radio" id="gender" name="gender" value="fem" checked onclick="RMRcalc()" /><br>
<label for='gender' class="inlinelabel">
Male </label>
<input type="radio" id="gender" name='gender' value="masc" onclick="RMRcalc()" /> <br> Weight (kg):<br>
<input type="number" id="weight"><br><br> Height (cm):<br>
<input type="number" id="height"><br><br> Age (years):<br>
<input type="number" id="age"><br><br> Activity Level:
<select id="activity" name="activity">
<option value="sedentary">sedentary (1-2x/week)</option>
<option value="low">low (2-3x/week)</option>
<option value="moderate">moderate (3-4x/week)</option>
<option value="high">high (5x/week)</option>
</select>
</form> <br>
<button type="button" onclick="">
calculate</button>
<p>Your Daily Estimated Requirements</p>
<div id="results"></div>
With this, there's just no calculation showing.
Thanks in advance!
A closing } is missing for the #media query.
There shouldn't be a variable declaration in your if condition: if (var i=this). Remove the var.
Both of your radio input have the same id="gender". Id's should be unique. Consider using a class instead. This will cause problems when you later use the gender variable for your if male vs female calculations because of this selector:
var gender = document.getElementById("gender").value;
For rad to be defined in your loop...
var rad = document.myForm.myRadios;
...you'll need to change myRadios to gender, because that's the name of your radio inputs. You'll also need to give your form the name myForm.
<form action="" id="RMRform" name="myForm">
Perhaps you're looking for something in this region...
function calc () {
const gender = document.querySelector('input[name="gender"]:checked').value,
weight = document.getElementById('weight').value,
height = document.getElementById('height').value,
age = document.getElementById('age').value,
activity = document.getElementById('activity').value;
// calculate base metric value
let metricBase = ((10 * weight) + (6.25 * height) - (5 * age));
// calculate per gender
metricBase = (gender === 'fem') ? metricBase - 161 : metricBase + 5;
// calculate with inline activity values
const bmr = Math.round( metricBase * parseFloat(activity) );
// format caloric intake output
document.getElementById('results').innerHTML = `${bmr.toLocaleString()} calories/day`;
}
// prevents form change listener until after first calculation
let firstCalc = true;
document.getElementById('calc').addEventListener('click', () => {
if (firstCalc) document.querySelector('form').onchange = calc;
firstCalc = false;
calc();
}, false);
body {
}
body, input {
font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;
font-size: 14px;
letter-spacing: 1px;
}
input[type="radio"] {
display: inline-block;
width: 1rem;
}
input[type="number"] {
border: none;
border-bottom: 1px solid #ccc;
}
.group {
padding: .5rem 0;
}
<form>
<div class="group">
<label class="radio">
<input type="radio" name="gender" value="fem" checked />
Female
</label>
<label class="radio">
<input type="radio" name='gender' value="masc" />
Male
</label>
</div>
<div class="group">
<label for="weight">Weight (kg):</label>
<input type="number" id="weight" value="79" />
</div>
<div class="group">
<label for="weight">Height (cm):</label>
<input type="number" id="height" value="172" />
</div>
<div class="group">
<label for="weight">Age (years):</label>
<input type="number" id="age" value="22" />
</div>
<div class="group">
<label for="activity">Activity Level:</label>
<select id="activity">
<option value="1.2" selected>Sedentary (1-2x/week)</option>
<option value="1.3">Low (2-3x/week)</option>
<option value="1.5">Moderate (3-4x/week)</option>
<option value="1.7">High (5x/week)</option>
</select>
</div>
<button type="button" id="calc">Calculate</button>
</form>
<p id="results"></p>
Here is what i see (i am quite new to JS so i may not see everything) :
There is no opening head tag (not sure if that's a problem).
The gender radio buttons both have the same id. IDs should be unique. And because of this my guess is that this code should only give you the value for fem no ?:
html:
<input type="radio" id="gender" name="gender" value="fem" checked
onclick="RMRcalc()" />
<input type="radio" id="gender" name='gender' value="masc"
onclick="RMRcalc()" />
js:
var gender = document.getElementById("gender").value;
In your for-loops i would use let instead of var, otherwise you might get in trouble someday. Checkout this post.
for (let i = 0; i < rad.length; i++) {
rad[i].addEventListener('change', function () {
I didn't understand this in your function RMRcalc : if (var i = this)

multiselect list with quantity option for each item

I have a free text field in my html page, but I want to fill it with given strings. So lets say I have strings, "apple", "banana" and "pineapple", and now I want to have a button "add content" that opens a modal box, or if it's easier simply a list embedded in my page, that gives me a list where I can select multiple items with the option to enter a quantity for each selected item and adds the selected strings to my text field. for example "3 x apple, 2 x pineapple"
I really appreciate any hint, because I'm clueless how to solve this in javascript / html
It's basically a shopping cart, but I couldn't find anything simple.
Try this:
var txt = document.getElementById( 'droptxt' ),
content = document.getElementById( 'content' ),
list = document.querySelectorAll( '.content input[type="checkbox"]' ),
quantity = document.querySelectorAll( '.quantity' );
txt.addEventListener( 'click', function() {
content.classList.toggle( 'show' )
} )
// Close the dropdown if the user clicks outside of it
window.onclick = function( e ) {
if ( !e.target.matches( '.list' ) ) {
if ( content.classList.contains( 'show' ) ) content.classList.remove( 'show' )
}
}
list.forEach( function( item, index ) {
item.addEventListener( 'click', function() {
quantity[ index ].type = ( item.checked ) ? 'number' : 'hidden';
calc()
} )
} )
quantity.forEach( function( item ) {
item.addEventListener( 'input', calc )
} )
function calc() {
for ( var i = 0, arr = []; i < list.length; i++ ) {
if ( list[ i ].checked ) arr.push( quantity[ i ].value + ' x ' + list[ i ].value )
}
txt.value = arr.join( ', ' )
}
#droptxt {
padding: 8px;
width: 300px;
cursor: pointer;
box-sizing: border-box
}
.dropdown {
position: relative;
display: inline-block
}
.content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 200px;
overflow: auto;
box-shadow: 0 8px 16px 0 rgba(0, 0, 0, .2);
z-index: 1
}
.quantity {
float: right;
width: 40px
}
.content div {
padding: 10px 15px
}
.content div:hover {
background-color: #ddd
}
.show {
display: block
}
<p>Click on the below text field:</p>
<div class="dropdown">
<input type="text" id="droptxt" class="list" readonly>
<div id="content" class="content">
<div class="list">
<input type="checkbox" id="apple" class="list" value="Apple" />
<label for="apple" class="list">Apple </label>
<input type="hidden" class="list quantity" min="1" value="1" />
</div>
<div class="list">
<input type="checkbox" id="banana" class="list" value="Banana" />
<label for="banana" class="list">Banana </label>
<input type="hidden" class="list quantity" min="1" value="1" />
</div>
<div class="list">
<input type="checkbox" id="pineapple" class="list" value="Pineapple" />
<label for="pineapple" class="list">Pineapple </label>
<input type="hidden" class="list quantity" min="1" value="1" />
</div>
</div>
</div>

form enable by input radio id (checked)

I have two forms. I want one of them to be enabled by the user choose through one of the radio buttons above.
What I want to do is to get the value of radio button and through this value make one of the forms enable.
So I try with JavaScript and input radio ID but I had no success:
<script>
window.addEventListener('load', init);
function init(){
var radio = document.getElementsByName ("questions");
for (var i=0; i<radios.length; i++) {
if(radio[i].getElementById.checked == "questions_1") {
radio[i].addEventListener(seleccionar);
}
}
function trigger() {
elementsForm = document.forms['question'].elements;
for (var y=0; y<elementsForm.length; y++) {
elementsForm[y].disabled=false;
}
}
</script>
Here's my code (HTML and CSS):
.category_1 {
height: 50px;
padding-top: 2%;
}
.question {
display: inline-flex;
margin-left: 5%;
}
.q-text {
font-weight: 600;
}
.q1 {
width: 44%;
}
.q2 {
width: 44%;
}
.form {
display: inline-flex;
margin-left: 5%;
}
.form.q1 {
width: 44%;
}
.form.q2 {
width: 44%;
}
.data {
margin-top: 5%;
}
.data label {
opacity: 0.5;
}
input[type=text] {
width: 100%;
}
select {
width: 100%;
}
textarea {
width: 98%;
}
input[type=submit] {
display: block;
margin: auto;
}
<body>
<div class="category_1">
<div class="question q1"><input type="radio" name="question" value="question_1" id="question_1">
<div class="q-text">QUESTION 1</div></div>
<div class="question q2"><input type="radio" name="question" value="question_2" id="question_2">
<div class="q-text">QUESTION 2</div></div>
</div>
<div class="form q1">
<form name="q1" method="post" action="">
<div class ="data">
<label for="others">Name:</label>
<input type="text" name="name" disabled>
</div>
<div class="data">
<label for="others">Select an item:</label>
<select name="items-q1" disabled>
<option value="it1">item 1</option>
<option value="it2">item 2</option>
<option value="it3">item 3</option>
<option value="it4">item 4</option>
</select>
</div>
<div class="data">
<label for="others">Anything else?</label>
<textarea name="more" disabled></textarea>
</div>
<div class="data">
<input type="submit" value="submit" disabled>
</div>
</form>
</div>
<div class="form q2">
<form name="q2" method="post" action="">
<div class ="data">
<label for="others">Name:</label>
<input type="text" name="name" disabled>
</div>
<div class ="data">
<label for="others">Choose an option:</label><br>
<input type="radio" name="option" value="o1" disabled><label for="others">1</label>
<input type="radio" name="option" value="o2" disabled><label for="others">2</label>
</div>
<div class="data">
<label for="others">Anything else?</label>
<textarea name="more" disabled></textarea>
</div>
<div class="data">
<input type="submit" value="submit" disabled>
</div>
</form>
</div>
</body>
I'd really appreciate any suggestions.
First of all i noticed your are getting the radios by the wrong name
its "question" not "questions"
<script>
var rad = document.getElementsByName('question');
for(var i = 0; i < rad.length; i++) {
rad[i].onclick = function() {
if(this.value == "questions_1") {
//input logic to display form
//This is where you run isTrue() Function
isTrue(data);
}
else{
//This is where you run isFalse() function
isFalse(data);
}
};
}
//Function to run if its true
function isTrue(data){
//something equals something
}
//Function to run if its false
function isFalse(data){
//something equals something
}
</script>
Reference Link
<script>
var rad = document.getElementsByName('question');
for(var i = 0; i < rad.length; i++) {
rad[i].onclick = function () {
if(this.value == "question_1") {
e1();
}else {
e2();
}
};
}
function e1() {
var eform1 = document.querySelectorAll('.q1 input[type=text], .q1 select, .q1 textarea, .q1 input[type=submit]');
for(var i = 0; i < eform1.length; i++) {
eform1[i].disabled = false;
}
}
function e2() {
var eform2 = document.querySelectorAll('.q2 input[type=text], .q2 input[type=radio], .q2 textarea, .q2 input[type=submit]');
for(var i = 0; i < eform2.length; i++) {
eform2[i].disabled = false;
}
}
</script>

JavaScript - how to change checkbox background?

I want to change background of checkbox without using jQuery (if is that possible of course), because I'm not familiar with that library.
HTML:
<form name="checkBox">
<input onchange="checkbox()" type="checkbox" class="cbox" />
</form>
JS:
function checkbox(){
var checkbox = document.getElementByClass('cbox');
if(document.getElementById('cbox').checked === true){
checkbox.style.background = "url('uncheck.png')";
}else{
checkbox.style.background = "url('check.png')";
}
}
You are mixing class names and ID's. Try this.
HTML:
<form name="checkBox">
<input onchange="checkbox()" type="checkbox" id="cbox" />
</form>
JS:
function checkbox(){
var checkbox = document.getElementById('cbox');
if(checkbox.checked === true){
checkbox.style.background = "url('uncheck.png')";
}else{
checkbox.style.background = "url('check.png')";
}
}
How about a pure CSS solution without any need to use images: http://jsfiddle.net/7qcE9/1/.
HTML:
<form name="checkBox">
<input type="checkbox" id = "checkbox1" />
<label for = "checkbox1"></label>
</form>
CSS:
form > input[type = "checkbox"] {
display: none;
}
form > label {
display: inline-block;
width: 20px;
height: 20px;
border: 1px solid #000;
border-radius: 3px;
font-size: 20px;
text-align: center;
cursor: pointer;
}
form > input[type = "checkbox"]:checked + label:before {
content:'\2714';
}
You can pass a reference to the checkbox using this in the inline handler as follows:
html
<form name="checkBox">
<input onchange="checkbox(this)" type="checkbox" class="cbox" />
</form>
js
function checkbox(elm){ // elm now refers to the checkbox
if(elm.checked === true){
elm.style.background = "url('uncheck.png')";
}else{
elm.style.background = "url('check.png')";
}
}
So that you can use the function for n number of elements.

How can I only select one radio button?

I am creating a review-control and using radiobutton for grade selection. I wrote some simple js to add a diffrent class when a radiobutton is checked.
The problem is that you can check every radio button, I want the user only to check one value. I writing this in javascript, but jQuery is welcome or a smartare solution.
Demo : http://jsfiddle.net/cbqt8/5/
HTML:
<div class="reviews">
<label class="input-check">
<input onchange="change_state(this)" type="radio" value="1" name="review[rating]" /> Bad
</label>
<label class="input-check">
<input onchange="change_state(this)" type="radio" value="2" name="review[rating]" /> Its okey
</label>
<label class="input-check">
<input onchange="change_state(this)" type="radio" value="3" name="review[rating]" /> Great
</label>
<label class="input-check">
<input onchange="change_state(this)" type="radio" value="4" name="review[rating]" /> Awesome
</label>
<label class="input-check">
<input onchange="change_state(this)" type="radio" value="5" name="review[rating]" />Super
</label>
</div>
JavaScript:
function change_state(obj) {
if (obj.checked) {
//if radiobutton is being checked, add a "checked" class
obj.parentNode.classList.add("checked");
}
else {
//else remove it
obj.parentNode.classList.remove("checked");
}
}
CSS:
/*reviews box*/
.reviews{
padding: 25px;
margin:0;
}
/*this is the style of an radio "button"*/
.input-check {
display: inline-block;
height:20px;
padding:5px 8px;
background:green;
width:90px;
color:white;
text-align: center;
}
/* This is the style for a radio "button" */
.input-check.checked{
background:red;
color:black;
font-weight:bold;
}
/*Hide the radiobutton*/
.input-check input {
display:none;
}
You got to remove the checked class for previously checked item.
jsFiddle: http://jsfiddle.net/P8jB8/
function change_state(obj) {
if (obj.checked) {
var checkedNodes = getElementsByClassName(document, "checked");
for (var i=0;i<checkedNodes.length;i++) {
checkedNodes[i].classList.remove("checked");
}
//if radiobutton is being checked, add a "checked" class
obj.parentNode.classList.add("checked");
}
else {
//else remove it
obj.parentNode.classList.remove("checked");
}
}
function getElementsByClassName(node,classname) {
if (node.getElementsByClassName) { // use native implementation if available
return node.getElementsByClassName(classname);
} else {
return (function getElementsByClass(searchClass,node) {
if ( node == null )
node = document;
var classElements = [],
els = node.getElementsByTagName("*"),
elsLen = els.length,
pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"), i, j;
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
})(classname, node);
}
}
​

Categories