Make content visable once Javascript variable reaches particular number - javascript

I am a bit of a javascript noob. I want to make different content appear on my page changing once a user has clicked 3 links on the page.
So I assume I want a variable which increases on every click of the link and an if statement that makes the content appear only once the variable reaches my desired number. This is what I've got so far:
<script>
var pass = 0;
function clicked() {
pass = pass + 1;
}
</script>
Then on the links:
LINK
Then on the content
<script>
if (pass > 1) {
document.write('First<br>') }
else {document.write('Second<br>') }
</script>
It isn't working and the variable always equals 0. Any ideas?

You 'content script' is only called once (when pass is still zero).
You need to check it every time when the link is clicked:
var pass = 0;
function clicked() {
pass = pass + 1;
if (pass > 1) {
document.write('First<br>');
} else {
document.write('Second<br>');
}
}

Here is an example:
var count = 1,
topics = ['Hello', 'Well...', 'Goodbye'];
function clickHandler() {
if (count >= 3) {
changeText(Math.round((Math.random() * 2)));
count = 1;
} else {
count += 1;
}
}
function changeText(idx) {
document.getElementById('content').innerHTML = topics[idx];
}
When the link is pressed 3 times you'll get random content from the list (topics).
What is changed
In the clickHandler the counter is being reset so each 3 clicks random content will be shown
I use innerHTML instead of document.write - its better practice
count is checked on each click instead of once like you check pass.
Example here.

Related

HTML/Javascript keypad function isn't working

I am making a page for a school project, and I am trying to make a keypad for a passcode system. However, I don't know how to get the keys to work. Looking it up, I have found multiple working keypads, however, I don't know what parts of their code I would have to add to my page to make it work.
The code that follows is currently what I have attached to the onclick part of each of the buttons:
<script>
function kpclick(){
var current = document.getElementById("tbInput").value;
var append = this.innerHTML;
if (current.length < 4) {
if (current=="0") {
document.getElementById("tbInput").value = append;
} else {
document.getElementById("tbInput").value += append;
}
}
}
</script>
The "tbInput" mentioned is a textbox underneath the keypad in the same div that later will be hidden and (hopefully) disabled. If there is no solution that allows the keypad to be used while the textbox is disabled, I will likely move it outside of the div the keypad is in.
When I press any of the buttons currently, nothing happens. What's happening here?
I'm assuming this is meant to be the button context. You can pass it with onclick="kpclick(this)".
function kpclick(target) {
var current = document.getElementById("tbInput").value;
var append = target.innerHTML;
if (current.length < 4) {
if (current == "0") {
document.getElementById("tbInput").value = append;
} else {
document.getElementById("tbInput").value += append;
}
}
}
<button onclick="kpclick(this)">0</button>
<button onclick="kpclick(this)">1</button>
<input id="tbInput">

I am trying to use a single button to change to class of 4 different elements one after the other with several clicks

I am trying to write some javascript to change the css of 4 different classes 1 after the other.
So I click a button for the first time i want it to change class of the first element, then a second click of the same button will change the class of a second element and then the same for the 3rd and 4th.
I have the first click changing the first element but if I add in the code with the intention for it the change the class for the second element it is changed with the first click. I've tried using separate 'if' statements and an 'else if' but it always changes all the classes together or just the first class.
FIRST TRY
With 1 count element - Even though the critcount increases to 2, with the second click it does not get access to the else part of the if statement on a second click of the button.
var critcount = 1;
$(function () {
$('#criteriasubmit').click(function () {
if (critcount = 1) {
var criteria1 = document.querySelector('.criteria1');
criteria1.classList.add('criteria1selected')
critcount++;
} else if (critcount= 2) { *//this part of the if statement is intended to work for the second
click the second click*
var criteria2 = document.querySelector('.criteria2');
criteria2.classList.add('criteria2selected')
critcount++;
}
console.log("The crit count is : " + critcount);
})
});
SECOND TRY
Separate IF statements just change the class of both elements with a single click. Even though crit2count should not increase to 2
var crit1count = 1;
var crit2count = 1;
$(function () {
$('#criteriasubmit').click(function () {
if (crit1count = 1) {
var criteria1 = document.querySelector('.criteria1');
criteria1.classList.add('criteria1selected')
crit1count++;
}
if ((crit2count= '1') && (crit1count= '2')) { //*even if I put this above the 1st if it still
actives on the first
click*
var criteria2 = document.querySelector('.criteria2');
criteria2.classList.add('criteria2selected')
crit2count++;
}
console.log("The crit1 count is : " + crit1count);
console.log("The crit2 count is : " + crit2count);
})
});
I have tried different combinations of the second if statement it always activates on the first click with the 2 separate if statement methods.
I hope this is clear and makes sense, please let me know if you think you need some more info.
Thank you in advance!

Getting Text out of HTML into Javascript as a Function with Input Changing IDs

I am trying to create an if/else statement that checks the text of a button that the user presses. If there is no text in that button, it continues the function, if there is pre-existing text then it gives an alert stating that there is already an entry there.
Essentially, the user clicks a button and the code checks to see if that button is empty or not. However, since the button's ID is constantly changing, I don't know how to tell the code to check the pressed button. I feel that using 'this' is part of the solution to this problem, but I am too new to JavaScript to use it correctly.
This is my entire JavaScript code, off it works fine except for the two lines that have comments in them. I am trying to make the variable "inSquare" to equal the text from the button that triggered the function. Then it goes on to check the text of the variable, but currently all it does is fail the if and head straight to the else.
var turnNumber = 9;
var whoseTurn;
var inSquare;
function currentTurn(id) {
inSquare = this.innerHTML; /*This Line*/
if (inSquare === "") { /*This Line*/
if (whoseTurn === 0) {
id.innerHTML = "X";
turnNumber -= 1;
whoseTurn = turnNumber % 2;
} else {
id.innerHTML = "O";
turnNumber -= 1;
whoseTurn = turnNumber % 2;
}
} else {
window.alert("Something is already in that square!");
}
}
Also, here is an example of what the HTML buttons look like. (There are nine total, but they are all formatted the same).
<button id="topLeft" onclick="currentTurn(this)"></button>
<button id="topMid" onclick="currentTurn(this)"></button>
<button id="topRight" onclick="currentTurn(this)"></button>
inSquare = this.innerHTML; should be inSquare = id.innerHTML;
this in your function refers to the window object, but you want to refer to the element you passed, which you provided as the id argument of the function.

How to count dynamically created divs

I'm trying to write a form builder where users can generate a signup form. I need to limit the amount of items that the user can create however they also need to delete the items.
Originally I had
var limit = 5;
var counter = 0;
if (counter == limit) {
However when the user deleted items the counter remained the same and so they couldnt replace the deleted form element with a new item. So what I want to do is count how many items are currently active. I tried to do this by giving each new element a class (.kid) and then counting the amount of divs with that class but it didnt work.
Could anyone point me in the right direction? This is what I have so far however it doesn't work.
var limit = 6;
var num = $('.kid').length;
function addAllInputs(divName, inputType){
if (num == limit) {
alert("You have all ready added 6 form items");
}
else {
var newdiv = document.createElement('div');
newdiv.setAttribute('id', 'child' + (counter + 1));
newdiv.setAttribute('class', 'kid' );
Cheers all!
You need to capture the current counter in a closure. Decrease the counter when the user deletes an item and increase it after an item is created. Your code sample doesn't reveal how you handle the deletion, but I'll try to illustrate what I mean with a small code snippet:
$(document).ready(function () {
var limit = 5;
var counter = $('.kid').length;
$('#triggers_delete').click(function () {
/* delete the item */
counter--;
});
$('#triggers_creation').click(function () {
if (counter == limit) {
alert('Limit reached');
return false;
}
/* somehow determine divName and inputType
and create the element */
addAllInputs(divName, inputType);
counter++;
});
});
function addAllInputs(divName, inputType) {
/* just create the item here */
}
Is there any reason an approach like this won't work? Every time you go to add a new DIV, the length of the current collection is examined to see if it meets or exceeds the limit. Of course, you may need to refine the scope of your selector if there could be other DIVs of the form with the same class ID.
var limit = 6;
function addAllInputs(divName, inputType){
if ( $('.kid').length >= limit ) {
alert("You have all ready added 6 form items");
}
else {
var newdiv = document.createElement('div');
newdiv.setAttribute('id', 'child' + (counter + 1));
newdiv.setAttribute('class', 'kid' );
}
Edit: Just a note, I am assuming that you are either removing the deleted items from the DOM or differentiating them from active items with a different class or attribute. Otherwise, the approach I suggested will return a count that includes the deleted items as well.
The only real issue is that your num variable is being defined outside of the function. It will get the number of .kid elements at the time the page loads and will not update. Simply move this line inside the function:
var limit = 6;
function addAllInputs(divName, inputType){
var num = $('.kid').length;
...
Try this
var limit = 6;
function addAllInputs(divName, inputType){
if ($('.kid').length == limit) {
alert("You have all ready added 6 form items");
}
else {
var newdiv = $('div', { 'id': 'child' + (counter + 1), 'class': 'kid' } );
$("inputContainerSelector").append(newdiv);
}

jQuery submit form IF

Hey guys,
I have this great scripts someone on stack overflow helped me out with, except the one major function I need is missing.
This is a game where the user picks a number (by entering that number in a text field) then hits a play button. After they hit the play button a series of numbers will appear, they then have to click on the number that matches their number.
The query script I'm using counts how many times they hit the number and how many times they missed the number. Take a look at the script in action here. link text
now what I need it to do, is send the score (hits and misses ) to a database after 3 misses, so I can keep high score. Any ideas? Here's the script.
var hitCount = 0,
missCount = 0;
function IsNumeric(n) {
return !isNaN(n);
}
$("#getit").click(function() {
var li = [],
intervals = 0,
n = parseInt($('#MyNumber').val());
if (IsNumeric(n)) {
setInterval(function() {
li[intervals++ % li.length].text(Math.random() > .1 ? Math.floor(Math.random() * (10 + n) + (n / 2)) : n).attr('class', '');
}, <?php echo $time ?>);
}
$('#randomnumber').empty();
for (var i = 0; i < 5; i++) {
li.push($('<li />').click(function() {
var $this = $(this);
if (!$this.hasClass('clicked')) {
if (parseInt($this.text(), 10) === n) {
$this.addClass('correct');
$('#hitcount').text(++hitCount);
} else {
$this.addClass('wrong');
$('#misscount').text(++missCount);
}
}
$this.addClass('clicked');
}).appendTo('#randomnumber'));
}
return false;
});
I've updated your problem here.
After updating the status Check for the missCount if it is greater than or equal to 3 then stop the play(clear the interval and unbind the event), then save the value using an ajax request.
I've changed the event handling to use event delegation instead of direct click event on the <li> elements. Event delegation is better in cases where there are lot of elements to which we have to bind a particular event.
I updated your fiddle with the solution. Check http://jsfiddle.net/DHPQT/2/.
I marked all the new stuff with a comment in the form of
//new ....
The main thing to do is checking after
$('#misscount').text(++missCount);
if missCount is 3 and if yes stop the game and send something

Categories

Resources