javascript/jquery incrementation check - javascript

I have very delicate problem, I'll make an example. What am i doing is that I'm basically prepending elements and differentiating them by incrementing (i need to do it this way for certain reasons), then there is an option to click on any element and delete it.
This is only stupid example of what it looks like:
$(function () {
var i = 0;
$("#new").click(function(){
i++;
$("#container").prepend("<div class='prepended "+i+"'>blah blah blah</div>")
$(".prepended").click(function(){
$(this).remove();
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="new">click here</button>
<div id="container"></div>
When I delete any element, I need to somehow manage to make the incrementing "i" variable fill the missing element. I don't know how to explain in words so I'll explain in "code":
Let's say I prepended 6 elements so the "i" variable is now 6:
if(deleted_divs_class == 1)
{
i = 1; // fill the missing "1"
next_click_i = 6; // variable i on next click should be 6 in order to continue in right order
}
else if (deleted_divs_class !== 1 || 6) // deleted element is somewhere from middle so it's not 1 or 6
{
i = fill_missing_number; // fill the removed number
next_click_i = 6; // continue in right order
}
else
{
i--;
// deleted element is the last element of line so continue normally by incrementing
}
i know how to get deleted_divs_class variable and apply the next_click_i variable but i don't know how make the whole thing work dynamically
I know that this question might seems very weird but this is just an example, it's part of much much much bigger code and i just need to make logic of this "incrementation" in order to make the whole thing work properly as i need.
So i just can not figure out the logic.

I suppose I created the code you are looking for, but I’m not sure if I understood your question correctly. Look at this code. Is this what you wanted or not?
$(function () {
var missed=[]; //Here will be stored missed numbers
var i = 0;
$("#new").click(function(){
var n=0;
if(missed.length>0) {
n=missed.shift(); //get next missed number from the array
} else
n=++i;
$("#container").prepend("<div data-i='"+n+"' class='prepended "+n+"'>"+n+"blah blah blah</div>")
});
$('#container').on('click',".prepended",[], function(){
missed.push($(this).data('i')); //save removed number into missed numbers array
$(this).remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="new">click here</button>
<div id="container"></div>

To backfill the deleted i values, you'll need to store them. In this example, deleted_i holds all deleted values, and attempts to retrieve the new value from there first when creating a new element. If it's empty, it defaults to incrementing the value of i.
Note also that the click event is now bound to the container so that it only fires once - in your example, it was getting re-bound to all .prepended elements, so that when you clicked on one, it was firing that function as many times as the loop had run so far.
$(function () {
var i = 0,
deleted_i = []
$("#new").click(function(){
var idx;
console.log(deleted_i)
if(deleted_i.length) idx = deleted_i.shift() //grab the first deleted index, if one exists
else idx = ++i;
$("#container").prepend("<div data-index='"+idx+"' class='prepended "+idx+"'>blah blah blah this is "+idx+"</div>")
});
$("#container").click(function(e){
var $target = $(e.target)
if($target.hasClass('prepended')){
$target.remove();
deleted_i.push($target.attr('data-index'))
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="new">click here</button>
<div id="container"></div>

Related

Count multiple div class in same page

I am trying to make a correct and incorrect question counter that shows groups of 4.
If I click on the first correct answer the counter works correctly and increases as I click, but it does not work with the second correct answer. The same happens with the wrong answers
This is the codes that I use, anyone could help me? Thx
HTML CODE:
¿Which of the following operations results in 8?
<input class="solucioncorrecta" value="6+2">
<input class="solucioncorrecta" value="7+1">
<input class="solucionincorrecta" value="1+1">
<input class="solucionincorrecta" value="2+2">
And the JS CODE:
<!-- CONTADOR FALLOS TEST -->
<script type="text/javascript">
var root = document.querySelector('.solucionincorrecta');
root.onclick = function() {
var elem = document.getElementById('contadorfallos');
elem.innerHTML = +elem.innerText + 1;
};
</script>
<!-- CONTADOR FALLOS TEST -->
<!-- CONTADOR ACIERTOS TEST -->
<script type="text/javascript">
var root = document.querySelector('.solucioncorrecta');
root.onclick = function() {
var elem = document.getElementById('contadoraciertos');
elem.innerHTML = +elem.innerText + 1;
};
</script>
The issue is that you are using document.querySelector() and not document.querySelectorAll()
document.querySelector() Returns the first match
document.querySelectorAll() Returns all matches
As a result, you are only setting an onclick property on the first .correcta and .incorrecta elements, not all of them.
To set this on all of them, you need to do two things:
You need use document.querySelectorAll() instead of document.querySelector(). This returns a list (specifically, a NodeList) of matching elements.
Loop over the items in your list, and attach onclick handlers to each of them. There are many ways to loop over a NodeList, listed here.
Here is an example:
// get all incorrect elements
var incorrectElements = document.querySelectorAll('.incorrecta');
// loop over each elements
for (var element of incorrectElements) {
// add an onclick
element.onclick = incorrectClickHandler
}
// this is the function being called by onclick
function incorrectClickHandler() {
score.innerText = parseInt(score.innerText) - 1;
}
It would be better if you upload your full codes. But anyway I write you some notes that probably answer your question.
-dont use the same name (root) for your .correcta and .incorrecta
-in your second <script>, you didnt defined button as an object . So browser cant understand it.

Javascript - want to press button repeatedly and have same function trigger

I'm making a quiz in Javascript and I want to be able to use the same button over and over for answers without reloading the page. Here's my code:
document.getElementById("nextBtn").addEventListener("click", function() {
let answers = document.getElementById('answers').value;
let inputAns = [0, 1, 2];
for (var i = 0; i < inputAns.length; i++) {
if (answers == inputAns[i]) {
document.getElementById("correctAnswers").innerHTML = "✅";
inputAns++;
} else {
document.getElementById("incorrectAnswers").innerHTML = "❌";
inputAns++;
}
}
});
and
<button type="submit" id="nextBtn" class="nextBtn">NEXT!</button>
</div>
<div class="correctAnswers" id="correctAnswers"></div>
<div class="incorrectAnswers" id="incorrectAnswers"></div>
So when the button (nextBtn) is pressed, it reads the input bar (answers) and checks to see if that matches the input of the array (inputAns). If it matches, a green check is displayed. If it doesn't, a red x is displayed. Then the loop adds to the array to make the answer change for the next question. This works one time. But when the button is pressed again, nothing happens. How can I make the function repeat so that more questions can be checked and checks or x's can appear? Thanks!
ETA: More HTML
The first thing you'll want to do is turn your .innerHTML to append rather than replace (with +=).
You'll also want to make use of a true equals in the conditional, or else an empty answer will be treated as the same thing as 0, and thus be valid for the first answer. If you do this, you'll also want to make use of parseInt(answers) rather than just answers.
After this, you'll want to shift your input array outside of your function, and set up a current answer variable as well. This should reference the first index of the array.
From here, you'll want to completely remove your loop, and simply run inputAns.shift() inside of your 'success' criteria; this will remove the first element in the array. Because of this, you're able to run the comparison against currentAnswer = inputAns[0]. If the first element is removed, the answer will be compared against the second element, and so on until all answers have been given.
Finally, you'll probably want to add a message or 'stop' condition when all answers have been entered. This can be done by checking if (!inputAns.length).
This can be seen in the following, where the correct answers are 0, 1, 12` in order:
let inputAns = [0, 1, 2];
let currentAnswer = inputAns[0];
document.getElementById("nextBtn").addEventListener("click", function() {
let answers = document.getElementById('answers').value;
if (parseInt(answers) === currentAnswer) {
document.getElementById("correctAnswers").innerHTML += "✅";
inputAns.shift();
if (!inputAns.length) {
console.log("All answers provided!");
}
} else {
document.getElementById("incorrectAnswers").innerHTML += "❌";
}
currentAnswer = inputAns[0];
});
<input id="answers" />
<button id="nextBtn">Next</button>
<div id="correctAnswers"></div>
<div id="incorrectAnswers"></div>

I create dynamically some text area in a div. How can i get its names in javascript?

This is my code to create the textarea and it works fine, but I want to know how many textarea the user creates and their names.
function createBoxEquip() {
$codEquip = $('#equipamento').val();
$nomeEquip = $('#equipamento>option:selected').text();
$novadiv = "#div"+$codEquip;
if ( !$( $novadiv ).length ) {
$("#equip_tot").append('<div class="box"name=div'+$codEquip+'id=div'+$codEquip+'></div>')
$("#div"+$codEquip).append('<span class="titulo1" name='+$codEquip+' id='+$codEquip+'> - '+$nomeEquip+'</span><span name=texto'+$codEquip+' id=texto'+$codEquip+'><br> </span>');
$("#div"+$codEquip).append('<input type="button" name=apagar'+$codEquip+' id=apagar'+$codEquip+' value="Remover" onclick="deleteBoxEquip('+$codEquip+')"><span name=texto1'+$codEquip+' id=texto1'+$codEquip+'> <br></span>');
$("#div"+$codEquip).append('<input type="text" style="width: 20px;" name=contalinhas'+$codEquip+' id=contalinhas'+$codEquip+'><span name=texto2'+$codEquip+' id=texto2'+$codEquip+'><br></span>');*/
$("#div"+$codEquip).append('<textarea style="width: 150px;" rows=12 name=numerosserie'+$codEquip+' id=numerosserie'+$codEquip+' value="'+$codEquip+' - '+$nomeEquip+'"/><span name=texto3'+$codEquip+' id=texto3'+$codEquip+'> </span>');
}
}
As long as you can pre-determine what the names of the textarea will be, for example - I've written similar code that generated a bunch of <div> tags with unique ID's, each Id was numeric, so I'd auto-generate a bunch of tags like this:
<div id="div-0">Zero</div>
<div id="div-1">One</div>
<div id="div-2">Two</div>
Because I know in advance that each div id will have the prefix div- followed by a digit which begins at 0 and increments sequentially, I can iterate through each element in a loop, and know when I've reached an undefined element:
function loopElements() {
var divPrefix = "div-";
var divNo = 0;
// Loop through all div- tags:
//
while (true) {
// The .length property will return 0 if the element
// doesn't exist...
//
if ($("#" + divPrefix + divNo.toString()).length == 0)
// This div doesn't exist, bail!
//
break;
// do something with div
divNo++;
}
}
Something like this would work, it depends on the names/id's you're creating, and if you can somehow predetermine what they should be.
hope this helps.
EDIT:
Having read your question again I think the above solution may not be what you're looking for, if not I apologise.
There are some ambiguities with your question...exactly how are these names created? Does the user choose them? Are they generated programmatically?
You should post more code and explain in greater detail.

using OOP on .click function in javascript

I am making a webpage that has a baseball strikezone with 25 buttons that will be clickable in 25 locations. I need to know if there is a easier way to do this then what I am doing. Maybe something that will take up far less lines. The button is clicked and then the counter is added by one to another table.
$('#one').click(function(){
counter++;
$('#ones').text(counter);
});
var countertwo = 0;
$('#two').click(function(){
countertwo ++;
$('#twos').text(countertwo);
});
A bit of a guess here, but:
You can store the counter on the button itself.
If you do, and you give the buttons a common class (or some other way to group them), you can have one click handler handle all of them.
You can probably find the other element that you're updating using a structural CSS query rather than id values.
But relying on those ID values:
$(".the-common-class").click(function() {
// Get a jQuery wrapper for this element.
var $this = $(this);
// Get its counter, if it has one, or 0 if it doesn't, and add one to it
var counter = ($this.data("counter") || 0) + 1;
// Store the result
$this.data("counter", counter);
// Show that in the other element, basing the ID of what we look for
// on this element's ID plus "s"
$("#" + this.id + "s").text(counter);
});
That last bit, relating the elements by ID naming convention, is the weakest bit and could almost certainly be made much better with more information about your structure.
You can use something like this:
<button class="button" data-location="ones">One</button>
...
<button class="button" data-location="twenties">Twenty</button>
<div id="ones" class="location">0</div>
...
<div id="twenties" class="location">0</div>
$('.button').on('click', function() {
var locationId = $(this).data('location')
, $location = $('#' + locationId);
$location.text(parseInt($location.text()) + 1);
});
Also see this code on JsFiddle
More clean solution with automatic counter
/* JS */
$(function() {
var $buttons = $('.withCounter'),
counters = [];
function increaseCounter() {
var whichCounter = $buttons.index(this)+1;
counters[whichCounter] = counters[whichCounter] ? counters[whichCounter] += 1 : 1;
$("#counter"+whichCounter).text(counters[whichCounter]);
}
$buttons.click(increaseCounter);
});
<!-- HTML -->
<button class="withCounter">One</button>
<button class="withCounter">Two</button>
<button class="withCounter">Three</button>
<button class="withCounter">Four</button>
<p id="counter1">0</p>
<p id="counter2">0</p>
<p id="counter3">0</p>
<p id="counter4">0</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Getting inner HTML from different ids

I'm just now starting to try to learn Javascript, so bear with me. I'm trying to get information from a list on one part of my page to a new section with three places at the click of a button.
Each item in the list has its own button, and I need my script to know which place to put the list item based on the number of times the button has been clicked (which should coincide with how many list items have already been added to the list).
I've tried created a script to increase i and take the id of the paragraph into a function, but I can't seem to make it work. I'm hoping that by "counting" the number of times the button has been clicked, it will put each new list item that has been added in the next place in the new section.
I'm not sure how to make the counting part work, though, and it has just occurred to me that maybe the first part of my function constantly remains at zero.
I would really appreciate any help that I can get with this.
Thanks in advance!
Here's my code:
<script>
function increase(place) {
var i = 0;
addToDilly(i, place);
i++;
}
function addToDilly(num, place) {
if num = 0 {
document.getElementById("firstStop").innerHTML = document.getElementById(place).innerHTML;
}
if num = 1 {
document.getElementById("secondStop").innerHTML = document.getElementById(place).innerHTML;
}
if num = 2 {
document.getElementById("thirdStop").innerHTML = document.getElementById(place).innerHTML;
}
}
</script>
<p id="firstStop">This is a paragraph.</p>
<p id="secondStop">This is another paragraph.</p>
<p id="thirdStop">This is another paragraph.</p>
<hr/>
<p id="1">Royal Oak <button onclick="increase(1)">Add To Dilly</button></p>
<p id="2">Ferndale <button onclick="increase(2)">Add To Dilly</button></p>
<p id="3">Chesterfield <button onclick="increase(3)">Add To Dilly</button></p>
Try this script:
<script>
var i = 0;
function increase(place) {
console.log(place);
addToDilly(i, place);
i++;
}
function addToDilly(num, place) {
if (num == 0) {
document.getElementById("firstStop").innerHTML = document.getElementById(place).innerHTML;
}
if (num == 1) {
document.getElementById("secondStop").innerHTML = document.getElementById(place).innerHTML;
}
if (num == 2) {
document.getElementById("thirdStop").innerHTML = document.getElementById(place).innerHTML;
}
}
</script>
Here's the running example
I would suggest a complete re-write. If your aim is to update a list of items, just update a list of items (literally) :)
Note: You originally tagged your question as jQuery, so this initial answer is in jQuery.
The text you wish to add needs to been in an element related to the button, but not containing the button itself. For this example I placed them before the buttons.
e.g. http://jsfiddle.net/TrueBlueAussie/t13h54bu/3/
$('button').click(function () {
var $button = $(this);
var text = $button.prev('p').html();
var $target = $('#list');
$target.append($('<li>').html(text));
});
and simpler HTML:
<ul id="list"></ul>
<hr/>
<p>Royal Oak</p>
<button>Add To Dilly</button>
<p>Ferndale</p>
<button>Add To Dilly</button>
<p>Chesterfield</p>
<button>Add To Dilly</button>
Then if you want to limit the items to 3 add this:
if ($target.children().length < 3) {
$target.append($('<li>').html(text));
}
http://jsfiddle.net/TrueBlueAussie/t13h54bu/4/

Categories