How to apply CSS styling to elements created by jquery's append()? - javascript

I am trying to create a dynamic form, and have run into a problem with styling that makes itself quite apparent when you add elements to a form. There is styling added to inputs on load that aren't applied to any created when I add them with jQuery's append() function. The margins are nonexistant on the new input elements, whereas if I add them manually in the beginning on page load the styling is there. Seems to be some browser default styling which I cannot override. How do I fix this? Example code below.
CSS:
#GraphTools
{
border-top: 1px solid #BBBBBB;
height: 24px;
margin: 0 5px 3px;
padding-top: 2px;
}
#GraphSearch
{
float: left;
}
#GraphTools input
{
background-color: rgba(255, 255, 255, 0.4);
border-radius: 3px 3px 3px 3px;
box-shadow: 0 0 2px #444444 inset;
font-size: 14px;
padding: 2px;
}
#GraphTools input[type=button]:active, #GraphTools input[type=submit]:active
{
background-color: rgba(192, 192, 192, 0.4);
}
#GraphSearchFields
{
float: left;
margin-right: 5px;
}
#GraphSearchFields input
{
margin: 0 5px 0 5px;
}
#GraphZoom
{
float: right;
}
HTML:
<div id="GraphTools">
<div id="GraphSearch">
<form id="GraphSearchForm">
<div id="GraphSearchFields">
<input type="text" data-default-value="Sender" id="SenderBox0" class="GraphSearchBox" />
<input type="text" data-default-value="Reciever" id="RecieverBox0" class="GraphSearchBox" />
<input type="text" data-default-value="Sender" id="SenderBox1" class="GraphSearchBox" />
<input type="text" data-default-value="Reciever" id="RecieverBox1" class="GraphSearchBox" />
</div>
<input type="button" id="AddNewHumanSet" value="+" />
<input type="submit" value="Go" />
<input type="button" value="Reset" class="GraphResetButton" />
</form>
</div>
<div id="GraphZoom">
<input type="button" value="-" />
<input type="button" value="+" />
</div>
</div>
Javascript:
$(document).ready(function ()
{
function LoadDefaultSearchBoxValues()
{
$(".GraphSearchBox").each(function (i, e)
{
if ($(this).val() == "")
{
$(this).val($(this).data("default-value"));
}
});
}
LoadDefaultSearchBoxValues();
$(".GraphSearchBox").live("focus", function ()
{
if ($(this).val() == $(this).data("default-value"))
{
$(this).val("");
}
});
$(".GraphSearchBox").live("blur", function ()
{
if ($(this).val() == "")
{
$(this).val($(this).data("default-value"));
}
});
$("#GraphSearchForm").live("submit", function (event)
{
event.preventDefault();
var SenderBoxHasValue = !($("#SenderBox").val() == $("#SenderBox").data("default-value") && $("#SenderBox").val() == "");
var RecieverBoxHasValue = !($("#RecieverBox").val() == $("#RecieverBox").data("default-value") && $("#RecieverBox").val() == "");
if (SenderBoxHasValue && RecieverBoxHasValue)
{
graph.filterEdges(function (edge)
{
return edge.source.data.label.toLowerCase().indexOf($("#SenderBox").val().toLowerCase()) != -1 &&
edge.target.data.label.toLowerCase().indexOf($("#RecieverBox").val().toLowerCase()) != -1;
});
}
else if (SenderBoxHasValue)
{
graph.filterEdges(function (edge)
{
return edge.source.data.label.toLowerCase().indexOf($("#SenderBox").val().toLowerCase()) != -1;
});
}
else if (RecieverBoxHasValue)
{
graph.filterEdges(function (edge)
{
return edge.target.data.label.toLowerCase().indexOf($("#RecieverBox").val().toLowerCase()) != -1;
});
}
});
$(".GraphResetButton").live("click", function ()
{
graph.resetGraph();
});
$("#AddNewHumanSet").live("click", function ()
{
var inputcount = $("#GraphSearchFields").children("input").length / 2;
var mod4 = $("#GraphSearchFields").children("input").length % 4;
if (mod4 == 0)
{
$("#GraphSearchFields").append("<br />");
}
$("#GraphSearchFields").append('<input type="text" data-default-value="Sender" id="SenderBox' + inputcount + '" class="GraphSearchBox" /><input type="text" data-default-value="Reciever" id="RecieverBox' + inputcount + '" class="GraphSearchBox" />');
LoadDefaultSearchBoxValues();
});
});

You need to put a space in between 2 input boxes when you append them.
Take a look at this working demo it is fine now
http://jsfiddle.net/2xfED/1/

Related

How to combine input values together

I am trying to combine Input values. Below is my working code, any help is appreciated.
Here is my code:
getCodeBoxElement(index) {
return document.getElementById("codeBox" + index);
}
onKeyUpEvent(index, event) {
const eventCode = event.which || event.keyCode;
console.log((<HTMLInputElement>this.getCodeBoxElement(index)).value);
if ((<HTMLInputElement>this.getCodeBoxElement(index)).value.length === 1) {
if (index !== 6) {
this.getCodeBoxElement(index + 1).focus();
} else {
this.getCodeBoxElement(index).blur();
// Submit code
// for(var i=0; i<6; i++){
// this.verificationCode = (<HTMLInputElement>this.getCodeBoxElement(i)).toString;
// console.log(this.verificationCode);
// }
console.log("submit code ");
}
}
if (eventCode === 8 && index !== 1) {
this.getCodeBoxElement(index - 1).focus();
}
}
onFocusEvent(index) {
for (var item = 1; item < index; item++) {
const currentElement = this.getCodeBoxElement(item);
if (!(<HTMLInputElement>currentElement).value) {
currentElement.focus();
break;
}
}
}
/* Body Styling only end */
section {
display: flex;
/* align-items: center;
width: 100vw;
height: 100vh; */
text-align: center;
}
section form {
display: flex;
align-items: center;
width: auto;
margin-left: 12px;
/* margin: 0 auto; */
}
section form input {
width: 40px;
height: 40px;
text-align: center;
margin-left: -10px;
border: none;
border-radius: 10px;
}
section form input:last-child {
margin-right: 0;
}
section form input::-webkit-inner-spin-button,
section form input::-webkit-outer-spin-button {
-webkit-appearance: none;
appearance: none;
margin: 0;
}
section form input:focus,
section form input.focus {
border-color: green;
outline: none;
box-shadow: none;
}
<section>
<form style="margin-top: 10px;">
<input id="codeBox1" type="text" maxlength="1" (keyup)="onKeyUpEvent(1, $event)"
(focus)="onFocusEvent(1)" autocomplete="off">
<input id="codeBox2" type="text" maxlength="1" (keyup)="onKeyUpEvent(2, $event)"
(focus)="onFocusEvent(2)" autocomplete="off">
<input id="codeBox3" type="text" maxlength="1" (keyup)="onKeyUpEvent(3, $event)"
(focus)="onFocusEvent(3)" autocomplete="off">
<input id="codeBox4" type="text" maxlength="1" (keyup)="onKeyUpEvent(4, $event)"
(focus)="onFocusEvent(4)" autocomplete="off">
<input id="codeBox5" type="text" maxlength="1" (keyup)="onKeyUpEvent(5, $event)"
(focus)="onFocusEvent(5)" autocomplete="off">
<input id="codeBox6" type="text" maxlength="1" (keyup)="onKeyUpEvent(6, $event)"
(focus)="onFocusEvent(6)" autocomplete="off">
<!-- <input id="codeBox5" type="text" maxlength="1" (keyup)="onKeyUpEvent(5, $event)"
(focus)="onFocusEvent(5)" autocomplete="off">
<input id="codeBox6" type="text" maxlength="1" (keyup)="onKeyUpEvent(6, $event)"
(focus)="onFocusEvent(6)" autocomplete="off"> -->
</form>
</section>
Inputs return the value of the input as a string by default... So concatenating the values will combine them by default... If you want to add them as you would numbers, you would need to parse the value as an integer... Otherwise you can simply combine their values by using the plus symbol + => input.value + input2.value. Even the input type number value will return a string so by concatenating the values together you will be combining their values into one string, this would include numbers with typeof = string.
See my example inputs and their outputs for reference...
EDIT: For your issue, you can create an array to hold the value of each input through the iteration in your function... Once you have reached the threshold conditional, join the values of your array.
// create an array to hold your values
let code = new Array;
function onKeyUpEvent(index, event) {
const eventCode = event.which || event.keyCode;
if (getCodeBoxElement(index).value.length === 1) {
// save the value within your array with each selection
code[index] = getCodeBoxElement(index).value
if (index !== 4) {
getCodeBoxElement(index+ 1).focus();
} else {
getCodeBoxElement(index).blur();
// Submit code
// join the array values into a string using .join('');
let codeString = code.join('')
console.log(codeString)
}
}
if (eventCode === 8 && index !== 1) {
getCodeBoxElement(index - 1).focus();
}
}
function getCodeBoxElement(index) {
return document.getElementById('codeBox' + index);
}
let code = new Array;
function onKeyUpEvent(index, event) {
const eventCode = event.which || event.keyCode;
if (getCodeBoxElement(index).value.length === 1) {
//code[index] = getCodeBoxElement(index).value also works
code.push(getCodeBoxElement(index).value)
if (index !== 4) {
getCodeBoxElement(index + 1).focus();
} else {
getCodeBoxElement(index).blur();
// Submit code
let codeString = code.join('');
let display = document.getElementById('display')
display.style.color = 'darkgreen';
display.textContent = `You have entered: ${codeString}`;
}
}
if (eventCode === 8 && index !== 1) {
getCodeBoxElement(index - 1).focus();
}
}
function onFocusEvent(index) {
for (item = 1; item < index; item++) {
const currentElement = getCodeBoxElement(item);
if (!currentElement.value) {
currentElement.focus();
break;
}
}
}
// Body Styling only Begin ==============
body {
text-align: center;
background-color: lightcyan;
font-family: 'POPPINS', Open-Sans;
background: linear-gradient(to right, #4568dc, #b06ab3);
}
::selection {
color: #8e44ad;
}
// Body Styling only End ================
// Container-fluid Styling only Begin ===
.container-fluid {
.row {
align-items: center;
width: 100vw;
height: 100vh;
}
}
// Container-fluid Styling only End =====
// =====
// Passcode-wrapper Styling only Begin ==
.passcode-wrapper {
display: flex;
justify-content: space-between;
align-items: center;
width: auto;
margin: 0 auto;
input {
width: 50px;
height: 50px;
padding: 0;
margin-right: 5px;
text-align: center;
border: 1px solid gray;
border-radius: 5px;
&:last-child {
margin-right: 0;
}
&::-webkit-inner-spin-button,
&::-webkit-outer-spin-button {
-webkit-appearance: none;
appearance: none;
margin: 0;
}
&:focus,
&.focus {
border-color: green;
outline: none;
box-shadow: none;
}
}
}
// Passcode-wrapper Styling only End ====
<section class="container-fluid">
<div class="row">
<div class="col-md-8 offset-md-2">
<form class="text-center">
<div class="form-group">
<label for="password" class="text-white">Enter 4 Digit Password</label>
<div class="passcode-wrapper">
<input id="codeBox1" type="number" maxlength="1" onkeyup="onKeyUpEvent(1, event)" onfocus="onFocusEvent(1)">
<input id="codeBox2" type="number" maxlength="1" onkeyup="onKeyUpEvent(2, event)" onfocus="onFocusEvent(2)">
<input id="codeBox3" type="number" maxlength="1" onkeyup="onKeyUpEvent(3, event)" onfocus="onFocusEvent(3)">
<input id="codeBox4" type="number" maxlength="1" onkeyup="onKeyUpEvent(4, event)" onfocus="onFocusEvent(4)">
</div>
</div>
</form>
</div>
</div>
</section>
<div id="display"></div>
I just did it like this when I did something like this.
document.onkeyup = function() {
ch = document.getElementsByClassName("ch");
x = ch.length;
out = "";
for (y=0;x>y;y++) {
out += ch[y].value;
}
document.getElementById("final").innerHTML = out;
}
<input type='text' maxlength='1' class='ch' onkeyup='javascript: if (event.keyCode == 8) { this.previousElementSibling.focus() } else { this.nextElementSibling.focus() }' onfocus='this.select()'><input type='text' maxlength='1' class='ch' onkeyup='javascript: if (event.keyCode == 8) { this.previousElementSibling.focus() } else { this.nextElementSibling.focus() }' onfocus='this.select()'><input type='text' maxlength='1' class='ch' onkeyup='javascript: if (event.keyCode == 8) { this.previousElementSibling.focus() } else { this.nextElementSibling.focus() }' onfocus='this.select()'><input type='text' maxlength='1' class='ch' onkeyup='javascript: if (event.keyCode == 8) { this.previousElementSibling.focus() } else { this.nextElementSibling.focus() }' onfocus='this.select()'>
<span id="final" style="color: green;"></span>

JavaScript functions working by themselves but not working together

Today I started building a dummy client-side web app project in order to improve my basic JavaScript skills. Basically, it's a scientific calculator imitation that runs on line. As you'll see in the code, there are buttons in my HTML file each of which calls to one of the JavaScript functions in my JavaScript file. The calculator doesn't work, I mean, at all, and as I tried debugging, every function in my JavaScript file works by them-self as intended, but seemingly they don't work together.
Here's my code:
var currentMode = 'deg';
var screen = document.getElementById("screen");
var lastChar = screen.value.slice(-1);
/**
* Auxiliary functions
*/
function isNumeric(val) {
return !isNaN(parseFloat(val)) && isFinite(val);
}
function sine(val) {
if (currentMode === 'deg') {
return Math.sin(Math.PI * val / 180);
}
return Math.sin(val);
}
function cos(val) {
if (currentMode === 'deg') {
return Math.cos(Math.PI * val / 180);
}
return Math.cos(val);
}
function tan(val) {
if (currentMode === 'deg') {
return Math.tan(Math.PI * val / 180);
}
return Math.tan(val);
}
function ln(val) {
return Math.log(val);
}
/**
* Calculator functions
*/
function addSpecial(val) {
var nums = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
var operations = ['+', '-', '*', '/', '^'];
if (screen.value === '0') {
if (nums.indexOf(val) >= 0)
screen.value = val;
else if (val === '.' || operations.indexOf(val) >= 0)
screen.value += val;
else
screen.value = '0';
} else if (lastChar === '.' || operations.indexOf(lastChar) >= 0) {
if (val !== '.' && val !== '=' && operations.indexOf(val) < 0)
screen.value += val;
} else {
if (val !== '=')
screen.value += val;
else {
if (lastChar === '.' || operations.indexOf(lastChar) >= 0)
screen.value = 'SYNTAX ERROR!';
else if (screen.value.split('(') !== screen.value.split(')'))
screen.value = 'ERROR! Open or close parantheses!';
else {
try {
screen.value = eval(screen.value);
} catch(err) {
screen.value = err.message;
}
}
}
}
}
function setAngleMode(newMode) {
if (newMode === 'rad') {
if (currentMode === 'deg') {
currentMode = 'rad';
screen.value *= Math.PI / 180;
}
} else {
if (currentMode === 'rad') {
currentMode = 'deg';
screen.value *= 180 / Math.PI;
}
}
}
function addSymbol(val) {
switch (val) {
case 'pi':
screen.value = Math.PI;
break;
case 'e':
screen.value = Math.E;
break;
case 'phi':
screen.value = 1.61803398875;
break;
case 'gamma':
screen.value = 0.5772156649;
}
}
function clearScreen() {
screen.value = '';
}
function clearLast() {
screen.value.slice(0, -1);
}
function inverseVal() {
var len = screen.value.length;
var subs;
for (var i = 0; i < len; ++i) {
for (var j = len; j > i; --j) {
subs = screen.value.slice(i, j);
if (isNumeric(subs)) {
screen.value = 1 / parseFloat(subs);
break;
}
}
}
}
function addSquare() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += '^2';
}
}
function addPower() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += '^';
}
}
function addSquareroot() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += '^(1/2)';
}
}
function addRoot() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += '^(1/';
}
}
function addExp() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += 'Math.E^';
}
}
function addSin() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += 'sine(';
}
}
function addCos() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += 'cos(';
}
}
function addTan() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += 'tan(';
}
}
function addLn() {
if (isNumeric(lastChar) || lastChar === ')') {
screen.value += 'ln(';
}
}
h5 {
text-align: right;
color: #333333;
font-family: Arial;
font-size: 12px;
font-weight: bold;
margin: 3px;
}
input[type=text] {
text-align: right;
height: 50px;
width: 176px;
padding: 6px;
border: 10px groove #888888;
background-color: #E5DFA0;
font-family: Luicida, monospace;
}
.scientific {
position: relative;
top:0px;
left: 33px;
}
.scientific input[type=button] {
width: 28px;
height: 28px;
background-color: #444444;
color: #BBBBBB;
font-family: Verdana;
font-size: 8px;
font-weight: bold;
padding: 2px;
margin-top: 2px;
margin-right: 2.5px;
margin-bottom: 0px;
margin-left: 2.5px;
border: none;
}
.scientific input[type=button].cardinal {
width: 28px;
height: 28px;
background-color: red;
color: white;
font-family: Verdana;
font-size: 8px;
font-weight: bold;
padding: 2px;
margin-top: 2px;
margin-right: 2.5px;
margin-bottom: 0px;
margin-left: 2.5px;
border: none;
}
.scientific input[type=image] {
width: 24px;
height: 24px;
background-color: #444444;
padding: 2px;
margin-top: 2px;
margin-right: 2.5px;
margin-bottom: 0px;
margin-left: 2.5px;
border: none;
}
.simple input[type=button] {
width: 32px;
height: 32px;
background-color: #EEEEEE;
color: #222222;
font-family: Verdana;
font-size: 11px;
}
.simple input[type=button].roman {
font-family: "Times New Roman", serif;
font-size: 13px;
}
#calc-contain {
width: 180px;
margin: 0px auto;
}
<html>
<head>
<title>::Scientific Calculator::</title>
<link rel="stylesheet" type="text/css" href="main.css" />
<script type="text/javascript" src="engine.js"></script>
</head><body>
<div id="calc-contain">
<img src="EnData.png" alt="EnData" width="180px" />
<h5>SCIENTIFIC CALCULATOR</h5>
<form id="calculator">
<input type="text" id="screen" value="0" readonly />
<div class="scientific">
<div class="line">
<input type="button" value="RAD" onclick="setAngleMode('rad')" />
<input type="button" value="DEG" onclick="setAngleMode('deg')" />
<input type="button" class="cardinal" value="C" onclick="clearScreen()" />
<input type="button" class="cardinal" value="CE" onclick="clearLast()" />
</div><div class="line">
<input type="button" value="sin" onclick="addSin()" />
<input type="button" value="cos" onclick="addCos()" />
<input type="button" value="tan" onclick="addTan()" />
<input type="button" value="ln" onclick="addLn()" />
</div><div class="line">
<input type="image" src="sqr.png" alt="square" onclick="addSquare()" />
<input type="image" src="nthp.png" alt="nth power" onclick="addPower()" />
<input type="image" src="sqrt.png" alt="square root" onclick="addSquareroot()" />
<input type="image" src="nthr.png" alt="nth root" onclick="addRoot()" />
</div><div class="line">
<input type="button" value="1/x" onclick="inverseVal()" />
<input type="button" value="(" onclick="addSpecial('(')" />
<input type="button" value=")" onclick="addSpecial(')')" />
<input type="button" value="exp" onclick="addExp()" />
</div>
</div>
<div class="simple">
<div class="line">
<input type="button" class="roman" value="π" onclick="addSymbol('pi')" />
<input type="button" value="7" onclick="addSpecial('7')" />
<input type="button" value="8" onclick="addSpecial('8')" />
<input type="button" value="9" onclick="addSpecial('9')" />
<input type="button" value=":" onclick="addSpecial('/')" />
</div><div class="line">
<input type="button" class="roman" value="e" onclick="addSymbol('e')" />
<input type="button" value="4" onclick="addSpecial('4')" />
<input type="button" value="5" onclick="addSpecial('5')" />
<input type="button" value="6" onclick="addSpecial('6')" />
<input type="button" value="x" onclick="addSpecial('*')" />
</div><div class="line">
<input type="button" class="roman" value="φ" onclick="addSymbol('phi')" />
<input type="button" value="1" onclick="addSpecial('1')" />
<input type="button" value="2" onclick="addSpecial('2')" />
<input type="button" value="3" onclick="addSpecial('3')" />
<input type="button" value="-" onclick="addSpecial('-')" />
</div><div class="line">
<input type="button" class="roman" value="γ" onclick="addSymbol('gamma')" />
<input type="button" value="0" onclick="addSpecial('0')" />
<input type="button" value="." onclick="addSpecial('.')" />
<input type="button" value="=" onclick="addSpecial('=')" />
<input type="button" value="+" onclick="addSpecial('+')" />
</div>
</div>
</form>
</div>
</body>
</html>
Any help is appreciated.
I am able to get some functionality, (with some parenthesis errors). If it's not working AT ALL, I suspect you are loading the javascript before the DOM is ready which will cause errors with you getElementById. Try either loading in a window.onload handler or put the script before the closing body tag.

Toggle Checkbox upon clicking on Span

I'm working on an assignment that needs to, upon the click of a span element's text in an input div, output the same text in an output div. That part I've done successfully, but to the left of each span element within the input div is a checkbox that needs to also be checked upon the click of said span element.
I am not allowed to target each individual checkbox with its own unique ID because I will be adding in newer checkboxes and span elements later with the press of a button and prompt. This is an assignment on event delegation.
I will then need to be able to uncheck the checkbox and remove the appended output, but first things first, I cannot figure out how to target the checkboxes. The only thing I can think of is to somehow say that whatever index number of said span element was clicked would be the index number of said checkbox is clicked, but I'm unsure if that is the best method as well as how to go about doing that.
Also, this assignment should not have any JQuery involved. My next project is actually to redo this assignment in JQuery. Any help would be appreciated!
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Canvas Document Object Model Exercise</title>
<link rel="stylesheet" href="canvas_stylesheet.css">
</head>
<body>
<div id="input">
<form>
<input class="checkbox" type="checkbox"><span class="values">Apple</span></br></br>
<input class="checkbox" type="checkbox"><span class="values">Mango</span></br></br>
<input class="checkbox" type="checkbox"><span class="values">Grape</span></br></br>
<input class="checkbox" type="checkbox"><span class="values">Strawberry</span></br></br>
<input class="checkbox" type="checkbox"><span class="values">Cherry</span>
</form>
</div>
<div id="output"></div>
CSS:
#input {
width: 250px;
height: 300px;
float: left;
padding: 20px 0 30px 15px;
border-style: solid;
border-color: black;
border-width: 1px;
}
.values {
display: inline;
}
/*
#input form input {
padding: 20px 20px 20px 20px;
}
*/
#output {
width: 225px;
height: 326px;
float: left;
border-top: 1px solid black;
border-right: 1px solid black;
border-bottom: 1px solid black;
padding: 4px 20px 20px;
}
JS:
window.onload = UncheckAll;
function UncheckAll() {
var w = document.getElementsByTagName('input');
for (var i = 0; i < w.length; i++) {
if (w[i].type == 'checkbox') {
w[i].checked = false;
}
}
}
document.getElementById("input").addEventListener("click", function(e){
if (e.target.nodeName === "SPAN") {
var node = document.createElement("P");
var textnode = document.createTextNode(e.target.innerHTML);
node.appendChild(textnode);
document.getElementById("output").appendChild(node);
node.setAttribute("class", "outputItem")
}
});
Just surround your checkboxes elements with label, like I did here.
Ps: plese never write a br element like this </br>, its <br> with no slash at all
window.onload = UncheckAll;
function UncheckAll() {
var w = document.getElementsByTagName('input');
for (var i = 0; i < w.length; i++) {
if (w[i].type == 'checkbox') {
w[i].checked = false;
}
}
}
document.getElementById("input").addEventListener("click", function(e){
if (e.target.nodeName === "SPAN") {
var node = document.createElement("P");
var textnode = document.createTextNode(e.target.innerHTML);
node.appendChild(textnode);
document.getElementById("output").appendChild(node);
node.setAttribute("class", "outputItem")
}
});
#input {
width: 250px;
height: 300px;
float: left;
padding: 20px 0 30px 15px;
border-style: solid;
border-color: black;
border-width: 1px;
}
.values {
display: inline;
}
/*
#input form input {
padding: 20px 20px 20px 20px;
}
*/
#output {
width: 225px;
height: 326px;
float: left;
border-top: 1px solid black;
border-right: 1px solid black;
border-bottom: 1px solid black;
padding: 4px 20px 20px;
}
<!DOCTYPE html>
<html>
<head>
<title>Canvas Document Object Model Exercise</title>
<link rel="stylesheet" href="canvas_stylesheet.css">
</head>
<body>
<div id="input">
<form>
<label>
<input class="checkbox" type="checkbox"><span class="values">Apple</span>
</label>
<br><br>
<label>
<input class="checkbox" type="checkbox"><span class="values">Mango</span>
</label>
<br><br>
<label>
<input class="checkbox" type="checkbox"><span class="values">Grape</span>
</label>
<br><br>
<label>
<input class="checkbox" type="checkbox"><span class="values">Strawberry</span>
</label>
<br><br>
<label>
<input class="checkbox" type="checkbox"><span class="values">Cherry</span>
</label>
</form>
</div>
<div id="output"></div>
</body>
</html>
I realized the answer was to use .previousSibling and .nextSibling after posting the question, so I went ahead and finished all the code for the input/output part of the assignment. Then, I realized someone else mentioned .previousSibling in response to the first answer attempt. Thanks everyone!
window.onload = UncheckAll;
function UncheckAll() {
var w = document.getElementsByTagName('input');
for (var i = 0; i < w.length; i++) {
if (w[i].type == 'checkbox') {
w[i].checked = false;
}
}
}
document.getElementById("input").addEventListener("click", function(e){
//Click Input Text - Box Checks and Output Text Appears
if (e.target.nodeName === "SPAN") {
if (e.target.previousSibling.checked === false) {
var node = document.createElement("P");
var textnode = document.createTextNode(e.target.innerHTML);
node.appendChild(textnode);
document.getElementById("output").appendChild(node);
node.setAttribute("class", "outputItem")
e.target.previousSibling.checked = true;
return;
}
}
//Click Input Text - Box Unchecks and Output Text Disappears
if (e.target.nodeName === "SPAN") {
if (e.target.previousSibling.checked === true) {
for (i = 0; i < document.getElementsByClassName("outputItem").length; i++) {
if (e.target.innerHTML === document.getElementsByClassName("outputItem")[i].innerHTML) {
document.getElementsByClassName("outputItem")[i].remove();
e.target.previousSibling.checked = false;
return;
}
}
}
}
//Check Box - Output Text Appears
if (e.target.type === "checkbox") {
if (e.target.checked === true) {
var node = document.createElement("P");
var textnode = document.createTextNode(e.target.nextSibling.innerHTML);
node.appendChild(textnode);
document.getElementById("output").appendChild(node);
node.setAttribute("class", "outputItem")
return;
}
}
//Uncheck Box - Output Text Disappears
if (e.target.type === "checkbox") {
if (e.target.checked === false) {
for (i = 0; i < document.getElementsByClassName("outputItem").length; i++) {
if (e.target.nextSibling.innerHTML === document.getElementsByClassName("outputItem")[i].innerHTML) {
document.getElementsByClassName("outputItem")[i].remove();
return;
}
}
}
}
});

Javascript logic not working

The if condition is not working while the else if and else are working:
function userchk() {
var un = $('#user_name').val();
if (un.length < 3 && un.length != 0) {
$("#validateUser").html("<span style='color:red' class='status-not-available'>User Name Shoul Be Greater Then 3.</span>");
}
else if (un.length == 0) {
$('#validationUser').html("<span style='color:red' class='status-not-available'> User Name Cannot Be Empty.</span>");
}
else {
$('#validationUser').html("");
}
}
$('#btnTest').on('click', function() {
userchk();
});
input {
width: 100%;
margin-top: 20px;
float: left;
}
button {
font-size: 20px;
background-color: #555;
color: #fff;
padding: 10px 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnTest">Test userchk()</button>
<input type="text" name="user_name" id="user_name" onBlur="userchk()" class="form-control" placeholder="Username" />
<div id="validationUser"></div>
Your if condition results in an element with id #validateUser being selected and manipulated.
Your else if and else target #validationUser
The Javascript logic conditions are sound but you are not getting your expected results because you are targeting a different element in your if block.

How to add auto calculation for two inputs

I have this calculator that I'd like for the results to auto update after the the user adds input.
I've tried the .keyup thing, but I don't understand it.
I'm kinda new to javascript.
Here's my codepen for the project.
http://codepen.io/Tristangre97/pen/zNvQON?editors=0010
HTML
<div class="card">
<div class="title">Input</div>
<br>
<div id="metalSpan"><input class="whiteinput" id="numMetal" type="number">
<div class="floater">Metal Quantity</div>
<div id="metalAlert">
</div>
</div>
<br>
<div id="forgeSpan"><input class="whiteinput" id="numForge" type=
"number">
<div class="floater">Forge Quantity</div></div>
<br>
<input checked id="rb1" name="fuel" type="radio" value="spark"> <label for=
"rb1">Sparkpowder</label> <input id="rb2" name="fuel" type="radio" value=
"wood"> <label for="rb2">Wood</label><br>
<br>
<button class="actionButton" id="submit" type="button">Calculate</button></div>
<div id="forgeAlert">
</div>
<div id="radioSpan">
<div class="floater">
</div>
<div class="card">
<div class="title2">Results</div>
<br>
<div id="result"><span id="spreadMetal"></span> metal <span class=
"plural"></span> forge<br>
<span id="spreadSpark"></span> <span id="fuelType"></span> <span class=
"plural"></span> forge <span id="allSpark"></span><br>
Completion Time: <span id="timeSpark"></span> minutes<br></div>
</div>
</div>
JS
var metals = 0;
var ingots = 0;
var forges = 0;
var spread = 0;
var sparks = 0;
var tSpark = 0;
var isWood = false;
$(document).ready(function() {
$("#result").hide();
$("#alert").hide();
$("#submit").click(function() {
metals = $("#numMetal").val();
forges = $("#numForge").val();
if (metals == 0 || metals == '') {
$("#metalAlert").html("Please enter a value");
}
else if (forges == 0 || forges == '') {
$("#metalAlert").html('');
$("#forgeAlert").html("Please enter a value");
}
else {
if ($("input[name=fuel]:checked").val() == "wood") {
isWood = true;
}
else {
isWood = false;
}
if (forges > 1) {
$(".plural").html("per");
}
else {
$(".plural").html("in the");
}
$("#forgeAlert").html('');
if (metals % 2 == 0) {}
else {
metals = metals - 1;
$("#alert").show();
}
ingots = metals / 2;
spread = Math.floor(metals / forges);
sparks = Math.ceil(((spread / 2) * 20) / 60);
if (isWood) {
sparks = sparks * 2;
}
tSpark = sparks * forges;
if (forges > 1) {
$("#allSpark").html(String("(" + tSpark + " total)"));
}
else {
$("#allSpark").html(String(''));
}
$("#timeSpark").html(String((isWood) ? (sparks / 2) : sparks));
$("#spreadMetal").html(String(spread));
$("#spreadSpark").html(String(sparks));
$("#fuelType").html((isWood) ? "wood" : "sparkpowder");
$("#result").show();
}
});
});
To run the function whenever something is inputted in the field, try the
$("input").on('input', function() { .. });
var metals = 0;
var ingots = 0;
var forges = 0;
var spread = 0;
var sparks = 0;
var tSpark = 0;
var isWood = false;
$(document).ready(function() {
$("#result").hide();
$("#alert").hide();
$("input").on('input', function() {
metals = $("#numMetal").val();
forges = $("#numForge").val();
if (metals == 0 || metals == "") {
$("#metalAlert").html("Please enter a value");
} else if (forges == 0 || forges == "") {
$("#metalAlert").html("");
$("#forgeAlert").html("Please enter a value");
} else {
if ($("input[name=fuel]:checked").val() == "wood") {
isWood = true;
} else {
isWood = false;
}
if (forges > 1) {
$(".plural").html("per");
} else {
$(".plural").html("in the");
}
$("#forgeAlert").html("");
if (metals % 2 == 0) {
} else {
metals = metals - 1;
$("#alert").show();
}
ingots = metals / 2;
spread = Math.floor(metals / forges);
sparks = Math.ceil(spread / 2 * 20 / 60);
if (isWood) {
sparks = sparks * 2;
}
tSpark = sparks * forges;
if (forges > 1) {
$("#allSpark").html(String("(" + tSpark + " total)"));
} else {
$("#allSpark").html(String(""));
}
$("#timeSpark").html(String(isWood ? sparks / 2 : sparks));
$("#spreadMetal").html(String(spread));
$("#spreadSpark").html(String(sparks));
$("#fuelType").html(isWood ? "wood" : "sparkpowder");
$("#result").show();
}
});
});
body {
background-color:#316b6f;
font-family:Helvetica,sans-serif;
font-size:16px;
}
.whiteinput {
outline: none;
border-width: 0px;
margin: 0;
padding: .5em .6em;
border-radius: 2px;
font-size: 1em;
color: #316b6f;
}
.actionButton {
background-color: #316B6F;
color: #fff;
padding: .5em .6em;
border-radius: 3px;
border-width: 0px;
font-size: 1em;
cursor: pointer;
text-decoration: none;
-webkit-transition: all 250ms;
transition: all 250ms;
}
.actionButton:hover {
color: #fff;
}
.actionButton:active {
background: #BBFF77;
color: #316B6F;
-webkit-transition: all 550ms;
transition: all 550ms;
}
.card {
position: relative;
background: #4E8083;
color:#FFFFFF;
border-radius:3px;
padding:1.5em;
margin-bottom: 3px;
}
.title {
background: #76B167;
padding: 3px;
border-radius: 3px 0px 0px 0px;
position: absolute;
left: 0;
top: 0;
margin-bottom: 5px;
}
.title2 {
background: #2F3A54;
padding: 3px;
border-radius: 3px 0px 0px 0px;
position: absolute;
left: 0;
top: 0;
margin-bottom: 5px;
}
.floater {
padding: 3px;
}
.radiobtn {
background: red;
border-radius: 2px;
}
input[type=radio] + label:before {
content: "";
display: inline-block;
width: 20px;
height: 20px;
vertical-align:middle;
margin-right: 8px;
background-color: #aaa;
margin-bottom: 6px;
border-radius: 2px;
-webkit-transition: all 450ms;
transition: all 450ms;
}
input[type=radio], input[type=checkbox] {
display:none;
}
input[type=radio]:checked + label:before {
content: "\2022"; /* Bullet */
color:white;
background-color: #fff;
font-size:1.8em;
text-align:center;
line-height:14px;
margin-right: 8px;
}
input[type=checkbox]:checked + label:before {
content:"\2714";
color:white;
background-color: #fff;
text-align:center;
line-height:15px;
}
*:focus {
outline: none;
}
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<div class="card">
<div class="title">Input</div><br>
<div id="metalSpan">
<input class="whiteinput" id="numMetal" type="number">
<div class="floater">
Metal Quantity
</div>
<div id="metalAlert">
</div>
</div>
<br>
<div id="forgeSpan">
<input class="whiteinput" id="numForge" type="number">
<div class="floater">
Forge Quantity
</div>
</div>
<br>
<input type="radio" id="rb1" name="fuel" value="spark" checked>
<label for="rb1">Sparkpowder</label>
<input type="radio" id="rb2" name="fuel" value="wood">
<label for="rb2">Wood</label><br><br>
<button class="actionButton" id="submit"
type="button">Calculate</button>
</div>
<div id="forgeAlert">
</div>
<div id="radioSpan">
<div class="floater">
</div>
<div class="card">
<div class="title2">Results</div><br>
<div id="result">
<span id="spreadMetal"></span> metal <span class="plural"></span> forge<br>
<span id="spreadSpark"></span> <span id="fuelType"></span> <span class="plural"></span> forge <span id=
"allSpark"></span><br>
Completion Time: <span id="timeSpark"></span> minutes<br>
</div>
</div>
</div>
Codepen
It is triggering your errors because that is part of your function.
More info regarding the input method.
Look, you have two options:
Put all your algorithm of submit click into a function and call him into two binds: the submit click and input change (on('change')) or just remove your calculate button and rely the calculation into onchange of the inputs: each change of checks or inputs will trigger the calculation of metals. The second approach it's more interesting for me and removes the necessity to the user clicks to calculate (he already clicked into inputs and checks). Obviously you can add a filter to only allow to calculation function run after a certain minimum number of data filled, it's a good idea to avoid poor results resulted by lack of data.
In order to auto update calculation, we have to listen to users input on input elements. The easiest approach with minimum changes to existing code is to add input events and emit click on the button:
$("#numMetal, #numForge").on('input', function(){
$("#submit").click()
})
Better approach is to move calculation logic to separate function and call it on desirable events:
$("#numMetal, #numForge").on('input', function(){
calculate()
})
$("#submit").click(function(){
calculate()
})
This will keep the code structured and easier to follow.
Try this:
$( "#numMetal, #numForge" ).keyup(function(event) {
console.log('a key has been pressed');
// add code to handle inputs here
});
What happens here is that an event listener - the key up event - is bound to the two inputs you have on your page. When that happens the code inside will be run.
As suggested in other comments it would be a good idea to call a separate method with all the input processing code you have in the submit call, this way you will avoid code duplication.
You will also want to bind events to the checkboxs. This can be achieved with this:
$( "input[name=fuel]" ).on('change',function() {
console.log('checkbox change');
// call processing method here
});

Categories

Resources