Trying to make an if statement in JS that when one of the top 3 buttons changes, it checks which of the bottom 2 has the "active" class, and visa versa.
So when I click 30g it will check if option a or option b is active, and then change the price accordingly.
Any help would be greatly appreciated as I'm kind of a noob.
The problem is there are 2 rows of buttons (one to select the weight, and one to select option a or b). I know how it would work, I just don't know the syntax, this is what I want to happen but it's not coded right.
//this is shitty code of what I mean, but I don't know how to code in JS
if(button30g.isclicked && buttonOptionA.ContainsClass.Active)
{ Price=1.00; }
else if(button30g.isClicked && buttonOptionB.ContainsClass.Active)
{ Price=2.00; }
if(button70g.isclicked && buttonOptionA.ContainsClass.Active)
{ Price=3.50; }
else if(button70g.isClicked && buttonOptionB.ContainsClass.Active)
{ Price=4.00; }
if(button70g.isclicked && buttonOptionA.ContainsClass.Active)
{ Price=3.50; }
else if(button70g.isClicked && buttonOptionB.ContainsClass.Active)
{ Price=4.00; }
<!DOCTYPE html>
<html lang="en">
<head>
<style>
ul.nav a{
border: 2px solid #E1E8EE;
border-radius: 6px;
padding: 13px 20px;
font-size: 14px;
color: #5E6977;
background-color: #fff;
cursor: pointer;
transition: all .5s;
display: inline-block;
vertical-align: middle;
}
.activeBtn { color:grey; font-weight:1000; border: 2px solid grey; border-radius: 6px; }
</style>
</head>
<body>
<ul class="nav">
<li id="30" data-price="bird" onclick="myFunction()" class="activeBtn"><a>30g</a></li>
<li id="70" onclick="myFunction()"><a>70g</a></li>
<li id="90" onclick="myFunction()"><a>90g</a></li>
</ul>
<ul class="nav">
<li id="no" class="activeBtn"><a>option a</a></li>
<li id="yes"><a>option b</a></li>
</ul>
<br>
<div class="product-price">
<span id="price">148$</span>
</div>
</body>
<footer>
<script>
$(function() {
$( 'ul.nav li' ).on( 'click', function() {
$( this ).parent().find( 'li.activeBtn' ).removeClass( 'activeBtn' );
$( this ).addClass( 'activeBtn' );
});
});
</script>
<script>
function myFunction() {
const element = document.getElementById("30");
const element2 = document.getElementById("no");
const pricetag = document.getElementById("price");
if(((element.classList.contains("activeBtn"))==true)&&((element2.classList.contains("activeBtn"))==true))
{
pricetag.innerHTML = €1,00;
}
</script>
</footer>
</html>
The work that you want I have done it separately so check this out. This code works according to the option "yes" or "no" and shows the price.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.radioStyle{
border-color: blue;
border-width: thin;
border-style: solid;
width: 50%;
}
</style>
</head>
<body>
<div><input type="radio" name="grams" value="30" id = "30" onclick="myFunction()"> 30g</div>
<div><input type="radio" name="grams" value="70" id = "70" onclick="myFunction()"> 70g</div>
<div><input type="radio" name="grams" value="90" id = "90" onclick="myFunction()"> 90g </div>
<hr>
<input type="radio" name="option" value="yes" id ="yes" checked onclick="myFunction()"> yes<br>
<input type="radio" name="option" value="no" id = "no" onclick="myFunction()"> no<br>
<br>
<span id = "sp">
0$
</span>
</body>
<footer>
<script>
function setBorder(){
var siblings = document.querySelectorAll('input[name = "grams"]');
siblings.forEach(element => element.parentElement.className="");
var grams = document.querySelector('input[name = "grams"]:checked');
grams.parentElement.className = "radioStyle";
console.log(siblings);
console.log(grams);
}
function myFunction(){
setBorder();
var grams = document.querySelector('input[name = "grams"]:checked').value;
var option = document.querySelector('input[name = "option"]:checked').value;
var rate = 0;
if (option == "yes"){
if (grams == "30")
rate = 1.5;
else if (grams == "70")
rate = 2.5;
else if (grams == "90")
rate = 3.5;
}
else if (option == "no"){
if (grams == "30")
rate = 2;
else if (grams == "70")
rate = 3;
else if (grams == "90")
rate = 4;
}
document.getElementById("sp").innerHTML = rate*grams+"$";
}
</script>
</footer>
</html>
Related
Good morning. Improving this code I found it difficult to insert a custom radio with fonts.googleapis to show after the quiz verification function. Something like the attached image Do you have any suggestions? or better yet an example of code.... heartfelt thanks to the community, I wish you a good day to all and happy coding
var answers = ["1b"];
var rads, quiz; // need to be set after load
window.addEventListener("load",function() { // when page loads
quiz = document.getElementById("quiz");
rads = quiz.querySelectorAll("input[type=radio]"); // all radios in the quiz
document.getElementById("scoreButton").addEventListener("click",function(e) { // on click of scoreme
var score = 0;
for (var i=0;i<rads.length;i++) { // loop over all radios in the form
var rad = rads[i];
var idx = rad.name.substring(1)-1; //remove the q from the name - JS arrays start at 0
var checked = rad.checked;
var correct = rad.value==answers[idx];
if (correct) {
rad.closest("label").classList.toggle("correct");
}
else if (checked) {
rad.closest("label").classList.toggle("error")
}
}
});
});
.correct {
color: green;
font-weight: bold;
text-decoration: underline;
border-left: 2px solid green;
}
.error {
color: red;
font-weight: bold;
text-decoration: line-through;
border-left: 2px solid red;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<form id="quiz">
<div class="questions">
<dl id="1">
<dd><b>1. QUESTION.</b><br>
<label><input type="radio" name="q1" value="1a"> 1. WRONG</label><br>
<label><input type="radio" name="q1" value="1b"> 2. RIGHT</label><br>
<label><input type="radio" name="q1" value="1c"> 3. WRONG</label>
</dd>
</dl>
<input type="button" value="RESULT" id="scoreButton">
</div>
</form>
var answers = ["1b", "1c"];
var rads, quiz, cur, par;// need to be set after load
var ShowAnswer = true; // Try false
window.addEventListener("load", function() {
// when page loads
quiz = document.getElementById("quiz");
rads = quiz.querySelectorAll("input[type=radio]"); // all radios in the quiz
document
.getElementById("scoreButton")
.addEventListener("click", function(e) {
// on click of scoreme
cur = quiz.querySelector("input[type=radio]:checked");
par = cur.parentNode;
var score = 0;
for (var i = 0; i < rads.length; i++) {
// loop over all radios in the form
var rad = rads[i];
var idx = rad.name.substring(1) - 1; //remove the q from the name - JS arrays start at 0
var checked = rad.checked;
var correct = !(answers.indexOf(cur.getAttribute("value")) == -1);
rad.style.appearance = 'none';
document.getElementById("scoreButton").style.display = 'none';
if (!(answers.indexOf(rad.getAttribute('value')) == -1) && ShowAnswer) {
rad.parentNode.classList.add("correct");
rad.parentNode.innerHTML =
`<span class="material-icons-round correct c">check</span>` +
rad.parentNode.innerHTML;
}
if (correct) {
par.classList.add("correct");
par.innerHTML =
`<span class="material-icons-round correct c">check</span>` +
par.innerHTML;
} else if (checked) {
par.classList.add("error");
par.innerHTML =
`<span class="material-icons-round error e">close</span>` +
par.innerHTML;
}
}
});
});
.correct {
color: green;
font-weight: bold;
text-decoration: underline;
}
.c {
text-decoration: none;
border-left: 0px;
margin-left: -24px;
/*From https://fonts.googleapis.com/icon?family=Material+Icons+Round*/
}
.error {
color: red;
font-weight: bold;
text-decoration: line-through;
}
.e {
text-decoration: none;
border-left: 0px;
margin-left: -24px;
/*From https://fonts.googleapis.com/icon?family=Material+Icons+Round*/
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons+Round" rel="stylesheet">
<form id="quiz">
<div class="questions">
<dl id="1">
<dd><b>1. QUESTION.</b><br>
<label><input type="radio" name="q1" value="1a"> 1. WRONG</label><br>
<label><input type="radio" name="q1" value="1b"> 2. RIGHT</label><br>
<label><input type="radio" name="q1" value="1c"> 3. WRONG But shown as right due to value in js</label>
</dd>
</dl>
<input type="button" value="RESULT" id="scoreButton">
</div>
</form>
Here is a PEN
Edited with replacement of choose option hiding!
I'm trying to have my form show child elements if the parent is visible and I keep getting an "undefined" error with my child element, even though I have it defined. I'm trying to have set this up where:
Q1: Checked responses will show parent elements (divs).
Q2: Depending on this response, it'll show child elements (divs).
Is there a way to do this?
//Next Tab
function next() {
var formTabOne = document.getElementById("stepOne");
formTabOne.classList.add("formTrans");
formTabOne.addEventListener("transitionend", function({
target
}) {
if (target === formTabOne) {
target.classList.add("hidden");
target.classList.remove("formTrans");
document.getElementById("stepTwo").classList.remove("hidden");
}
})
}
//Prev Tab
function prev() {
var formTabTwo = document.getElementById("stepTwo");
formTabTwo.classList.add("formTrans");
formTabTwo.addEventListener("transitionend", function({
target
}) {
if (target === formTabTwo) {
target.classList.add("hidden");
target.classList.remove("formTrans");
document.getElementById("stepOne").classList.remove("hidden");
}
})
}
function process() {
var form = document.myForm;
var biz = document.getElementById("biz");
var career = document.getElementById("career");
var change = document.getElementById("change");
var eq = document.getElementById("eq");
var empathy = document.getElementById("empathy");
var pm = document.getElementById("pm");
var bizMgr = document.getElementsByClassName("bizMgr");
var bizEE = document.getElementsByClassName("bizEE");
//Q1 - Topics
document.querySelectorAll("#chkTopic input").forEach((el) => {
const contentID = el.id.replace("chk", "").toLowerCase()
document.getElementById(contentID).style.display = el.checked ? "block" : "none";
});
//Q2 - Employee Type
var q2value = "";
for (var i = 0; i < form.q2.length; i++) {
var answer = form.q2[i];
if (answer.checked) {
q2value = answer.value;
}
}
if (q2value == "1") {
if (biz.style.display = "block") {
bizMgr.style.display = "block";
bizEE.style.display = "block";
}
} else {
if (biz.style.display = "block") {
document.getElementsByClassName("bizEE").style.display = "block";
}
}
}
html {
scroll-behavior: smooth;
}
#formWrapper {
background-color: #eaeaea;
padding: 20px;
margin-bottom: 40px;
min-height: 300px;
}
#myForm {
width: 70%;
min-height: 280px;
margin: 0 auto;
padding: 20px;
background-color: #fff;
border: 1px solid #dedede;
box-sizing: border-box;
}
.formStep {
opacity: 1;
background: #fff;
}
.formTrans {
visibility: hidden;
opacity: 0;
transition: visibility 0s 200ms, opacity 200ms linear;
}
.hidden {
display: none;
}
#biz, #career, #change, #eq, #empathy, #pm, #pd {
display: none;
width: 100%;
min-height: 200px;
box-sizing: border-box;
margin-bottom: 30px;
border: 1px solid #000;
}
.bizMgr, .bizEE, .careerMgr, .careerEE, .changeMgr, .changeEE, .eqMgr, .eqEE, .empathyMgr, .empathyEE, .pmMgr, .pmEE, .pdMgr, .pdEE {
display: none;
}
<form name="myForm" id="myForm">
<input type="button" value="Skip This" onclick="formSkip();">
<br><br>
<!--Step 1-->
<div id="stepOne" class="formStep">
<b>Select the topic(s) you're interested in:</b><br>
<div id="chkTopic">
<input id="chkBiz" type="checkbox" value="1"><label for="chkBiz">Business Structure/Acumen</label><br>
<input id="chkCareer" type="checkbox" value="2"><label for="chkCareer">Career Development</label><br>
<input id="chkChange" type="checkbox" value="3"><label for="chkChange">Change</label><br>
<input id="chkEQ" type="checkbox" value="4"><label for="chkEQ">Emotional Intelligence</label><br>
<input id="chkEmpathy" type="checkbox" value="5"><label for="chkEmpathy">Empathy</label><br>
<input id="chkPM" type="checkbox" value="6"><label for="chkPM">Performance Management</label><br>
</div>
<br>
<button type="button" id="btnStepOne" onclick="next();">Next</button>
</div>
<!--Step 2-->
<div id="stepTwo" class="formStep hidden">
<b>Are you a people leader?</b><br>
<input type="radio" name="q2" value="0">No<br>
<input type="radio" name="q2" value="1">Yes<br>
<br>
<button type="button" id="btnStepTwo" onclick="prev();">Previous</button>
<input type="button" value="Show Results" onclick="process();">
<input type="reset" value="Start Over" onclick="formReset();">
</div>
</form>
<div id="results">
<div id="biz">
Business Structure/Acumen
<div class="bizMgr">Manager Content</div>
<div class="bizEE">Employee Content</div>
</div>
<div id="career">
Career Development
<div class="careerMgr">Manager Content</div>
<div class="careerEE">Employee Content</div>
</div>
<div id="change">
Change
<div class="changeMgr">Manager Content</div>
<div class="changeEE">Employee Content</div>
</div>
<div id="eq">
Emotional Intelligence
<div class="eqMgr">Manager Content</div>
<div class="eqEE">Employee Content</div>
</div>
<div id="empathy">
Empathy
<div class="empathyMgr">Manager Content</div>
<div class="empathyEE">Employee Content</div>
</div>
<div id="pm">
Performance Management
<div class="pmMgr">Manager Content</div>
<div class="pmEE">Employee Content</div>
</div>
</div>
.getElementsByClassName returns a collection, bizMgr and bizEE are both collections. You have to iterate the collections and set each element to style.display = 'block'. You can't just call xxx.style.display on a javascript collection. You would want to change your code like the following:
if (q2value == "1") {
if (biz.style.display = "block") {
//bizMgr.style.display = "block"; -NO
//bizEE.style.display = "block"; -NO
for(let i = 0; i < bizMgr.length; i++){
bizMgr[i].style.display = "block";
}
for(let j = 0; j < bizEE.length; j++){
bizEE[j].style.display = "block";
}
}
} else {
if (biz.style.display = "block") {
//document.getElementsByClassName("bizEE").style.display = "block"; -NO
for(let j = 0; j < bizEE.length; j++){
bizEE[j].style.display = "block";
}
}
}
I'm relatively new to HTML and I want to create a form so that the user can get a customized output based on their answers. I have a basic form with button inputs, with multiple tabs of buttons. Is there some way for me to collect the data that the user selects by pressing multiple buttons, and assign it to a js variable? This is the code I have so far.
<!DOCTYPE HTML>
<html>
<head>
</head>
<style>
/* Hide all steps by default: */
.tab {
display: none;
}
#myButton {
padding: 0;
border: none;
background: none;
font-family: monospace;
font-size: 25px;
margin-right: 2%;
transition: margin-left 1s;
}
#myButton:hover {
color: rgb(77, 77, 77);
padding-left: 1%;
}
#main {
padding-bottom: 25vh;
padding-top: 25vh;
padding-left: 5%;
padding-right: 5%;
}
/* Header */
#heade {
position: fixed;
top: 0;
left: 0;
width: 100%;
background: #0F1116;
color: #fff;
padding: 3.25em 1.5em 1.5em 1.5em;
z-index: 100;
}
header {
padding-bottom: 30px;
margin-top: -3px;
padding-right: 80%;
}
</style>
<body>
<form id="regForm" style="text-align: center;" method="GET">
<!-- One "tab" for each step in the form: -->
<div class="tab">
<input onmousedown="myFunction()" name="qty" type="button" value="3" onclick="nextPrev(1)" id="myButton">
</div>
<div class="tab">
<ul style="list-style-type:none;">
<li><input name="qty" type="button" value="3" onclick="nextPrev(1)" id="myButton"></li>
<li><input type="button" name=parameter value="Click me" onclick="nextPrev(1)" id="myButton"></li>
<li><input type="button" value="Click me" onclick="nextPrev(1)" id="myButton"></li>
</ul>
</div>
<div class="tab">
<ul style="list-style-type:none;">
<li><input name="qty" type="button" value="3" onclick="nextPrev(1)" id="myButton"></li>
<li><input type="button" value="Click me" onclick="nextPrev(1)" id="myButton"></li>
</ul>
</div>
<div class="tab">
<ul style="list-style-type:none;">
<li><input name="qty" type="button" value="3" onclick="nextPrev(1)" id="myButton" class="ug"></li>
<li><input type="submit" value="Click me" onclick="nextPrev(1)" id="myButton" class="ug"></li>
</ul>
</div>
<div style="overflow:auto;"></div>
<div style="text-align:center;">
<!-- Circles which indicates the steps of the form: -->
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
</div>
</div>
</form>
</body>
<script>
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
function showTab(n) {
// This function will display the specified tab of the form...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
//... and fix the Previous/Next buttons:
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").innerHTML = "Submit";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
//... and run a function that will display the correct step indicator:
fixStepIndicator(n)
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
if (n == 1 && !validateForm()) return false;
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form...
if (currentTab >= x.length) {
// ... the form gets submitted:
document.getElementById("regForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
</script>
</html>
There may be some extra code in there as this is part of a larger webpage.
I have created a simple text editor which shows the associated CSS results in real time. for example if a user clicks Bold Then text becomes bold while user is typing (it shows real time change). Same like this I want a button after click it will wrap the new text with a div tag with specified class or id.
I know wrap method can wrap the div or other tag. But after adding new div tags through wrap() I want store its result which contains newly added div tags. so that I can use those result to generate new html pages.
Here is the html code:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script src="texteditor.js"></script>
</head>
<body>
<div id="content" style="margin-top: 10px; height: 70%; text-align: center;">
<h2><u>Simple Text Editor Created Using jQuery</u></h2>
<div class="ze ie"></div>
<style>
.font-bold.bold {
font-weight: bold;
}
.italic {
font-style: italic;
}
.selected {
background-color: orange;
}
#openpb {
margin: 15px;
}
</style>
<button type="button" class="g-button g-button-submit" id='stext'>Text</button>
<button type="button" class="g-button g-button-submit" id='shtml'>HTML</button>
<div id="controls" style="margin-bottom: 10px;">
<a id="bold" style="color: black; display: inline-block;" class="font-bold">
<button type="button">B</button>
</a>
<a id="italic" style="color: black !important; display: inline-block;" class="italic">
<button type="button">I</button>
</a>
<a id="link" class="link" style="display: inline-block;">
<button type="button">Link</button>
</a>
<select id="fonts" class="g-button">
<option value="Normal">Normal</option>
<option value="Arial">Arial</option>
<option value="Comic Sans MS">Comic Sans MS</option>
<option value="Courier New">Courier New</option>
<option value="Monotype Corsiva">Monotype</option>
<option value="Tahoma New">Tahoma</option>
<option value="Times">Times</option>
<option value="Trebuchet New">Trebuchet</option>
<option value="Ubuntu">Ubuntu</option>
</select>
</div>
<iframe frameborder="0" id="textEditor" style="width: 500px; height: 80px; border: 2px solid #CCC; border-radius: 20px; overflow: auto;"></iframe>
<textarea name="text" id='text' style="border-radius: 20px; overflow: auto; display: none; padding-left: 10px;" rows="6" cols="53"></textarea>
</div>
</body>
</html>
here is Jquery: as you can I have used setinterval method to show result in real time in textarea. same like this I want a button which will wrap new or selected text with div tag with specified id and class and I want store this changes(newly added div tag) in textarea.
$(document).ready(function () {
document.getElementById('textEditor').contentWindow.document.designMode = "on";
document.getElementById('textEditor').contentWindow.document.close();
var edit = document.getElementById("textEditor").contentWindow;
edit.focus();
$("#bold").click(function () {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
} else {
$(this).addClass("selected");
}
boldIt();
});
$("#italic").click(function () {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
} else {
$(this).addClass("selected");
}
ItalicIt();
});
$("#fonts").on('change', function () {
changeFont($("#fonts").val());
});
$("#link").click(function () {
var urlp = prompt("What is the link:", "http://");
url(urlp);
});
$("#stext").click(function () {
$("#text").hide();
$("#textEditor").show();
$("#controls").show()
});
$("#shtml").on('click', function () {
$("#text").css("display", "block");
$("#textEditor").hide();
$("#controls").hide();
});
});
function boldIt() {
var edit = document.getElementById("textEditor").contentWindow;
edit.focus();
edit.document.execCommand("bold", false, "");
edit.focus();
}
function ItalicIt() {
var edit = document.getElementById("textEditor").contentWindow;
edit.focus();
edit.document.execCommand("italic", false, "");
edit.focus();
}
function changeFont(font) {
var edit = document.getElementById("textEditor").contentWindow;
edit.focus();
edit.document.execCommand("FontName", false, font);
edit.focus();
}
function url(url) {
var edit = document.getElementById("textEditor").contentWindow;
edit.focus();
edit.document.execCommand("Createlink", false, url);
edit.focus();
}
setInterval(function () {
var gyt = $("#textEditor").contents().find("body").html().match(/#/g);
if ($("#textEditor").contents().find("body").html().match(/#/g) >= 0) { } else {
$("#text").val($("#textEditor").contents().find("body").html());
}
$("#text").val($("#textEditor").contents().find("body").html());
}, 1000);
I don't want use third party text editor plugins. in short I want texteditor which contain a button, after clicking this button it will wrap new text with div tag with specified class or id. something like Stack Overflow text editor...with facility of adding custom div with specified class or id.
<html>
<head>
<style>
#Problem{margin: 5px; outline: 1px dotted red; padding: 5px}
#Solution{margin: 5px; outline: 1px dotted green; padding: 5px}
#Solution textarea{
height: 200px;
width: 500px;
}
</style>
<script>
//Wraps the text in a new div with optional id and classname.
//Returns the new div.
function wrapMe(text, id, classname){
var tE = null;
if (text && text.trim() != ''){
tE = document.createElement('div');
tE.id = (id || '');
tE.className = (classname || '');
tE.innerHTML = (text || '');
}
return tE
}
//Adds the outer html of passed element to the textarea with a linebreak
function addElementToTextarea(e){
var tA = document.querySelector('textarea');
if (tA && e){
tA.innerHTML = (tA.innerHTML || '') + e.outerHTML + '

'
}
}
</script>
</head>
<body>
<div id = 'Problem'>
Problem: I don't want use third party text editor plugins. in short i want texteditor which contain a button, after clicking this button it will wrap new text with div tag with specified class or id. something like stackover flow text editor...with facility of adding custom div with speicifed class or id.
</div>
<div id = 'Solution'>
<input type = 'text' />
<button onclick = "addElementToTextarea(wrapMe(this.parentNode.querySelector('input').value, 'testid', 'testclass'))">Wrap me</button>
<br /><br />
<textarea readonly = 'readonly'></textarea>
</div>
</body>
</html>
Our teacher asked us to create a jar of coins that will count how many pennies, dimes, and etc we have and then gives a total amount of money.
this is the template that he want us to use
https://online.pcc.edu/content/enforced/70599-22278.201302/labs/frameworks/Lab4Template.html?_&d2lSessionVal=0Zb6SMZBBcQ8ENPN4HdQk4js0
He want us to enter pennies, nickels, dimes, quarters in the same text box separated by comma. My question is, How can I do that? I don't know how to do that in JavaScript. Can anyone lead me in the right direction.
here is the code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> 122 Lab 4 Template </title>
<meta name="author" content="Lee Middleton" />
<meta name="keywords" content="CIS122" />
<meta name="description" content="CIS 122 Lab 4" />
<link rel="stylesheet" type="text/css" href="/content/enforced/70599-22278.201302/labs/frameworks/../../new122_Style.css?_&d2lSessionVal=FeMQRN1p4YNBW7SRb8H38sRQW" />
<style type="text/css">
.container {
border: 1px solid black;
border-radius: 15px;
width: 350px;
margin: 25px auto;
padding: 10px;
}
.result {
width: 175px;
float: left;
}
p { margin: 5px 0 0 5px;}
.clear { clear: both; }
input[type='button'] {
margin: 10px 0 0 5px;
}
</style>
<script language="javascript">
function countCoins()
{
// Add your code here to count the coins and display your answers
}
</script>
<script type="text/javascript" src="/d2l/common/mathjax/2.0/MathJax.js?config=MML_HTMLorMML%2c%2fd2l%2flp%2fmath%2fdisplay%2fconfig.js%3fv%3d9.4.1000.156-10" ></script></head>
<body>
<h1>CIS 122 Lab 4</h1>
<div class="container">
<h2>SORT-O-COIN</h2>
<form name="clubForm" style="margin-bottom: 10px;">
<div style="margin-left: 10px;">Coin Jar <input name="coinJar" size="40" type="text" /></div>
<p>Number of pennies: <span name="pennies"></span></p>
<p>Number of nickels: <span name="pennies"></span></p>
<p>Number of dimes: <span name="pennies"></span></p>
<p>Number of quarters: <span name="pennies"></span></p>
<p>Number of half-dollars: <span name="pennies"></span></p>
<p>Total number of coins: <span name="totalCoins"></span></p>
<p>Total value: <span name="totalValue"></span></p>
<input value="Count the coins" onclick="countCoins()" type="button" /></form></div>
</body>
</html>
Your text, split by comma using String.split
var valuesArray = yourInput.split(',');
It gives an array of values that were split by the ,. They are accessible by indexes.
var first = valuesArray[0];
var second = valuesArray[1]; //and so on...
As for counting, you can figure it out from there.
You can use this as a reference.
Note: this may not be complete, some bits may still need to be done, but it demonstrates all that you should need to know, to deal with such a question, or give you specific things to search/ask questions about so that you may learn.
CSS
.container {
border: 1px solid black;
border-radius: 15px;
width: 350px;
margin: 25px auto;
padding: 10px;
}
.result {
width: 175px;
float: left;
}
p {
margin: 5px 0 0 5px;
}
.clear {
clear: both;
}
input[type='button'] {
margin: 10px 0 0 5px;
}
HTML
<h1>CIS 122 Lab 4</h1>
<div class="container">
<h2>SORT-O-COIN</h2>
<form id="clubForm" style="margin-bottom: 10px;">
<div style="margin-left: 10px;">Coin Jar
<input id="coinJar" size="40" type="text">
</div>
<p>Number of pennies: <span id="pennies"></span>
</p>
<p>Number of nickels: <span id="nickels"></span>
</p>
<p>Number of dimes: <span id="dimes"></span>
</p>
<p>Number of quarters: <span id="quarters"></span>
</p>
<p>Number of half-dollars: <span id="halfDollars"></span>
</p>
<p>Total number of coins: <span id="totalCoins"></span>
</p>
<p>Total value: <span id="totalValue"></span>
</p>
<input value="Count the coins" id="countCoinsButton" type="button">
</form>
</div>
Javascript
(function (global) {
var types = "pennies nickels dimes quarters halfDollars".split(" "),
worths = "0.01 0.05 0.10 0.25 0.5".split(" "),
numTypes = types.length,
totals = {},
coinJar,
clubForm;
function countCoins() {
var values = coinJar.value.trim().split(","),
length = Math.min(numTypes, values.length),
i = 0,
coins,
value;
clubForm.reset();
while (i < length) {
value = values[i].trim();
if (value !== "") {
coins = parseInt(value, 10) || 0;
totals[types[i]] = (totals[types[i]] || 0) + coins;
totals["coins"] = (totals["coins"] || 0) + coins;
totals["value"] = parseFloat(((totals["value"] || 0) + (coins * parseFloat(worths[i]))).toFixed(2));
}
i += 1;
}
length = types.length;
i = 0;
while (i < length) {
document.getElementById(types[i]).textContent = totals[types[i]] || 0;
i += 1;
}
document.getElementById("totalCoins").textContent = totals["coins"] || 0;
document.getElementById("totalValue").textContent = totals["value"] || "0.00";
}
global.addEventListener("load", function onLoad() {
global.removeEventListener("load", onLoad);
clubForm = document.getElementById("clubForm");
coinJar = document.getElementById("coinJar");
document.getElementById("countCoinsButton").addEventListener("click", countCoins, false);
}, false);
}(window))
On jsfiddle
First you need to split the text of textbox.
var value = mystring.split(",");
Then go though each item of the array.
First you add value[x] to the total coin count.
Then set the id of the coin type to the value of value[x] for example
document.getElementById('pennies').innerHTML = value[0];
Then take value[x] times the coin value, for example
totalamount = totalamount + (value[x] * 1);
for pennies and add it to the total amount.
At the end you can set the total value with
document.getElementById('totalValue').innerHTML = totalamount.
Overall, it would be something like this:
function countCoins () {
// Add your code here to count the coins and display your answers
var coinJar = document.getElementsByName("coinJar")[0].value; //first get the value
var coinArray = coinJar.split(","); //split it
var values = [0.01, 0.05, 0.10, 0.25, 0.50]; //coin values
var ids = ['pennies', 'nickels', 'dimes', 'quarters', 'halfdollars']; //ids of coins*
var total = 0; //total dollar amount
var coinnumber = 0; //amount of coins.
for (var i = 0; i < coinArray.length; i++) {
var currentvalue = parseInt(coinArray[i]); //value of current coin
document.getElementsByName(ids[i])[0].innerHTML = currentvalue; //set the html
total += currentvalue * values[i];
coinnumber += currentvalue;
}
document.getElementsByName('totalValue')[0].innerHTML = total;
document.getElementsByName('totalCoins')[0].innerHTML = coinnumber;
}
JSFiddle