I have two functions that are essentially identical. The negIndex function works as advertised, no problems, but the posIndex function give me the error "cannot set enterTable.innerHTML to 'null'".
I'm fairly new to Javascript so it could be something obvious, but if it is i'm lost. I've tried a few different things without positive results. Any help would be appreciated.
The HTML
<ul id="exitTable" style="list-style-type: none; display: flex; flex-direction: column; vertical-align: center"></ul>
<br>
<ul id="enterTable" style="list-style-type: none; display: flex; flex-direction: column; vertical-align: center"></ul>
The Javascript
// Put DOM elements into variables
const myForm = document.querySelector('#my-form');
const price = document.querySelector('#stockPrice');
const shares = document.querySelector('#sharesAmount');
const commission = document.querySelector('#commissionAmount');
const fee = document.querySelector('#feeAmount');
const max = document.querySelector('#maxGain');
const msg = document.querySelector('.msg');
const exitTable = document.querySelector('#exitTable');
const enterTable = document.querySelector('#enterTable');
// Listen for form submit
myForm.addEventListener('submit', onSubmit);
function onSubmit(e) {
e.preventDefault();
if (price.value === '' || shares.value === '') {
// alert
msg.classList.add('error');
msg.innerHTML = 'Please enter required fields';
// Remove error after 3 seconds
setTimeout(() => msg.remove(), 3000);
} else {
let subTotal = price.value * shares.value;
subTotal = subTotal.toFixed(2)
let total = subTotal + parseFloat(commission.value);
function popList(name) {
let li = document.createElement('li');
li.textContent = name;
li.style.cssText = 'text-align: center'
return li;
}
//finds the 5%-50% loss amounts based on subTotal
function negIndex(num) {
let negPer = -0.05;
let negArray = [];
let i = 0;
exitTable.innerHTML = "";
while (negPer >= -0.50) {
negArray[i] = parseFloat(num * negPer).toFixed(2);
let s = parseFloat(negPer * 100).toFixed(1) + "% " + negArray[i];
let x = popList(s); //creating list elements
exitTable.appendChild(x);
i++;
negPer += -0.05;
}
}
function posIndex(num) {
let posPer = 0.05;
let posArray = [];
let i = 0;
enterTable.innerHTML = "";
while (posPer <= 1.00) {
posArray[i] = parseFloat(num * posPer).toFixed(2);
let s = parseFloat(posPer * 100).toFixed(1) + "% ->" + posArray[i];
let x = popList(s);
enterTable.appendChild(x);
i++;
posPer += 0.05;
}
}
posIndex(subTotal);
negIndex(subTotal);
}
//Listen for form clear
myForm.addEventListener('reset', onReset);
function onReset() {
price.innerHTML = "";
shares.innerHTML = "";
commission.innerHTML = "";
fee.innerHTML = "";
}
I'm just gessing what your html could look like
// Put DOM elements into variables
const myForm = document.querySelector('#my-form');
const price = document.querySelector('#stockPrice');
const shares = document.querySelector('#sharesAmount');
const commission = document.querySelector('#commissionAmount');
const fee = document.querySelector('#feeAmount');
const max = document.querySelector('#maxGain');
const msg = document.querySelector('.msg');
const exitTable = document.querySelector('#exitTable');
const enterTable = document.querySelector('#enterTable');
let subTotal = 0;
// Listen for form submit
myForm.addEventListener('submit', onSubmit);
function onSubmit(e) {
e.preventDefault();
if (price.value === '' || shares.value === '') {
// alert
msg.classList.add('error');
msg.innerHTML = 'Please enter required fields';
// Remove error after 3 seconds
setTimeout(() => {
msg.classList.remove('error');
msg.innerHTML = '';
}, 3000);
} else {
subTotal = price.value * shares.value;
subTotal = subTotal.toFixed(2)
}
posIndex(subTotal);
negIndex(subTotal);
}
function popList(name) {
let li = document.createElement('li');
li.textContent = name;
li.style.cssText = 'text-align: center'
return li;
}
//finds the 5%-50% loss amounts based on subTotal
function negIndex(num) {
let negPer = -0.05;
let negArray = [];
let i = 0;
exitTable.innerHTML = "";
while (negPer >= -0.50) {
negArray[i] = parseFloat(num * negPer).toFixed(2);
let s = parseFloat(negPer * 100).toFixed(1) + "% " + negArray[i];
let x = popList(s); //creating list elements
exitTable.appendChild(x);
i++;
negPer += -0.05;
}
}
function posIndex(num) {
let posPer = 0.05;
let posArray = [];
let i = 0;
enterTable.innerHTML = "";
while (posPer <= 1.00) {
posArray[i] = parseFloat(num * posPer).toFixed(2);
let s = parseFloat(posPer * 100).toFixed(1) + "% ->" + posArray[i];
let x = popList(s);
enterTable.appendChild(x);
i++;
posPer += 0.05;
}
}
//Listen for form clear
myForm.addEventListener('reset', onReset);
function onReset() {
price.innerHTML = "";
shares.innerHTML = "";
commission.innerHTML = "";
fee.innerHTML = "";
}
<form id="my-form">
<div>
<label for="stockPrice">Stock price</label>
<input type="number" id="stockPrice" />
</div>
<div>
<label for="sharesAmount">Shares amount</label>
<input type="number" id="sharesAmount" />
</div>
<div>
<label for="commissionAmount">Commission amount</label>
<input type="number" id="commissionAmount" />
</div>
<div>
<label for="feeAmount">Fee amount</label>
<input type="number" id="feeAmount" />
</div>
<div>
<label for="maxGain">Max gain</label>
<input type="number" id="maxGain" />
</div>
<div class="msg"></div>
<button type="submit">Submit</button>
</form>
<ul id="exitTable" style="list-style-type: none; display: flex; flex-direction: column; vertical-align: middle"></ul>
<br>
<ul id="enterTable" style="list-style-type: none; display: flex; flex-direction: column; vertical-align: middle"></ul>
Related
The percentage will be updated depending on the two counters. I have to have as total data the sum of counter and counter1
var botonElement = document.getElementById("botonClick");
var pElement = document.getElementById("areaContador");
var pPorce = document.getElementById("porcen");
var contador = 0;
var botonElement1 = document.getElementById("botonClick1");
var pElement1 = document.getElementById("areaContador1");
var pPorce1 = document.getElementById("porcen1");
var contador1 = 0;
botonElement.onclick = function () {
contador++;
pElement.textContent = contador;
/* pPorce.textContent = result + "%"; */
}
botonElement1.onclick = function () {
contador1++;
pElement1.textContent = contador1;
/* pPorce1.textContent = result + "%"; */
}
Looks like you are looking for something like below.
function increaseCounter(index) {
const countElement1 = document.getElementById("counter1");
const countElement2 = document.getElementById("counter2");
const currentCountElement = document.getElementById("counter" + index);
currentCountElement.value = parseInt(currentCountElement.value) + 1;
const value1 = parseInt(countElement1.value);
const value2 = parseInt(countElement2.value);
const total = value1 + value2;
const perc1 = ((value1/total) * 100).toFixed(2);
const perc2 = ((value2/total) * 100).toFixed(2);
document.getElementById("percentage1").innerHTML = perc1;
document.getElementById("percentage2").innerHTML = perc2;
}
.container {
display: flex;
background-color: #993355;
color: #ffffff;
}
<div class="container">
<div>
<h3>Area 1</h3>
<div>Count: <input type="text" value="0" id="counter1" /></div>
<div>Percentage: <label id="percentage1"></label></div>
<div><button onclick="increaseCounter(1)">Click Here!</button></div>
</div>
<div>
<h3>Area 2</h3>
<div>Count: <input type="text" value="0" id="counter2" /></div>
<div>Percentage: <label id="percentage2"></label></div>
<div><button onclick="increaseCounter(2)">Click Here!</button></div>
</div>
</div>
I am creating a status posting and commenting system.
It is implemented in Vanilla JavaScript. Anyone can add a post and can comment on the post.
Everything is working fine but the comment section is working on first post only.
deletion of comment and post is working fine.
I don't know what's the problem is, if anyone could help me..
Here is the HTML code
<div class="container-post" id="container-post">
<div class="create-post">
<form>
<div class="form-group">
<div class="username">
<p class="name" style="top:15px;">User Name</p>
</div>
<p class="qoutes">
<textarea style=" font-size: 15pt;" class="form-control" id="enter-post" rows="7" id="mypara" placeholder="Share Your Thoughts..."></textarea>
</p>
<div class="postbar">
<button type="button" class="btn btn-primary post-me" id="post-button"> <span id="postText">Post</span></button>
</div>
</div>
</form>
</div>
<hr class="line-bar">
<div class="allpost">
<div class="mainpost" id="post-div"></div>
</div>
Here is the JavaSCript code
showTask();
showComment();
let addPost = document.getElementById("enter-post");
let addPostBtton = document.getElementById("post-button");
addPostBtton.addEventListener("click", function () {
var addPostVal = addPost.value;
if (addPostVal.trim() != 0) {
let webtask = localStorage.getItem("localtask");
if (webtask == null) {
var taskObj = [];
}
else {
taskObj = JSON.parse(webtask);
}
taskObj.push(addPostVal);
localStorage.setItem("localtask", JSON.stringify(taskObj));
}
showTask();
});
function showTask() {
let webtask = localStorage.getItem("localtask");
if (webtask == null) {
var taskObj = [];
}
else {
taskObj = JSON.parse(webtask);
}
let htmlVal = '';
let createPost = document.getElementById("post-div");
taskObj.forEach((item, index) => {
htmlVal += `
<div class="post-class"><div class="username u-name">
<p class="name i-name">${"User Name " + index}</p>
<i class="fas fa-trash-alt" onclick="removePost(${index});"></i></button>
</div>
<hr>
<p class="quotes">
${item}
</p>
<div class="comment-section" id="comment-section">
<p class="comment-qoute">
<textarea style=" font-size: 15pt;" class="form-control commentBox" rows="3" id="mypara" placeholder="Leave a comment"></textarea>
</p>
<button class="btn btn-primary comment-btn" id="commentBtn">comment</button>
<ul class="comments" id="comments-portion">
<p></p>
</ul>
</div>
</div>
<br><br>`
});
createPost.innerHTML = htmlVal;
}
function removePost(index) {
let webtask = localStorage.getItem("localtask");
let taskObj = JSON.parse(webtask);
taskObj.splice(index, 1);
localStorage.setItem("localtask", JSON.stringify(taskObj));
showTask();
}
var commentPost = document.getElementById('mypara');
var commentBtn = document.getElementById('commentBtn');
commentBtn.addEventListener('click', function () {
var commentValue = commentPost.value;
if (commentValue.trim() != 0) {
let commentTask = localStorage.getItem("comments");
if (commentTask == null) {
var commentObj = [];
}
else {
commentObj = JSON.parse(commentTask);
}
commentObj.push(commentValue);
localStorage.setItem("comments", JSON.stringify(commentObj));
}
showComment();
});
function showComment() {
let commentsTask = localStorage.getItem("comments");
if (commentsTask == null) {
var commentObj = [];
}
else {
commentObj = JSON.parse(commentsTask);
}
let commentHTMLValue = '';
var createComment = document.getElementById("comments-portion");
commentObj.forEach((item, index) => {
commentHTMLValue += `<div class="comment-box-btn">
<p>${index + ". "}<span>${item}</span></p>
<i class="far fa-times-circle fa-2x" onclick="removeComment(${index});"></i>
</div>
`;
});
createComment.innerHTML = commentHTMLValue;
}
var deleteBtn = document.querySelector('.comment-del');
deleteBtn.addEventListener('click', () => {
});
// remove comment
function removeComment(index) {
let commentTask = localStorage.getItem("comments");
let commentObj = JSON.parse(commentTask);
commentObj.splice(index, 1);
localStorage.setItem("comments", JSON.stringify(commentObj));
showComment();
}
When you use code like:
createComment.innerHTML = commentHTMLValue;
you are completely replacing the contents of the element. Try using:
createComment.innerHTML += commentHTMLValue;
which appends new content to the end of the existing contents.
I can't do a snippet here as the use of localStorage is not allowed. Copy this block into a blank file and save it as an html file and then open that in a browser.
This is how I think you are describing your requirements and is also based on the data format in my comments. It's not pretty and needs plenty of sprucing up, but it runs.
<!DOCTYPE html>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<html>
<head>
<title>Task listing</title>
<script type="text/javascript">
let taskList = [];
function checkTasks() {
let tasksList = getTasksList();
if (tasksList.length == 0) {
let newTask = prompt("Please enter a task description");
if (newTask) {
let thisIndex = getNewIndex();
let a = {"id": thisIndex, "task": newTask, "comments": []}
taskList.push(a);
saveTasksList(taskList);
}
}
displayTasks();
}
function displayTasks() {
let container = document.getElementById("tasks");
container.innerHTML = "";
let taskList = getTasksList();
taskList.forEach(function(task){
let d = document.createElement("div");
d.id = "task_" + task.id;
d.className = "commentdiv";
d.innerHTML = "<h3>" + task.task + "</h3>";
let l = document.createElement("ul");
l.id = "comments_" + task.id;
let comments = task.comments;
if (comments.length > 0) {
let commentindex = 0;
comments.forEach(function(comment) {
let c = document.createElement("li");
c.innerHTML = comment;
let cb = document.createElement("button");
cb.id = "deletecomment_" + task.id + "_" + commentindex;
cb.innerHTML = "Delete comment";
cb.onclick = function() {deleteComment(task.id, commentindex);};
c.appendChild(cb);
l.appendChild(c);
})
}
let b = document.createElement("button");
b.id = "addcomment_" + task.id;
b.onclick = function() {addComment(task.id);};
b.innerHTML = "Add comment";
d.appendChild(b);
d.appendChild(l);
container.appendChild(d);
})
}
function addComment(taskid) {
let newcomment = prompt("Enter comment");
if (newcomment) {
let tasklist = getTasksList();
let filtered = tasklist.filter(task => task.id == taskid);
if (filtered[0]) {
let thisTask = filtered[0];
thisTask.comments.push(newcomment);
let thisIndex = taskList.findIndex((task) => task.id == taskid);
taskList[thisIndex] = thisTask;
}
saveTasksList(taskList);
displayTasks();
}
}
function addNewTask() {
let newTask = prompt("Enter task description");
let taskList = getTasksList();
let lastindex = localStorage.getItem("tasksindex");
let index = getNewIndex();
let a = {"id": index, "task": newTask, "comments": []}
taskList.push(a);
saveTasksList(taskList);
displayTasks();
}
function deleteComment(taskid, commentindex) {
let tasklist = getTasksList();
let filtered = tasklist.filter(task => task.id == taskid);
// as long as there is at least one task with the taskid value, find and delete the comment
// based on the index position of the comment in the comments array
if (filtered[0]) {
let thisTask = filtered[0];
thisTask.comments.splice(commentindex, 1);
let thisIndex = taskList.findIndex((task) => task.id == taskid);
taskList[thisIndex] = thisTask;
}
saveTasksList(taskList);
displayTasks();
}
function getTasksList() {
let tasks = localStorage.getItem("tasks");
taskList = JSON.parse(tasks);
if (!taskList) {
taskList = [];
}
return taskList;
}
function saveTasksList(taskList) {
localStorage.setItem("tasks", JSON.stringify(taskList));
}
function getNewIndex() {
let lastindex = localStorage.getItem("tasksindex");
let idx = 0;
if (!lastindex) {
idx = 1;
} else {
idx = Number(lastindex) + 1;
}
localStorage.setItem("tasksindex", idx);
return idx;
}
function removeAll() {
localStorage.removeItem("tasks");
localStorage.removeItem("tasksindex");
displayTasks();
}
window.onload = checkTasks;
</script>
<style type="text/css">
.commentdiv {
border:1px solid black;
width:1000px;
padding:5px;
border-radius:5px;
}
button {
margin-left:10px;
}
h3 {
width:100%;
border-bottom: 1px dotted black;
}
ul {
list-style-type:decimal;
}
</style>
</head>
<body>
<h2>My task list <button id="addNewTaskButton" onclick="addNewTask();">Add new task</button></h2>
<hr>
<div id="tasks">
</div>
<button id="removeAll" onclick="removeAll();">Remove all tasks</button>
</body>
</html>
I made products quantity counter for e-commerce that should increase and decrease the quantity by 1 and it works only if the elements exist in dom without appending from javascript
but when I click on the get button to append from javascript the last appended element only increases or decreases by one.
here is the code:
class Cart {
static global() {
Cart.getBtn = document.getElementById('get');
Cart.main = document.getElementsByTagName('main')[0];
Cart.min = 1;
}
constructor(num) {
this.num = num;
}
static insertEl() {
const div = document.createElement('div');
div.innerHTML = `
<br>
<div>
<button type="button" class="minus">-</button>
<input type="number" min="1" max="20" value="1">
<button type="button" class="plus">+</button>
</div>
`;
Cart.main.appendChild(div);
}
static plusFunc() {
// plus btn
let plus = document.querySelectorAll('.plus');
plus.forEach(function(btn) {
btn.addEventListener('click', function(e) {
let input = e.target.previousElementSibling;
let max = Number(input.getAttribute('max'));
let num1 = new Cart(Number(input.value));
if (num1.num >= Cart.min) {
num1.num += 1;
}
if (num1.num >= max) {
num1.num = max;
}
input.value = num1.num;
});
});
}
static minusFunc() {
// minus btn
let minus = document.querySelectorAll('.minus');
minus.forEach(function(btn) {
btn.addEventListener('click', function(e) {
let input = e.target.nextElementSibling;
let max = Number(input.getAttribute('max'));
let num1 = new Cart(Number(input.value));
if (num1.num <= max) {
num1.num -= 1;
}
if (num1.num <= Cart.min) {
num1.num = Cart.min;
}
input.value = num1.num;
});
});
}
}
Cart.global();
// events
Cart.getBtn.addEventListener('click', function() {
Cart.insertEl();
Cart.plusFunc();
Cart.minusFunc();
});
<button type="button" id="get">get</button>
<main></main>
You're adding a new plus and a new minus listener to each element whenever a new element is appended. Have plusFunc and minusFunc only add to the newly created element instead:
class Cart {
static global() {
Cart.getBtn = document.getElementById('get');
Cart.main = document.getElementsByTagName('main')[0];
Cart.min = 1;
}
constructor(num) {
this.num = num;
}
static insertEl() {
const div = document.createElement('div');
div.innerHTML = `
<br>
<div>
<button type="button" class="minus">-</button>
<input type="number" min="1" max="20" value="1">
<button type="button" class="plus">+</button>
</div>
`;
Cart.main.appendChild(div);
return div;
}
static plusFunc(btn) {
btn.addEventListener('click', function(e) {
let input = e.target.previousElementSibling;
let max = Number(input.getAttribute('max'));
let num1 = new Cart(Number(input.value));
if (num1.num >= Cart.min) {
num1.num += 1;
}
if (num1.num >= max) {
num1.num = max;
}
input.value = num1.num;
});
}
static minusFunc(btn) {
btn.addEventListener('click', function(e) {
let input = e.target.nextElementSibling;
let max = Number(input.getAttribute('max'));
let num1 = new Cart(Number(input.value));
if (num1.num <= max) {
num1.num -= 1;
}
if (num1.num <= Cart.min) {
num1.num = Cart.min;
}
input.value = num1.num;
});
}
}
Cart.global();
// events
Cart.getBtn.addEventListener('click', function() {
const div = Cart.insertEl();
const [minus, plus] = div.querySelectorAll('button');
Cart.plusFunc(plus);
Cart.minusFunc(minus);
});
<button type="button" id="get">get</button>
<main></main>
But this quite a weird setup - why have a class that basically has nothing but static methods? Consider a plain object instead:
const Cart = {
getBtn: document.getElementById('get'),
main: document.querySelector('main'),
min: 1,
max: 20,
insertEl() {
const div = document.createElement('div');
div.innerHTML = `
<button type="button" class="minus">-</button>
<input type="number" min="1" max="20" value="1">
<button type="button" class="plus">+</button>
`;
this.main.insertAdjacentHTML('beforeend', '<br>');
this.main.appendChild(div);
return div;
}
}
Cart.getBtn.addEventListener('click', function() {
const div = Cart.insertEl();
const [minus, input, plus] = div.children;
minus.addEventListener('click', () => input.value = Math.max(Cart.min, input.value - 1));
plus.addEventListener('click', () => input.value = Math.min(Cart.max, Number(input.value) + 1));
});
<button type="button" id="get">get</button>
<main></main>
I'm working with JavaScript and am having issues with a couple of for loops at a specific value.
When the slider value is incremented, the amount of pics increase by one and vice versa for when its lowered. However, for a reason I'm unsure of, it will remove one of the pics when the slider is incremented from 9 to 10, and will add one when it's lowered from 10 to 9. This problem doesn't occur anywhere else in the slider, so I'm not sure whats going on.
Here's the code. The picture used isn't attached but the missing image favicon does the same job.
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
var prevnumb = 0;
var num = 2
var numberofdivs = 0;
output.innerHTML = slider.value;
slider.oninput = function() {
prevnum = num;
output.innerHTML = this.value;
num = this.value;
var newnum = num;
var newprevnum = prevnum;
console.log(prevnum, num);
if (prevnum > num) {
for (newnum; newprevnum > newnum; newnum++) {
var element = document.getElementById("id");
element.parentNode.removeChild(element);
}
} else if (num > prevnum) {
for (newprevnum; newnum > newprevnum; newprevnum++) {
var picpol = document.createElement("img");
picpol.src = "polee.png";
picpol.setAttribute("id", "id");
picpol.setAttribute("class", "polio");
document.getElementById("basecontainer").appendChild(picpol);
console.log(picpol);
}
} else {
console.log("no change");
}
}
body {
text-align: center;
}
#basecustom {
text-align: center;
}
.polio {
margin: none;
padding: none;
}
Base Customization
<br>
<br>
<div id="basecustom">
Select your amount of pics
<input type="range" min="2" max="25" value="2" id="myRange">
<p>Value: <span id="demo"></span></p>
<div id="valcont"></div>
<div id="basecontainer">
<img class="polioo" src="polee.png" id="id"><img class="polioo" src="polee.png" id="id">
</div>
</div>
You were missing casting value to int. By default it is string.
num = parseInt(this.value);
Above casting will fix your problem.
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
var prevnumb = 0;
var num = 2
var numberofdivs = 0;
output.innerHTML = slider.value;
slider.oninput = function() {
prevnum = num;
output.innerHTML = this.value;
num = parseInt(this.value);
var newnum = num;
var newprevnum = prevnum;
console.log(prevnum, num);
if (prevnum > num) {
for (newnum; newprevnum > newnum; newnum++) {
var element = document.getElementById("id");
element.parentNode.removeChild(element);
}
} else if (num > prevnum) {
for (newprevnum; newnum > newprevnum; newprevnum++) {
var picpol = document.createElement("img");
picpol.src = "https://www.vyapin.com/blog/wp-content/uploads/2012/07/bullet_04-1.gif";
picpol.setAttribute("id", "id");
picpol.setAttribute("class", "polio");
document.getElementById("basecontainer").appendChild(picpol);
console.log(picpol);
}
} else {
console.log("no change");
}
}
body {
text-align: center;
}
#basecustom {
text-align: center;
}
.polio {
margin: none;
padding: none;
}
Base Customization
<br>
<br>
<div id="basecustom">
Select your amount of pics
<input type="range" min="2" max="25" value="2" id="myRange">
<p>Value: <span id="demo"></span></p>
<div id="valcont"></div>
<div id="basecontainer">
<img class="polioo" src="https://www.vyapin.com/blog/wp-content/uploads/2012/07/bullet_04-1.gif" id="id"/><img class="polioo" src="https://www.vyapin.com/blog/wp-content/uploads/2012/07/bullet_04-1.gif" id="id"/>
</div>
</div>
change num = this.value; to num = parseInt(this.value,10); in your original code, num will be a string. so when it increments to 10, you will get a string '10'. And prevnum is '9'. And if (prevnum > num) { will be true.
var result = 0;
function sum() {
var txtFirstNumberValue = document.getElementById('w_amount').value;
var txtSecondNumberValue = document.getElementById('c_size').value;
var result = 0;
if (txtFirstNumberValue > 0) {
result = ((0.15 * parseInt(txtFirstNumberValue)) + parseInt(txtFirstNumberValue)) / parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('e_fee').value = parseFloat(result).toFixed(0);
}
} else {
document.getElementById('e_fee').value = result;
}
}
// document.getElementById('e_fee').value = result;
function isChecked(checkbox, winnerCount) {
var winner_amount = document.getElementById('w_amount').value;
var chkMultiEntry = document.getElementById("test5");
if (winner_amount.length == 0) {
document.getElementById('err_w_amount').innerHTML = "Please enter winning amount";
chkMultiEntry.checked = false;
} else {
document.getElementById('winnerCount').disabled = !checkbox.checked;
document.getElementById('winner').disabled = !checkbox.checked;
document.getElementById('err_w_amount').remove();
return true;
}
}
var x2;
function set() {
var set = document.getElementById('winnerCount').value;
if (set.length > sum.length) {
document.getElementById('err_winnerCount').remove();
} else {
document.getElementById('set').innerHTML = "Please enter Set No. of Winners";
}
document.getElementById("demo").innerHTML = "Rank     Winning%           Winning Amount";
var x = document.getElementById("w_amount").value;
var w = document.getElementById("c_size").value;
var y = document.getElementById("winnerCount").value;
var a = parseInt(x) / parseInt(y);
var z;
var c;
var b = a / x * 100;
x2 = document.getElementsByClassName('tot');
if (y <= w) {
for (z = 1; z <= parseInt(y); z++) {
document.getElementById("demo1").innerHTML += +z + " <input type='text' class='tot' id='perc" + z + "' value='' onkeyup='getValues(this)'/> <input type='text' class='pop' id='val" + z + "' value='Rs." + a + "'/><br>";
}
for (i = 0; i < x2.length; i++) {
x2[i].value = b;
}
} else {
alert('errr');
$('#err_winnerCount').innerHTML = "Please enter less than contest size";
}
}
var sharePerc = 0;
function getValues(arg) {
var id = arg.getAttribute('id');
var value = this.value;
var winAmt = document.getElementById("w_amount").value;
var curPerc = document.getElementById(id).value;
//var str = "Visit Microsoft!";
var correspondingId = id.replace("perc", "val");
var curAmt = curPerc * (winAmt / 100);
document.getElementById(correspondingId).value = curAmt;
sharePerc = (100 - curPerc) / (x2.length - 1);
var shareValue = sharePerc * (winAmt / 100);
//console.log((100 - curPerc)/(x2.length-1));
for (var i = 1; i < x2.length + 1; i++) {
if (id != "perc" + i) {
document.getElementById("perc" + i).value = parseFloat(sharePerc).toFixed(0);
document.getElementById("val" + i).value = parseFloat(shareValue).toFixed(0);
}
}
//document.getElementById(id).disabled = true;
}
<form name="form" action="register" method="post" id="userForm">
<ul class="demo">
</br>
<li>Winning Amount:<input type="number" id="w_amount" onkeyup="sum()" onblur="validate()" name="wamount"><span class="err" id="err_w_amount"></span></li>
</br>
<li>Contest Size:<input type="number" id="c_size" onkeyup="sum()" onblur="checkTextField(this);" name="csize" value="2"></li>
</br>
<li>Entry Fee:<input type="number" id="e_fee" name="cname" onkeyup="sum()" value=""></li>
</br>
<!-- <li><input type="checkbox" id="MultiEntry"><p>Join this contest with multiple teams</p></li></br> -->
<li><input type="checkbox" id="test5" onchange="return isChecked(this, 'winnerCount');" /><label for="test5">Customize Winnings</label></li>
<li><span class="inTxt">Set No. of Winners</span>
<input type="number" maxlength="5" placeholder="min 2 & max 100" name="Name" id="winnerCount" disabled="disabled" /> </br>
</br>
<input class="W_set" type="button" name="button" value="Set" id="winner" disabled="disabled" onclick="set()"></input><span class="err" id="err_winnerCount"></span></li>
</br>
</ul>
</form>
<div>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
</div>
// firstly when giving winning amount and contest size we get the entry fee and after check in customize winning it will enable the set number of winners and set button.In set number of winners the input should be less than the contest size but while entering the greater than contest size it will not showing error message and after clicking set button we get a list of winners in this the winning % should be decreasing order while changing the default winning % of first text box but in my code while changing the second text box it changes the first text box also. if possible please know me how to solve this.
var result = 0;
function sum() {
var txtFirstNumberValue = document.getElementById('w_amount').value;
var txtSecondNumberValue = document.getElementById('c_size').value;
var result = 0;
if (txtFirstNumberValue > 0) {
result = ((0.15 * parseInt(txtFirstNumberValue)) + parseInt(txtFirstNumberValue)) / parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('e_fee').value = parseFloat(result).toFixed(0);
}
} else {
document.getElementById('e_fee').value = result;
}
}
// document.getElementById('e_fee').value = result;
function isChecked(checkbox, winnerCount) {
var winner_amount = document.getElementById('w_amount').value;
var chkMultiEntry = document.getElementById("test5");
if (winner_amount.length == 0) {
document.getElementById('err_w_amount').innerHTML = "Please enter winning amount";
chkMultiEntry.checked = false;
} else {
document.getElementById('winnerCount').disabled = !checkbox.checked;
document.getElementById('winner').disabled = !checkbox.checked;
document.getElementById('err_w_amount').remove();
return true;
}
}
var x2;
function set() {
$('#err_winnerCount').html("");
var set = document.getElementById('winnerCount').value;
var contestSize = document.getElementById('c_size').value;
if (set > contestSize) {
$('#err_winnerCount').html("");
} else {
//document.getElementById('set').innerHTML = "Please enter Set No. of Winners";
}
var x = document.getElementById("w_amount").value;
var w = parseInt(document.getElementById("c_size").value);
var y = parseInt(document.getElementById("winnerCount").value);
var a = parseInt(x) / parseInt(y);
var z;
var c;
var b = a / x * 100;
x2 = document.getElementsByClassName('tot');
if (y <= w) {
//document.getElementById("demo").innerHTML = "Rank     Winning%           Winning Amount";
var demoTableBody = document.getElementById("demo_table").tBodies[0];
demoTableBody.innerHTML = "";
//console.log(demoTableBody.innerHTML);
for (z = 1; z <= parseInt(y); z++) {
//console.log(demoTableBody.children.length);
var rowIndex = demoTableBody.children.length + 1;
var newRow = "<td>"+rowIndex+"</td>";
newRow += "<td><input type='text' class='tot' id='perc" + rowIndex + "' value='' onkeyup='getValues(this)'/><span class = 'perc_error_spn' id='perc_error" + rowIndex + "'></span></td>";
newRow += "<td><input type='text' class='pop' id='val" + rowIndex + "' value='Rs." + a + "'/></td>";
demoTableBody.innerHTML += newRow;
//document.getElementById("demo1").innerHTML += +z + " <input type='text' class='tot' id='perc" + z + "' value='' onkeyup='getValues(this)'/> <input type='text' class='pop' id='val" + z + "' value='Rs." + a + "'/><br>";
}
for (i = 0; i < x2.length; i++) {
x2[i].value = b;
}
} else {
alert("errr");
$('#err_winnerCount').html("Please enter less than contest size");
}
}
var sharePerc = 0;
function getValues(arg) {
// clear all error messages.
var errorSpans = document.getElementsByClassName("perc_error_spn");
for(var i = 0; i < errorSpans.length; i++){
errorSpans[i].innerHTML = "";
}
var id = arg.getAttribute('id');
var row_index = arg.parentNode.parentNode.rowIndex;
var value = this.value;
var winAmt = document.getElementById("w_amount").value;
var tmp = 0;
var previousWinnersPercentage = [];
var nextWinnersPercentage = [];
for(var i = 1; i < row_index; i++){
tmp += parseFloat(document.getElementById("perc" + i).value);
previousWinnersPercentage[previousWinnersPercentage.length] = tmp;
}
for(var i = row_index + 1 ; i <= x2.length; i++){
nextWinnersPercentage[nextWinnersPercentage.length] = parseFloat(document.getElementById("perc" + i).value);
}
//winAmt -= tmp;
var curPerc = document.getElementById(id).value;
sharePerc = (100 - tmp - curPerc) / (x2.length - row_index);
var isInvalidInput = isBiggerThanPreviousPercentage(previousWinnersPercentage,curPerc);
if(!isInvalidInput){
isInvalidInput = isLesserThanPreviousPercentage(nextWinnersPercentage,curPerc);
}
if((sharePerc <= 0 && x2.length > 1) || isInvalidInput){
var errorSpan = id.replace("perc", "perc_error");
document.getElementById(errorSpan).innerHTML = "Invalid input";
return;
}
//var str = "Visit Microsoft!";
var correspondingId = id.replace("perc", "val");
var curAmt = curPerc * (winAmt / 100);
document.getElementById(correspondingId).value = curAmt;
sharePerc = (100 - tmp - curPerc) / (x2.length - row_index);
var shareValue = sharePerc * (winAmt / 100);
//console.log((100 - curPerc)/(x2.length-1));
for (var i = row_index; i <= x2.length; i++) {
if (id != "perc" + i) {
document.getElementById("perc" + i).value = parseFloat(sharePerc).toFixed(0);
document.getElementById("val" + i).value = parseFloat(shareValue).toFixed(0);
}
}
//document.getElementById(id).disabled = true;
}
function reorderPercentage(){
var demoTableBody = document.getElementById("demo_table").tBodies[0];
for(var i = 0; i < demoTableBody.children.length; i++){
var percentageInput = demoTableBody.children[i].querySelector(".tot");
//console.log(percentageInput.value);
var row = percentageInput.parentNode.parentNode,
sibling = row.nextElementSibling,
parent = row.parentNode;
var siblingPercentageValue = "";
//console.log(sibling);
if(sibling != null){
siblingPercentageValue = sibling.querySelector(".tot").value;
}
if(percentageInput.value < siblingPercentageValue){
parent.insertBefore(sibling,row);
}
}
}
function isBiggerThanPreviousPercentage(array,value) {
var result = false;
result = array.some(function (e) {
if(value > e){
return true;
}
});
return result;
}
function isLesserThanPreviousPercentage(array,value) {
var result = false;
result = array.some(function (e) {
if(value < e){
return true;
}
});
return result;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form" action="register" method="post" id="userForm">
<ul class="demo">
</br>
<li>Winning Amount:<input type="number" id="w_amount" onkeyup="sum()" name="wamount"><span class="err" id="err_w_amount"></span></li>
</br>
<li>Contest Size:<input type="number" id="c_size" onkeyup="sum()" onblur="checkTextField(this);" name="csize" value="3"></li>
</br>
<li>Entry Fee:<input type="number" id="e_fee" name="cname" onkeyup="sum()" value=""></li>
</br>
<!-- <li><input type="checkbox" id="MultiEntry"><p>Join this contest with multiple teams</p></li></br> -->
<li><input type="checkbox" id="test5" onchange="return isChecked(this, 'winnerCount');" /><label for="test5">Customize Winnings</label></li>
<li><span class="inTxt">Set No. of Winners</span>
<input type="number" maxlength="5" placeholder="min 2 & max 100" name="Name" id="winnerCount" disabled="disabled" /> </br>
</br>
<input class="W_set" type="button" name="button" value="Set" id="winner" disabled="disabled" onclick="set()"/><span class="err" id="err_winnerCount"></span>
<input type="button" value="Reorder" onclick="reorderPercentage();"/>
</br>
</ul>
</form>
<div>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<table id="demo_table">
<thead>
<tr>
<th>Rank</th>
<th>Winning %</th>
<th>Winning Amount</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<style>
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {background-color: #f1f1f1}
.dropdown:hover .dropdown-content {
display: block;
}
.dropdown:hover .dropbtn {
background-color: #3e8e41;
}
table, th, td {
border: 1px solid black;
}
</style>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<h2>Hoverable Dropdown</h2>
<p>Move the mouse over the button to open the dropdown menu.</p>
<div class="dropdown">
<button class="dropbtn">10 Winners</button>
<div class="dropdown-content">
<table style="width:100%">
<tr>
<th>Rank</th>
<th>Prize</th>
</tr>
<tr>
<td>1</td>
<td>1000</td>
</tr>
<tr>
<td>2-5</td>
<td>500</td>
</tr>
<tr>
<td>6-10</td>
<td>100</td>
</tr>
</table>
</div>
</div>
</body>
If you input number of winners greater than contest size it will prompt an alert box. Check and let me know that is it working or not?
Due to below code both the text boxes are modified simultaneously.
If you can explain the below code, why you are using this
for (var i = 1; i < x2.length + 1; i++) {
if (id != "perc" + i) {
document.getElementById("perc" + i).value = parseFloat(sharePerc).toFixed(0);
document.getElementById("val" + i).value = parseFloat(shareValue).toFixed(0);
}
}