jquery skip a block - php

I have a jquery game that you can view here link text
The game starts by you entering a number in a text field.
then you click the play button.
After clicking the play button a set of square appear each rotating random numbers, click on the square that has your number to build up your score, miss 3 times and you are done.
I added the game to my site, you can view it here link text
the problem I'm having is that my site members will just keep the cursor on one box and wait for their number to appear in that one box. Which ruins the game.
Is there a way to make it so they can't click on the same box more than once in a row. They'll have to go click another box before they can come back to this one.
here's my complete script
var hitCount = 0,
missCount = 0;
function IsNumeric(n) {
return !isNaN(n);
}
$("#getit").click(function() {
var hitCount = 0,
missCount = 0;
$('#hitcount').text(0);
$('#misscount').text(0);
$('#message').hide(100);
var li = [],
intervals = 0,
n = parseInt($('#MyNumber').val());
var intervalId = -1;
if (IsNumeric(n)) {
intervalId = 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 < 7; i++) {
li.push($('<li />').appendTo('#randomnumber'));
}
$('#randomnumber').delegate("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);
}
//New code If the missCount > 3 stop the game and save the value
if(missCount>=<?php echo $limit ?>){
clearInterval(intervalId);
$('#randomnumber').undelegate("li", "click");
// Use a ajax request to save the values
$.ajax({
type : 'POST',
url : 'FBhighscore_hwnd.php',
dataType : 'json',
data: {
tgameid: $('#tgameid').val(),MyNumber: $('#MyNumber').val(),totalHits: hitCount
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
$('#loginForm').show(500);
else
$('#send').hide(500);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#loginForm').show(500);
}
});
}
}
$this.addClass('clicked');
});
return false;
});

Have you tried using .one() to bind your click events, instead of .click()? Here's the documentation for it: http://api.jquery.com/one/
If you bind the click event with .one() then you could ensure that the function will only be triggered once. Then, inside that function, rebind the events for all other boxes, thus ensuring that they have to click another box before click the same one again.
Alternately:
Use a combination of .hover() and setTimeout() (and possibly hoverIntent) to disable a box when the user hovers their mouse over it for too long.
EDIT
Have a look at this modified version of your jsFiddle: http://jsfiddle.net/Ender/9ffTA/
Clicking on the same box twice in a row is disallowed. Hopefully you can use that as a guide.

Inside of your click you can mark that box as "locked" and just disable it until the next click.

That will not solve your problem. The user can still just move to another box and wait for their number to appear in that box. I just did it myself on your site. I don't believe there is a solution to your problem with the current game design.

I don't think the problem is with clicking, but with scoring.
Your proposed solution doesn't really defeat "waiting" as a strategy, as Drew points out. To really fix waiting, you need to give it a penalty.
Were it my game, I'd have three scoring metrics — correctly clicked boxes (what you're currently calling "hits"), incorrectly clicked boxes (... "misses"), and unclicked boxes (not in your current game). In other words, if my number is 5 and a box containing a 5 fades (is replaced by another number) before I click it, that's counted against me.
With this scoring system in place, anyone who simply hovers over a box and waits — even if they switch boxes between clicks — will watch their score get lower and lower as they miss boxes.

Related

results shown twice Jquery scroll-to-load-content function, Php & mySql

I have a scroll-to-load-content function, where
//s > selector which define the number of Sql results given by results.php?selector=s
jQuery.fn.ShowResults = function(t,s){
var loading = false; //to prevents multipal ajax loads
var track_load=0;
var total_groups=t;
$("#results").load("results.php?selector="+s, {'group_no':track_load},
function() { track_load++; });
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height())
{
if(track_load <= (total_groups-1) && loading==false)
/*I think that in this line is the clue*/
{
loading = true;
$.post("results.php?selector="+s, {'group_no':track_load}, function() {
$('#results').append(data);
track_load++;
loading = false;
});
}
}
}
}
$("#results").ShowResults(8,1);
$("#show1").on("click", function(e){ $("#results").ShowResults(8,1);});
$("#show2").on("click", function(e){ $("#results").ShowResults(6,2);});
$("#show3").on("click", function(e){ $("#results").ShowResults(4,3);});
I have by default selector=1;
<a id=show1>Show 1</a>
<a id=show2>Show 2</a>
<a id=show3>Show 3</a>
<ul id=results></ul>
PHP results.php?selector=1 would be
if($_POST)
{
$data_per_group=10; //each group return 10 records as maximun
$group_number = $_POST["group_no"];
$position = ($group_number * $data_per_group);
$s=$_GET['selector'];
if($s==1){$results=mysql_query("SELECT * WHERE condition1 LIMIT $position, $data_per_group");}
if($s==2){$results=mysql_query("SELECT * WHERE condition2 LIMIT $position, $data_per_group");}
if($s==3){$results=mysql_query("SELECT * WHERE condition3 LIMIT $position, $data_per_group");}
while($res=mysql_fetch_array($results)){
$data=$res['names'];
echo "<li>$data</li>";
}
}
the problem is that sometimes, it looks like the function is called twice, and shows the same results repeated like this
<ul id=results>
<li>AAA</li>
<li>BBB</li>
<li>CCC</li>
<li>AAA</li>
<li>BBB</li>
<li>CCC</li>
</ul>
I have tried to use event.preventDefault(); and event.stopPropagation(); with no solution
The question is how do I stop this function behaviour? It looks like that anytime I click the anchors, I call twice the same function and conflicts with the set by default. I was adviced to us mysql_fetch_row() but the problem is still on. update. After testing many times, I realize That it shows twice becouse of the scroll. I need to improve this lines if(track_load <= (total_groups-1) && loading==false) or maybe anytime I click an anchor the function takes the number of groups total_groups from the default release.
Simply change track_load from 0 to 1.
The .load() request already gets the first 'track', yet the first $.post request requests track_load 0 again.
I did solve the issue, thanks to everyone who tried to help me.
the problem it was that anytime I click an anchor a, for some reason, the page still keept the prior value of total_groups.
jQuery.fn.ShowResults = function(t,s){
var total_groups=t;
setInterval( function(){alert(total_groups);},2000)
/*more coding*/
}
By default it was set selector=1 $("#results").ShowResults(8,1); .So when I clicked on a id=show2 $("#results").ShowResults(6,2);, it can be seen alerts ,setInterval(), showing different total_groups values, 8 & 6. And if I press a id=show3 $("#results").ShowResults(4,2);, the alert in one moment will display 8,6 & 4. Why this happens I still dont know.
so I decided to add $ajax({}); in order to obtain total_groups from another page total_groups.php?s=selector which returns the total_groups value only.
jQuery.fn.ShowResults = function(s){
$ajax({
type: 'POST',
url: "total_groups.php?s="+selector,
data: $(this).serialize(),
success: function(data) {
var total_groups=data; //I obtain total_groups by ajax now.
$("#results").load();
$(window).scroll(function() {
/*append data code*/
}//end load scroll
}//end success
});//end ajax
}//end function
So by using Ajax, the problem is finally solve.

Counting clicks changing link href

I asked this question but did not explain it thoroughly. I have a regular link:
Click Me
I want the change the href after the link is clicked 10 times not by the individual use but clicked 10 total times by all users.My jquery is obviously flawed but here is what i have:
var count = 0;
$(document).ready(function(){
$('a').click(function(){
count++;
if(count > 10){
$('a').attr("href","https://www.yahoo.com");
}
});
});
I am new to jQuery but from what ive read cookies and local storage store individual users information not the total websites information. So how could i use ajax with a database to do this? maybe even php?
You have a huge fundamental misunderstanding of how JavaScript works.
Firstly, when someone clicks that link, they're going to be navigated away from your page unless you do something to prevent that (e.preventDefault or return false in jQuery). Once they're navigated away, your counter is lost because is stored locally, in memory, for the life of the page.
Secondly, even if the counter wasn't cleared, or you stored the counter in a cookie, or localStorage, it will only count for a single user. If you want to count the clicks by all users, you're going to have to do that server side. i.e., in PHP.
So... how do we do that? Well, as I said before, when a user clicks that link, they're going to be sent to Google. Your site will have no knowledge of what has occurred.
We have two options to deal with this. We can intercept the click, and use AJAX (more appropriately "XHR") to send a request back to your server, where you can log the click, before forwarding them off to Google.
Or, you re-write the URL to something like /log_click.php?forward=http://google.com. Now when the user clicks the link, they will actually be sent to your log_click.php script, where you can log the click to your database, and then use $_GET['forward'] in combination with header('location: ...') to forward them off to their destination. This is the easiest solution. Through some JavaScript hackery, you can hide the link so that when they mouse over it, they won't even know they're being sent to your site (Google does this).
Once you've accumulated your 10 clicks, you again use PHP to write out a different HTML link the next time someone views that page.
HTML
<a href='http://www.google.com' data-ref='99'>Click Me</a>
Javascript
$("a").click(function() {
var _this = $(this);
var ref = $(this).data('ref');
$.ajax({
url: '/click_url.php',
type: 'POST',
data: {id:ref}
success: function(href) {
if(href != '')
_this.attr("href",href);
}
});
}
PHP (click_url.php)
if($_POST['id'] > 0){
$id = $_POST['id'];
//count increment
$sql = "UPDATE table SET count = count + 1 WHERE id = '$id'";
mysql_query($sql);
//get row count
$sql = "SELECT * FROM table WHERE id = '$id' LIMIT 1";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
//if count > 10 , return new url
if($row['count'] > 10){
die($row['href']);
}
}
While clicking the link you can call an ajax request and increment the count in the server. So that u should remove link from href and call manually by using javascript window.location.href each time. Hope that helps
var count = 0;
$(document).ready(function(){
$('a').click(function(e){
e.preventDefault();
count++;
if(count > 10){
$('a').attr("href","https://www.yahoo.com");
}
});
});
and use ajax like below
//send set state request
$.ajax({
type: "POST",
contentType: "text/xml; charset=utf-8",
datatype: "xml",// you can set json and etc
url:"your php file url",
data: {test:test1},// your data which you want to get and post
beforeSend: function (XMLHttpRequest) {
// your action
},
success: function (data, textStatus, XmlHttpRequest) {
// your action },
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
for more deatils see Ajax
Mark's answer is more useful, even you want to implement for the sake of some constraints then try below with jQuery 1.9
I have implemented for 3 clicks, AFAIU you need to change the URL on every 3rd successive click
var c=0;
$(document).on('click', 'a#ten', function(e){
c++;
alert('clicked ' + c + ' times');
if(c%3 == 0) {
$('a').attr("href","https://www.yahoo.com");
alert('changed');
c = 0;
}
e.preventDefault();
})
working DEMO
You must save no of times that link has been clicked in the database with php. when you render the link(with php) check the no of times it has been called before and decide what link to render.
Click Me
write this javascript in the page wher you place your link
$(function()
{
$('.mylink').click(function()
{
$.ajax({
type: "POST",
url: "listening/end/point", // enter your counting url here
async: false
);
});
});
And in server on the listening end point write php script to store no of times that link has been called.

Javascript duplicate ids

Hello guys J have problem at Javascript. This is the code,
function reply_click(clicked_id) {
var la = <? php echo json_encode($logOptions_id); ?> ;
var mood = clicked_id;
$.post('msg.php', {
myne: la,
mood: mood
}, function (data) {
$('#nov').html(data);
});
$('#postDiv').on('keydown', '#textarea', function (e) {
if ((e.which == 13) && !event.shiftKey) {
var textarea = $("#textarea").val();
$.post('pst.php', {
mibe: la,
voot: mood,
pst: textarea
}, function (data) {
var textarea = $("#textarea").val('');
});
}
});
}
The problem is when I clicked on item I get clicked_id, after post message, its ok, but then once again I clicking the item, I get second id, and after post enter button it post in to database difference id from first item and second, seems duplicating values, how many times I click on different items , getting different ids and this problem is spamming my DB.
Every time you click the button, you add another keydown binding to #textarea. So if you click the button 5 times, then when you press Enter the keydown binding will be run 5 times.
You should move $('#postDiv').on('keydown', '#textarea', ...) outside the function, and just do it once in the document ready handler.

How to change answer buttons after clicking on "Add" button?

I have an application [here][1] where an user is able to select their options and answers. Please follow steps below in application.
Step 1: When you open application, you will see the "Open Grid" link,
click on it and select an option type, after you select an option it
will display the answer buttons at the bottom. For example if the
option you choose is "5", it will display 5 answer buttons "A - E",
if option chose is 8, it will display 8 answer buttons "A-H".
Now this is fine. As you can see the correct amount of answer buttons appear depending on the option chosen from the grid. But the problem I have is if the user wants to add a previous option. please look at steps below:
Step 2: You will see a green plus button on left hand side, click on
it, this will open up a modal window.
Step 3: In the search box type in "AAA" and then click on "Submit"
button, it will display rows from the database.
Step 4: If you look at the first row you can see that under "Option Type" column, it is A-D. Select this row by clicking on the "Add" button.
What will happen is that the
modal window will close and if you look at the answer and option
control on the right hand side, you can see that the Option Type
textbox contains the number 4 (This is because Option Type was "A-D" so there are 4 options "A,B,C,D"), so it should display answer buttons A-D but it doesn't, it doesn't change the answer buttons at all, they remain the same.
So my question is how can I get the correct Answer buttons to appear after the user has clicked on the "Add" button?
Below is the code where it imports the answer buttons after an option is selected from the grid:
$('.gridBtns').on('click', function()
{
var clickedNumber = this.value;
$(this).closest('.option').siblings('.answer').find('.answers').each(function(index) {
if (!isNaN(clickedNumber) && index < clickedNumber) {
$(this).show();
} else {
$(this).hide();
$(this).removeClass('answerBtnsOn');
$(this).addClass('answerBtnsOff');
}
var $this = $(this);
var context = $this.parents('.optionAndAnswer');
console.log($this);
});
if (clickedNumber === 'True or False') {
$(this).closest('.option').siblings('.answer').find('input[name=answerTrueName]').show();
$(this).closest('.option').siblings('.answer').find('input[name=answerFalseName]').show();
} else if (clickedNumber === 'Yes or No') {
$(this).closest('.option').siblings('.answer').find('input[name=answerYesName]').show();
$(this).closest('.option').siblings('.answer').find('input[name=answerNoName]').show();
}
getButtons();
});
});
function getButtons()
{
var i;
if (initClick == 0) {
for (i = 65; i <= 90; i++) { // iterate over character codes for A to Z
$("#answer" + String.fromCharCode(i)).removeClass("answerBtnsOn").addClass("answerBtnsOff");
}
initClick = 1;
}
// code above makes sure all buttons start off with class answerBtnsOff, (so all button are white).
}
Below is function where it controls what happens after the "Add" button has been clicked on:
function addwindow(numberAnswer,gridValues) {
if(window.console) console.log();
if($(plusbutton_clicked).attr('id')=='mainPlusbutton') {
$('#mainNumberAnswerTxt').val(numberAnswer);
$('#mainGridTxt').val(gridValues);
} else {
$(plusbutton_clicked).closest('tr').find('input.numberAnswerTxtRow').val(numberAnswer);
$(plusbutton_clicked).closest('tr').find('input.gridTxtRow').val(gridValues);
}
$.modal.close();
return false;
}
After analyzing your above code as well as HTML source code of link you gave, looks like you are just one step behind. You are only assigning the grid value(4 in above case) to in mainGridTxt input box. You need to trigger the click event on the grid buttons.
Put the below code after $model.close
$('#btn'+gridValues).trigger('click');
Above code will trigger the click event on grid button with id 'btn4'.

Barcode reading values to textbox?

I have a barcode scanner which reads the string of the barcode and displays in the active text box. also there is no consistent end character to the barcode, or standard length (I have 5 diffent length sizes. 16,17,18,19,20). I need to extract values from scanned data. so extracting values also depend on the barcode length.
So how would I go about firing a method when the WHOLE string has been read in?
Im using php and ajax to do this.
$(document).ready(function()
{
$("#bcode").focus();
//prevents autocomplete in some browsers
$("#bcode").attr('autocomplete', 'off').keyup(function(event)
{
var name = $("#bcode").val();
$("#status").empty();
if(name.length > 17 ) `// need to check all possible length values like this`
{
selectAll();
$("#status").html('<img align="absmiddle" src="images/loading.gif" /> Checking availability...').show();
$.ajax({
type: "POST",
url: "namecheck.php",
data : "bcode=" + name,
success: function(msg)
{
$("#status").html(msg).show();
}
});
}
else
{
$("#status").html('').addClass('err').show();
}
});
});
I did some work with a card swiper, there are similar challenges there. The data comes in a rapid burst, but there isn't a consistent "end-of-data" string being sent. The solution is to use setTimeout and wait - when the input stops, then you fire your processing code.
Depending on your hardware, the amount of waiting you'll want to do varies. Experiment with this code, to adjust the wait time, simply adjust the duration argument of setTimeout. I've started it on 500ms - that works pretty well for the card swipers. Forgive me if there are any minor wobbles in my code here - I am not a jQuery guy :)
$(document).ready(function() {
$("#bcode")
.focus()
.attr('autocomplete', 'off')
.keyup(function(event){
// if the timer is set, clear it
if (barcode_watch_timer !== false)
clearTimeout(barcode_watch_timer);
// set the timer to wait 500ms for more input
barcode_watch_timer = setTimeout(function () {
process_barcode_input();
}, 500);
// optionally show a status message
//$("#status").html('waiting for more input...').show();
// return false so the form doesn't submit if the char is equal to "enter"
return false;
});
});
var barcode_watch_timer = false;
function process_barcode_input() {
// if the timer is set, clear it
if (barcode_watch_timer !== false)
clearTimeout(barcode_watch_timer);
// grab the value, lock and empty the field
var name = $("#bcode").val();
$("#bcode").attr('disabled', true);
// empty the status message
$("#status").empty();
// add a loading message
$("#status").html('<img align="absmiddle" src="images/loading.gif" /> Checking availability...').show();
// send the ajax request
$.ajax({
type: "POST",
url: "namecheck.php",
data : "bcode=" + name,
success: function(msg) {
// unlock the field, show a success status
$("#bcode").attr('disabled', false);
$("#status").html(msg).show();
}
});
}
Does it need to be a text area?
The last barcode reader I used always ended with a newline. If you are inputing into a <input type="text"/> the return char will likely try to submit the form, and you can use an onSubmit to capture the event and process your input.
Try observe the field with code by interval
Example
setInterval(function() {
var value = $("#code").val(),
prev_value = $("#code").attr("prev_value");
if (prev_value == value) {// compare with prevent value for detecting canges
console.log("value is not changed");
return;
}
//if (value.length < 17) {
//exeption
// or reset value $("#code").val(prev_value);
//return;
//}
if (value[value.length-1] == "\n") {// check last symbol
console.log(value);// Do something with you code eg send by AJAX
}
$("#code").attr("prev_value", value); // save current value for compare later
}, 1000 );

Categories