I'm very new to Javascript and am looking for a way to have my code only respond to the clicked item in the list. (full JSFiddle here: http://jsfiddle.net/5cjPF/, although for some reason buttons aren't responsive...)
For the functions below, each applies only to a certain clicked item, however, right now only the first item that each refers to is responding. A friend of mine suggesting creating a class for each function, but I honestly have no idea where to begin and would really appreciate a push in the right direction!
<script type="text/javascript">
var submitcount = 0;
function arrow() {
if (submitcount == 0 || submitcount % 2 == 0) {
var extension = document.getElementById('one');
extension.insertAdjacentHTML('beforeend', '<div id="before-two"><div id="two"><div class="btn-group"><!----><button type="button" class="left" onclick="modify_qtyTag(1)"></button><!----><button type="button" class="tag" id=tag>synonyms</button><!----><button type="button" class="right" onclick="modify_qtyTag(0)"></button><!----></div><div class="btn-group"><button type="button" class="left" onclick="modify_qtyTag(1)"></button><!----><button type="button" class="tag" id=tag>beast</button><!----><button type="button" class="right" onclick="modify_qtyTag(0)"></button></div><p><div class="btn-group"><!----><button type="button" class="left" onclick="modify_qtyTag(1)"></button><!----><button type="button" class="tag" id=tag>antonyms</button><!----><button type="button" class="right" onclick="modify_qtyTag(0)"></button><!----></div><div class="btn-group"><button type="button" class="left" onclick="modify_qtyTag(1)"></button><!----><button type="button" class="tag" id=tag>gentle</button><!----><button type="button" class="right" onclick="modify_qtyTag(0)"></button></div></p></div></div></div>');
}
else if(document.getElementById('two')) {
var deleted = document.getElementById('before-two');
deleted.remove(deleted.selectedIndex);
}
submitcount += 1;
};
var upvotes = 0;
var votes = 0;
function modify_qty(val) {
var qty = document.getElementById('qty').value;
votes += 1;
upvotes += val;
var percent = Math.round((upvotes / votes) * 100);
document.getElementById('qty').value = percent;
}
var upvotesTag = 0;
var votesTag = 0;
function modify_qtyTag(val) {
var extension = document.getElementById('tag');
votes += 1;
upvotes += val;
var percent = Math.round((upvotes / votes) * 100);
var allThings = percent + "%," + " 100%," + " 100%," + " 100%;";
extension.style.backgroundSize = allThings;
extension.style.backgroundSize = "100%";
extension.style.backgroundSize = percent + "%, 100%, 100%, 100%";
}
</script>
The JS should be:
function modify_qtyTag(val, tagid) {
var extension = document.getElementById(tagid);
var votes = parseInt(extension.getAttribute("data-votes"), 10) + 1;
var upvotes = parseInt(extension.getAttribute("data-upvotes"), 10) + val;
var percent = Math.round((upvotes / votes) * 100);
var allThings = percent + "%," + " 100%," + " 100%," + " 100%;";
extension.style.backgroundSize = allThings;
extension.setAttribute('data-votes', votes);
extension.setAttribute('data-upvotes', upvotes);
}
The HTML would be something like:
<button type="button" class="left" onclick="modify_qtyTag(1, 'tag1')"></button>
<button type="button" class="tag" id="tag1" data-votes="0" data-upvotes="0">synonyms</button>
This adds an argument to the function that tells it which tag to update. And instead of using global variables for the votes and upvotes, it stores it in data attributes in the tag element, so that each one can have its own percentage.
Related
let table = 6;
let i = 1;
$(function() {
let $newOperatorButton = $('button');
$newOperatorButton.on('click', function math(){
let msgOperator = '';
let expression;
let operator = $(this).attr("value");
if(operator === '+'){
msgOperator = ' + ';
expression = (table + i);
while(i < 11){
msg += table + msgOperator + i + ' = ' + (table + i) + '<br />';
i++;
}
} else if (operator === '-') {
msgOperator = ' - ';
expression = (table - i);
while(i < 11){
msg += table + msgOperator + i + ' = ' + (table - i) + '<br />';
i++;
}
some code missing but it adds multiplication and division
let el = document.getElementById('blackboard');
el.innerHTML = msg;
}
);
});
This code is inside the body tag in my index.html
<section id="page">
<section id="blackboard"></section>
</section>
<form id="operator">
<button name="add" type="button" value="+">+</button>
<button name="subtract" type="button" value="-">-</button>
<button name="multiply" type="button" value="x">x</button>
<button name="division" type="button" value="/">/</button>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="/index.js"></script>
I have it so it prints out a table with 10 numbers depending on the button clicked. For ex. table = 6 and i = 1 is 6+1=7.... 6+10=16
You need an if statement at the end that reset your equations and variables.
after you've run your equation "i" is still equal to 11 so it never passes into the while loops again, you also need to empty your message so it doesn't keep adding addition text to your existing text.
$("#blackboard").html(msg)
if (i == 11) {
i = 1
msg = ""
}
Prints '2 x 10 = 20' but not the whole table when the input is 2. I tried various means. But the result is same.
No error. Just like to print the whole multiplication table.
function loop() {
var i = 1;
var x = document.getElementById("num").value;
//document.getElementById("result").value = result;
while (i <= 10) {
document.getElementById("result").value = x + " x " + i + " = " + i * x;
i++;
}
}
<h1>While loop: </h1>
<p>The while loop keeps repeating an action until an associated condition returns false.</p>
<img src="images/loop.jpg" /><br/>
<img src="images/loop2.jpg" /><br/>
<body>
<p>JavaScripts Runs:</p>
<script src="while_1loop.js">
</script><br/> What number table would you like to have?<input type="number" name="" id="num" /><br>
<button type="button" onclick="loop()" ;>Start</button><br>
<textarea rows="12" cols="15" id="result" readonly>
</textarea><br/>
You are always changing the value of 'result' rather than adding to it:
function loop() {
var i = 1;
var x = document.getElementById("num").value;
//document.getElementById("result").value = result;
while (i <= 10) {
var result = document.getElementById("result");
var sum = document.createTextNode(x + " x " + i + " = " + i * x + "\n");
result.appendChild(sum);
i++;
}
}
<h1>While loop: </h1>
<p>The while loop keeps repeating an action until an associated condition returns false.</p>
<img src="images/loop.jpg" /><br/>
<img src="images/loop2.jpg" /><br/>
<body>
<p>JavaScripts Runs:</p>
<script src="while_1loop.js">
</script><br/> What number table would you like to have?<input type="number" name="" id="num" /><br>
<button type="button" onclick="loop()" ;>Start</button><br>
<textarea rows="12" cols="15" id="result" readonly>
</textarea><br/>
If I understand what you mean,
You rewrite whole textarea with this code:
document.getElementById("result").value = x + " x " + i + " = " + i * x;
but you need add new result after older results. Something like this:
var oldValue = document.getElementById("result").value;
var result = x + " x " + i + " = " + i * x;
document.getElementById("result").value = oldValue + '\n' + result;
This is my problem: if I try to erase the last element that I pushed with the relative button everything works, but if I try to erase the first (or at least not the last one), all the elements in the array are erased.
To avoid this I used $.inArray to check if the element is in the Array and to erase only the element in that index, but it doesn't help.
What I want is to be able to erase the element I want and only the one that I select.
$(document).ready(function() {
var array = [];
$('.add').click(function(e) {
var $thisEvent = $(e.currentTarget).closest('.event');
var i = $thisEvent.find('.i').text();
array.push(i);
console.log(i +' added, Array is now ' + array);
$thisEvent.append('<button class="remove">🗙' + i + '</button>');
var $total = 0;
for (var y = 0; y < array.length; y++) {
$total += array[y] << 0;
}
$('.total').html('The sum of the elements in the array is ' + $total);
$('.remove').click(function() {
if ($.inArray(i, array) !== -1) {
array.splice($.inArray(i, array), 1);
console.log(i + ' removed, Array is now ' + array);
} else {
console.log('There is no ' + i + ' to remove from the array!');
}
$(this).remove();
var $total = 0;
for (var y = 0; y < array.length; y++) {
$total += array[y] << 0;
}
$('.total').html('The sum of the elements in the array is ' + $total);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="event">
<span class="i" style="margin-right: 5px;">1</span><button class="add">Add to Array</button>
</div>
<br />
<div class="event">
<span class="i" style="margin-right: 5px;">2</span><button class="add">Add to Array</button>
</div>
<br />
<div class="event">
<span class="i" style="margin-right: 5px;">3</span><button class="add">Add to Array</button>
</div>
<p class="total"></p>
Try changing
$thisEvent.append('<button class="remove">🗙' + i + '</button>');
To
var $remove = $('<button class="remove">🗙' + i + '</button>');
$thisEvent.append($remove);
Then change
$('.remove').click(function() {
To
$remove.click(function() {
This way you aren't adding a new click event listener to all the other remove buttons every time a new one is added
I am having some trouble to get through this below jsfiddle task.
jsfiddle link
I want to do the same function using dynamic id.
I tried so many methods, but nothing works.
Please don't recommend to change the infrastructure. The page has been already designed the same kind of structure.
I need to achieve this same kind of function using two nested for loops with dynamic id.
HTML:
<div class="col-md-4" id="beforeDiv0">
<div class="col-md-2" style="padding-right: 0px; padding-top: 5px;">
<label for="Amount" style="font-weight:bold;">Amount:</label>
</div>
<div class="col-md-6">
<input class="form-control" type="number" id="textboxId0" value="1000" />
</div>
</div>
<br/><br/>
<div class="col-md-4" id="beforeDiv1">
<div class="col-md-2" style="padding-right: 0px; padding-top: 5px;">
<label for="Amount" style="font-weight:bold;">Amount:</label>
</div>
<div class="col-md-6">
<input class="form-control" type="number" id="textboxId1" value="1000" />
</div>
</div>
Javascript & jQuery:
$(document).ready(function(){
var newAmount = parseFloat(1000) + parseFloat(5);
for(var id=0; id<3; id++){
for (var i = 1; i < 3; i++) {
var html = '<tr style="height:50px;">';
html = html + '<td class="td-Amount" style="text-align: right; font-size: 15px; font-weight: bold;">';
html = html + 'Original: '+ '<span id="OrginalAmount' + i + '">' + 1000 + '</span><br/>' + 'New: <span id="Output' + id + "" + i + '">' + newAmount + '</span></td>';
html = html + '</tr>';
$(html).insertAfter("#beforeDiv" + id);
//var abc = id + "" + i;
//var xyz = '#textboxId' + id;
//var zyx = "Output"+id+""+i;
}
}
var myArr = new Array();
var myArr2 = new Array();
for(var id=0; id<3; id++){
var xyz = '#textboxId' + id;
myArr[id] = id;
for (var i = 1; i < 3; i++) {
myArr2[i] = i;
var calc = myArr[id] + "" + myArr2[i];
var zyx = "Output" + calc;
//below line is for dynamic id retrieval
/*
$(xyz).on("click change paste keyup", function() {
var x = parseFloat(1000);
var y = parseFloat($(this).val());
var AmtChange = x + y;
document.getElementById(zyx).innerHTML = AmtChange;
});
*/
$("#textboxId0").on("click change paste keyup", function() {
var x = parseFloat(1000);
var y = parseFloat($(this).val());
var AmtChange = x + y;
document.getElementById("Output01").innerHTML = AmtChange;
document.getElementById("Output02").innerHTML = AmtChange;
});
$("#textboxId1").on("click change paste keyup", function() {
var x = parseFloat(1000);
var y = parseFloat($(this).val());
var AmtChange = x + y;
document.getElementById("Output11").innerHTML = AmtChange;
document.getElementById("Output12").innerHTML = AmtChange;
});
}
}
});
I looked at your code, and considered your comments, and if I understand you correctly, then something like this is what you are after:
$('input[id^=textboxId]').on("click change paste keyup", function() {
var id = $(this).attr('id');
id = id.replace(/\D/g,'');
var x = parseFloat(1000);
var y = parseFloat($(this).val());
var AmtChange = x + y;
/**
* The following could not really be simplified, because
* there are no defining data- attributes, or anything
* to identify the table rows as belonging to the textbox.
* When I tried to simplify the selection of "output" spans,
* a span with id Output111 would have been matched by Output11
* and Output1.
*/
$('#beforeDiv' + id).nextUntil('br').each(function(i,el){
$('span[id^=Output]', this).text(AmtChange);
});
});
I tested this on Codepen: https://codepen.io/skunkbad/pen/ayeVLp
First, JSFiddle does not properly display result of my code, so I'll use CodePen, if that's ok.
Well, I'm trying hard to make a Pomodoro timer, but I'm stuck on pause/resume session. I have to be able to stop executing the function on click(and it should display that particular moment on screen, for example 22:22), and on another click it should be resumed. I know that eval() is not desirable, but could someone please help me with completing my awful code (I know it's a mess, but I'm learning JS every day)? To be more precise, I've managed to pause/stop execution, but I need help with resuming it.
Here is the code:
$( document ).ready(function(){
var toggle = true;
var a = document.getElementById("breakvalue");
a.innerHTML = 7;
var b = document.getElementById("sessionvalue");
b.innerHTML = 25;
$("#crcl").html("<h3>Session</h3>" + "</break>" + "<h1 id = numb>" + b.innerHTML + "</h1>");
$("#breakplus").on("click", function(){
$("#breakvalue").html(eval(a.innerHTML)+1);
});
$("#breakminus").on("click", function(){
if (a.innerHTML>=2){
$("#breakvalue").html(eval(a.innerHTML)-1);
}
});
$("#sessionplus").on("click", function(){
$("#sessionvalue").html(eval(b.innerHTML)+1);
$("#crcl").html("<h3>Session</h3>" + "</break>" + "<h1 id = numb>" + b.innerHTML + "</h1>");
});
$("#sessionminus").on("click", function(){
if(b.innerHTML>=2){
$("#sessionvalue").html(eval(b.innerHTML)-1);
$("#crcl").html("<h3>Session</h3>" + "</break>" + "<h1 id = numb>" + b.innerHTML + "</h1>");
}
});
$("#crcl").on("click", function (){
var capture = document.getElementById("crcl");
var inner = capture.innerHTML;
var head = document.getElementById("numb");
var inn = head.innerHTML;
if(toggle&&isNaN(inn)){
inter = setInterval(function(){
console.log(inn);
minutes = eval(inn.slice(0,2));
seconds=eval(inn.slice(3));
console.log(minutes);
console.log(seconds);
if(seconds>=0){
$("#crcl").html("<h3>Session</h3>" + "</break>" + "<h1>" + minutes + ":" + seconds-- + "</h1>");}
if (seconds<0){
seconds=59;
minutes = eval(minutes-1);
$("#crcl").html("<h3>Session</h3>" + "</break>" + "<h1>" + minutes + ":" + seconds-- + "</h1>");}
if(eval(minutes)<0){
$("#crcl").html("<h1>BREAK!!!</h1>");
clearInterval(inter);
}
toggle=false;
}, 1000);
}
if(toggle&&!isNaN(inn)){
var minutes = eval(b.innerHTML-1);
var seconds=59;
inter = setInterval(function(){
if(seconds>=0){
$("#crcl").html("<h3>Session</h3>" + "</break>" + "<h1 id = numb>" + minutes + ":" + seconds-- + "</h1>");
}
if (seconds<0){
seconds=59;
minutes = eval(minutes-1);
$("#crcl").html("<h3>Session</h3>" + "</break>" + "<h1 id = numb>" + minutes + ":" + seconds-- + "</h1>");}
if(eval(minutes)<0){
$("#crcl").html("<h1>BREAK!!!</h1>");
clearInterval(inter);
}
toggle=false;
}, 1000);
}
if (!toggle) {
clearInterval(inter);
console.log(toggle);
toggle=true;
console.log(toggle);
$("#crcl").remove();
$(".center-block").html("<button type=button class= circle btn btn-primary id = crcl>" + inner + "</button>");
}
});
});
h5{
display:inline-block;
}
p{
font-size:30px;
}
.circle
{
width:500px;
height:500px;
border-radius:50%;
font-size:20px;
color:#fff;
line-height:500px;
text-align:center;
background:#000;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class = "container text-center">
<div>
<h1>Pomodoro Clock</h1>
</div>
<div class="container text-center" id = "length">
<h5>BREAK LENGTH</h5>
<h5>SESSION LENGTH</h5>
</div>
<div class="btn-group text-center">
<button type="button" class="btn btn-primary"id = "breakplus">+</button>
<p id = "breakvalue"></p>
<button type="button" class="btn btn-primary"id = "breakminus">-</button>
</div>
<div class="btn-group text-center">
<button type="button" class="btn btn-primary" id = "sessionplus">+</button>
<p id = "sessionvalue"></p>
<button type="button" class="btn btn-primary"id = "sessionminus">-</button>
</div>
<div class="center-block"><button type="button" class=" circle btn btn-primary" id = "crcl"></button></div>
</div>
</body>
This is the link to my Codepen
Ok, here is JSFiddle, too.
Solved. My mistakes were: forgetting h1 IDs on several places, putting minutes and seconds inside an if statement, and - biggest of all - putting stupid extra code inside the function:
$("#crcl").remove();
$(".center-block").html("<button type=button class= circle btn btn-primary id = crcl>" + inner + "</button>");