I have an HTML page with 2 divs (among other things) - "person" and "person-success", in which "person" is visible and "person-success" hidden. When a button in "person" is clicked, the visible div hides and the previously-hidden div "person-success" shows. The code is given below:
<div id="person">
<br><br>
<div id="counterNum" class="counter-color" l10nID="M_AC_UT_TXT_20"></div>
<div role="form">
...
<button type="submit" id="addPerson" class="btn btn-success" l10nID="M_LG_BTN_1"></button>
</div>
</div>
<div id="person-success" class="hide">
...
<p>
<span l10nID='M_AC_UT_TXT_19'></span>
You can add <span id="limit"></span> more people. <a href='<?php echo $root; ?>edituseraccount.php?action=addPerson'>Add another person?</a>
</p>
</div>
The JavaScript:
$('#addPerson').click(function() {
var counter = 0;
var limit = 10;
var args = {
...
$.post("addperson.php",args,function(data){
var response = JSON.parse(data);
if(response.status == 0){
counter += 1;
if (counter < limit){
$('#counterNum').text(counter);
$('#person').hide();
$('#limit').text(limit-counter);
$('#person-success').show();
}
}
console.log(data);
});
});
Now, when the button is pressed, while "person-success" will show, clicking on "Add another person?" should show "person" and hide "person-success" again. Only this time, the div "counterNum" should be updated with the value of "counter" from the JavaScript. With my code, clicking the link reopens the "person" div and hides the other, but counterNum is not updated, or even shown. Does anyone know how I could do that?
I hope I could explain my problem. Would be grateful for any help!!
Var counter Make it as global. Because each time when you click on the addPerson button when counter resets to zero.
var counter = 0;
var limit = 10;
$('#addPerson').click(function() {
var args = {
...
$.post("addperson.php",args,function(data){
var response = JSON.parse(data);
if(response.status == 0){
counter += 1;
if (counter < limit){
$('#counterNum').text(counter);
$('#person').hide();
$('#limit').text(limit-counter);
$('#person-success').show();
}
}
console.log(data);
});
});
The variable you declare is local scope.
Declare variable globally outside the click event called.
On each click it resets counter to 0.
Hope it helps !!!
Related
So I want to add to a variable every time someone clicks a button on my website. I am very new to HMTL so I don't know how to do this. All the examples I've googled just change text into other text and not adding to a variable.
If someone would like to enlighten me on how to do this I would greatly apricate it.
function changeIt() {
document.getElementById('test').innerHTML = "<h2>Congrats</h2>";
}
<div id="test">
<b> <var> Test </ var> </b>
</div>
<button onclick="changeIt()">Test</button>
var sum = 0;
function changeIt() {
sum++;
document.getElementById('test').innerHTML = `<h2> ${sum} </h2>`;
}
<div id="test">
<b> <var> Test </ var> </b>
</div>
<button onclick="changeIt()">Test</button>
The code you've written in document.innerHTML is correct. For making it dynamic and to add a new Congrats onto the screen instead of just modifying the old one, you need to keep a global counter and loop over it.
let count = 0;
function changeIt() {
count++;
for (let i=0;i<count;i++) {
document.getElementById('test').innerHTML = '';
let h2 = document.getElementById('test').createElement;
h2.innerHTML = "Congrats";
document.getElementById('test').appendChild(h2);
}
}
Since you are calling the changeIt function on every button click it will let you update the count and will loop over the count to add the Congrats 'count' number of times to your div.
I try to make a cart page with 'empty cart' button and 'add to cart' button. I want to make the list so it adds under each other. In my code each time I press "add to shopping cart" it comes right beside each other with no spaces(instead of coming on the next line). What should I do?
How do I also make an 'empty cart' button once I have all the products added, is there a method to remove all the nodes in the cart using a function?
window.onload = start;
function start()
{
console.log('start');
}
function addTo()
{
document.getElementById("output").innerHTML += document.getElementById("txtProduct").value;
}
function empty()
{
}
<label>Product</label> <input type="text" id="txtProduct">
<button onclick="addTo()">Add to shopping cart</button>
<button onclick="empty()">Empty cart</button>
<p id="output"></p>
Check this out:
window.onload = start;
function start()
{
console.log('start');
}
function addTo()
{
var product = document.createElement("p");
product.innerText = document.getElementById("txtProduct").value;;
document.getElementById("wrapper").appendChild(product);
}
function empty()
{
document.getElementById("wrapper").innerHTML = "";
}
<label>Product</label> <input type="text" id="txtProduct">
<button onclick="addTo()">Add to shopping cart</button>
<button onclick="empty()">Empty cart</button>
<div id="wrapper">
<p id="output"></p>
</div>
I added a wrapper div so you could clean it on "empty" action.
Also I used the JS createElement function to create a <p> element for each product, it's more clean and right than adding just text to element's innerHTML. That makes them line-seperated, too...
Just change your addTo function like this:
function addTo() {
var elem = document.createElement("p");
elem.innerHTML = document.getElementById("txtProduct").value;
document.getElementById("output").appendChild(elem);
document.getElementById("txtProduct").value = "";
}
What this does is that every time you call the function, you create a p element with the value of txtProduct, it then appends the elem to the DOM and clear the value of txtProduct so you do not have to clear it manually each time you enter a value.
Then, change your empty function:
function empty() {
document.getElementById("output").childNodes.forEach((node) => {
node.innerHTML = "";
})
}
This is the jsbin test
I am trying to do a web app similar to google calendar. I have done the object and methods within it but now it's time to be able to add what I want as a task. My idea is for the user to add something to the input and that input being console.logged for now.
Any idea?
HTML
<div class="new-task" id="task-input">
<div id="add-new-task">Task: <input type="text"></div>
<div id="add-time">Time: <input type="text"></div>
<button class ="save-task" onclick="">Save task</button>
</div>
Javascript
var idCounter = 0
var tasksManager = {
array: [],
add: function(task){
taskObject = {
title: task,
idVerification: idCounter ++
}
tasksManager.array.push(taskObject)
},
show:function(id){
var i;
for (i = 0; i < tasksManager.array.length; i++) {
if(id === tasksManager.array[i].idVerification){
return tasksManager.array[i]
}
}
},
delete:function(task){
if(this.show){
tasksManager.array.splice(task)
}
}
}
var newTask = document.getElementById("add-new-task")
newTask.addEventListener('click',tasksManager.add())
console.log(tasksManager.array)
As you can see with console.log above the array index [0] is logged as undefined but I wanted the user to write in the input " Go to the gym" and this to be logged within the array.
Thanks
Some issues:
You are not assigning the click handler. Instead you execute it immediately (not on click).
When you call .add() you don't provide an argument: the name of the task
The click handler should be on the button element, not on the div that has the input element. And so it will be useful to give that button an id attribute.
You should retrieve the value from the input element, and so it would be more appropriate to give that element an id and not so much the div that wraps it.
The console.log at the end of your script is executed immediately. It should be done only when the user has clicked the button.
Snippet with some corrections (also in the HTML!):
var idCounter = 0
var tasksManager = {
array: [],
add: function(task){
let taskObject = {
title: task,
idVerification: idCounter ++
}
tasksManager.array.push(taskObject)
},
show:function(id){
var i;
for (i = 0; i < tasksManager.array.length; i++) {
if(id === tasksManager.array[i].idVerification){
return tasksManager.array[i]
}
}
},
delete:function(task){
if(this.show){
tasksManager.array.splice(task)
}
}
}
var button = document.getElementById("save-task"); // <-- the button
var input = document.getElementById("add-new-task"); // <-- the input (move the ID attribute to the input!)
button.addEventListener('click', () => {
tasksManager.add(input.value);
console.log(tasksManager.array)
})
<div class="new-task" id="task-input">
<div >Task: <input id="add-new-task" type="text"></div>
<div id="add-time">Time: <input type="text"></div>
<button class ="save-task" id ="save-task" onclick="">Save task</button>
</div>
I want to know how to make sure either the Yes or No button is toggled in my survey in order to continue (so if either Yes or No has been clicked, the nextQuestion function can continue. If Yes or No has not been clicked, I will give an alert to the user to please make a selection). I currently have the progress bar and question updating in the same function. I figured it would make sense to add this bit to it but I am getting confused.
var index_question = 0;
var question_number = 2;
var progress_question = 1;
var percentage = 0;
function nextQuestion(){
if (index_question < 4) && ($(".btn-success").button('toggle')) {
<!-- Question # and Question Text -->
document.getElementById("questionArea").innerHTML = questionSet[index_question];
index_question ++;
document.getElementById("questionNum").innerHTML = [question_number];
question_number ++;
<!-- Progress Bar -->
percentage = ((([progress_question])*(100))/(5));
progress_question++;
$(".progress-bar").width([percentage] + "%");
}
<!-- Survey Completed -->
else {
$(".progress-bar").width("100%");
alert("Thank you for completing the survey!")
}
}
<td><button class="btn btn-success" type="button" onclick="questionDecision">Yes</button></td>
<td><button class="btn btn-danger" type="button" onclick="questionDecision">No</button></td>
function questionDecision() {
$(".btn btn-success").button('toggle');
$(".btn btn-danger").button('toggle');
}
One option is to have a variable in the Javascript like var answered_question = False;, which is set to True in your questionDecision function after they have made a choice. Before advancing the user to the next question or updating the progress bar, always check if(clicked_yes_or_no==True){ }.
I want the "displayround" div to show a certain value in my array. When the page loads the first value in the array (1/38) is being displayed. When I press the "next" button I want it to show the next value in the array (2/38) and so on. And when I press "previous" button I want it to display the value that comes before the displayed value.
HTML:
<div id="buttonholder">
<button id="previous">< Previous round</button>
<button id="next">Next round ></button>
<button id="current">> Current round <</button>
<div style="font-size: 0;">
<form id="inputfield">
<input type="inputfield" value="Search for round here..."></input>
<button id="submit">Go</button>
</form>
</div>
<div id="displayround">
</div>
</div>
My Jquery/javascript:
$(document).ready(function() {
var round = new Array();
round[0]="1/38";
round[1]="2/38";
round[2]="3/38";
round[3]="4/38";
round[4]="5/38";
round[5]="6/38";
round[6]="7/38";
round[7]="8/38";
round[8]="9/38";
round[9]="10/38";
round[10]="11/38";
round[11]="12/38";
round[12]="13/38";
round[13]="14/38";
round[14]="15/38";
round[15]="16/38";
round[16]="17/38";
round[17]="18/38";
round[18]="19/38";
round[19]="20/38";
round[20]="21/38";
round[21]="22/38";
round[22]="23/38";
round[23]="24/38";
round[24]="25/38";
round[25]="26/38";
round[26]="27/38";
round[27]="28/38";
round[28]="29/38";
round[29]="30/38";
round[30]="31/38";
round[31]="32/38";
round[32]="33/38";
round[33]="34/38";
round[34]="35/38";
round[35]="36/38";
round[36]="37/38";
round[37]="38/38";
$("#buttonholder").find("button").addClass("left")
$("#buttonholder").find("#submit").removeClass("left").addClass("right")
$("#buttonholder").find("#inputfield").addClass("right");
$("#displayround").text(round[0]);
Here is the next button function:
$("#next").click(function() {
$("#displayround").text()
});
}); //end of document.ready function
Any help appreciated!
I will store index in some location, such .data()
Initially
$("#displayround").text(round[0]).data('index', 0);
In function next function call fetch index and use it
$("#next").click(function() {
var index = +$("#displayround").data('index');
$("#displayround").text(round[index + 1]).data('index', index + 1);
});
Similarity, In previous method call
Note: You have take care array length
EDIT
do you have a solution similar to ojovirtual regarding the overflow? When it's at 38/38 I want it to go back to 1/38 and vice versa.
$("#previous").click(function () {
var index = +$("#displayround").data('index') - 1;
if (index <= 0) index = round.length - 1;
$("#displayround").text(round[index]).data('index', index);
});
$("#next").click(function () {
var index = +$("#displayround").data('index') + 1;
if (index >= round.length) index = 0;
$("#displayround").text(round[index]).data('index', index);
});
DEMO
You can add a hidden field with the value you are showing and update it every time the user clicks "next" or "previous":
<input type='hidden' name='actualValue' value='0'/>
And then in your javascript:
$("#next").click(function() {
var actualValue=parseInt($("input[name=actualValue]").val());
$("#displayround").text(round[actualValue]);
actualValue++;
if (actualValue >= round.length) //check for overflow
actualValue=0;
$("input[name=actualValue]").val(actualValue);
});
Note that if the user keeps clicking the "Next" button, we set the value to '0', so next to 38/38 it will show 1/38 again. The "previous" click function will be very similar.