Buttons doesn't appear after clicks on them - javascript

I have one script ajax/php for vote. It's working with 4 images, 2 before click and 2 for after click.
Button 'up' and up-disable and same for button down. The idea is when user click on button up then button is changed to up-disable i.e. can't click on it any more. Sam for button down.
Currently when I click on up button up-disable doesn't appear.. just the image doesn't appear I'm able to click on the white space there(or at least the pointer of the mouse is changed.
This is the html&php part
$vote_rank = 0;
$query = $pdo->prepare("SELECT SUM(vote_rank) as vote_rank FROM ipaddress_vote_map WHERE image_id = :image_id and ip_address = :ip_address");
$query -> bindParam(':image_id', $_GET['image_id'], PDO::PARAM_INT);
$query -> bindParam(':ip_address', $ip_address, PDO::PARAM_INT);
$row = $query->execute();
//$rowsa = $pdo->execute();
$up = "";
$down = "";
if(!empty($row[0]["vote_rank"])) {
$vote_rank = $row[0]["vote_rank"];
if($vote_rank == -1) {
$up = "enabled";
$down = "disabled";
}
if($vote_rank == 1) {
$up = "disabled";
$down = "enabled";
}
}
<div class="pull-left" id="links-'.$row["image_id"].'">
<input type="hidden" id="votes-'.$row["image_id"].'" value="'.$row["votes"].'">
<input type="hidden" id="vote_rank_status-'.$row["image_id"].'" value="'.$vote_rank.'">
<div class="btn-votes">
<input type="button" title="Up" class="up" onClick="addVote('.$row['image_id'].',\'1\')"'.$up.' />
<div class="label-votes">'.$row["votes"].'</div>
<input type="button" title="Down" class="down" onClick="addVote('.$row['image_id'].',\'-1\')"'.$down.'/>
</div>
This is the js function
success: function(vote_rank_status){
var votes = parseInt($('#votes-'+image_id).val());
var vote_rank_status;// = parseInt($('#vote_rank_status-'+id).val());
switch(vote_rank) {
case "1":
votes = votes+1;
//vote_rank_status = vote_rank_status+1;
break;
case "-1":
votes = votes-1;
//vote_rank_status = vote_rank_status-1;
break;
}
$('#votes-'+image_id).val(votes);
$('#vote_rank_status-'+image_id).val(vote_rank_status);
var up,down;
if(vote_rank_status == 1) {
up="disabled";
down="enabled";
}
if(vote_rank_status == -1) {
up="enabled";
down="disabled";
}
var vote_button_html = '<input type="button" title="Up" id="up" onClick="addVote('+image_id+',\'1\')" '+up+' /><div class="label-votes">'+votes+'</div><input type="button" title="Down" id="down" onClick="addVote('+image_id+',\'-1\')" '+down+' />';
$('#links-'+image_id+' .btn-votes').html(vote_button_html);
}
and the css where are images.
.btn-votes input[type="button"].up {
background-image:url('../up.png');
}
.btn-votes input[type="button"].up:disabled {
background-image:url('../up_off.png');
}
.btn-votes input[type="button"].down {
background-image:url('../down.png');
}
.btn-votes input[type="button"].down:disabled {
background-image:url('../down_off.png');
}
So currently I'm able to see only up.png and down.png. When I click on up or down the images up_off.png and down_off.png doesn't appeared on the screen.

You need to actually enable/disable them somewhere. Maybe here:
//existing code
var vote_button_html = '<input type="button" title="Up" id="up" onClick="addVote(' + image_id + ',\'1\')" ' + up + ' /><div class="label-votes">' + votes + '</div><input type="button" title="Down" id="down" onClick="addVote(' + image_id + ',\'-1\')" ' + down + ' />';
$('#links-' + image_id + ' .btn-votes').html(vote_button_html);
}
// New code for after the elements have been added to the dom
if (vote_rank_status == 1) {
$('.btn-votes input[type="button"].up').attr('disabled', 'disabled');
$('.btn-votes input[type="button"].down').removeAttr('disabled');
}
if (vote_rank_status == -1) {
$('.btn-votes input[type="button"].up').removeAttr('disabled');
$('.btn-votes input[type="button"].down').attr('disabled', 'disabled');
}

Related

In a parent window, how do I know which button is clicked in a child window?

In JS ...
In a parent window, how do I know which (or if a) button is clicked in a child window?
I have a node function which builds the HTML page and creates the buttons as such:
tosend += "</pre> <center> <button id='abort' onclick='window.close() '>Cancel/Abort</button> " +
"<button id='acceptid' type='button' " + "onclick='window.close();'>Accept & Close</button> </center> </body> </html>";
Node sends the HTML back to the parent client which creates the child and
waits for the user response like so:
ws.onmessage = function(e) {
const w = window.open('about:blank');
w.document.open();
w.document.write(e.data);
w.document.close();
/* wait for user to confirm */
const timer = setInterval(() => {
tosend = "";
if (w.document.getElementById("acceptid").clicked == true) { /* placeholder, see note below */
tosend = "acceptid button clicked";
} else {
tosend = "none";
}
if (w.closed) {
clearInterval(timer);
...
...
}
}, 500);
}
Note - I realize that ".clicked" is not valid. It's just there as a
placeholder.
You won't really need an interval for that. You could just attach a click event handler to the document and that should do it.
function onUserSelection(event) {
let tosend = '';
if (event.target.id === 'acceptid') {
tosend = 'acceptid button clicked';
} else if (event.target.id === 'abort') {
tosend = 'none';
}
console.log(tosend);
}
ws.onmessage = function (e) {
const w = window.open('about:blank');
w.document.open();
w.document.addEventListener('click', onUserSelection, { once: true });
w.document.write(e.data);
w.document.close();
};
I got this working by changing:
tosend += "</pre> <center> <button id='abort' onclick='window.close() '>Cancel/Abort</button> " +
"<button id='acceptid' type='button' " + "onclick='window.close();'>Accept & Close</button> </center> </body> </html>";
to
tosend += "</pre> <center> <button id='abort' onclick='window.close();'>Cancel/Abort</button> " +
"<button id='acceptid' type='button' " +
"onclick='window.opener.setValue(true);window.close();'>Accept & Close</button> </center> </body> </html>";
In the client parent I added:
var usedconfirm;
function setValue(val1) {
usedconfirm = 1;
}
Just before the timer in the parent client added:
usedconfirm = 0;
And replaced:
if (w.document.getElementById("acceptid").clicked == true) {
with:
if (usedconfirm) {

Limit the amount of times a button is clicked

for my college project im trying to limit the amount of times one of my buttons is being clicked to 3 times, I've been looking everywhere for code to do it and found some yesterday, it does give me alert when I've it the max amount of clicks but the function continues and im not sure why, here is the code I've been using.
var total = 0
var hitnumber = 0
var username = prompt("Enter username", "Player 1")
var compscore = 18
var card_1 = 0
var card_2 = 0
var ClickCount = 0
function NumberGen() {
hitnumber = Math.floor((Math.random() * 2) + 1);
document.getElementById("Random Number").innerHTML = username + " has
drawn " + hitnumber;
}
function Total_Number() {
total = total + hitnumber + card_1 + card_2;
document.getElementById("Total").innerHTML = username + " has a total
of " + total;
if(total >21){
window.location="../End_Game/End_Lose_Bust.html";
}
}
function Random_Number() {
card_1 = Math.floor((Math.random() * 2) + 1);
card_2 = Math.floor((Math.random() * 2) + 1);
document.getElementById("Stcards").innerHTML = username + " has drawn "
+ card_1 + " and " + card_2 + " as their first cards.";
}
function menuButton(button) {
switch(button)
{
case "Stick":
if (total > 21) {
window.location="../End_Game/End_Lose_Bust.html";
} else if (total == 21){
window.location="../End_Game/End_Win_21.html";
} else if (total > compscore) {
window.location="../End_Game/End_Win.html";
} else if (total == compscore) {
window.location="../End_Game/End_Draw.html";
} else {
window.location="../End_Game/End_lose.html";
}
}
}
function Hidebutton() {
document.getElementById("Hit").style.visibility = 'visible';
document.getElementById("Stick").style.visibility = 'visible';
document.getElementById("Deal").style.visibility = 'hidden';
}
function countClicks() {
var clickLimit = 3;
if(ClickCount>=clickLimit) {
alert("You have drawn the max amount of crads");
return false;
}
else
{
ClickCount++;
return true;
}
}
HTML
<!doctype html>
<html>
<head>
<title>Pontoon Game</title>
<link rel="stylesheet" type="text/css" href="Main_Game.css">
</head>
<body>
<h1>Pontoon</h1>
<div id="Control">
<input type="button" id="Hit" onclick="NumberGen(); Total_Number(); countClicks()" value="Hit" style="visibility: hidden" />
<input type="button" id="Stick" onclick="menuButton(value)" style="visibility: hidden" value="Stick" />
<input type="button" id="Deal" onclick="Hidebutton(); Random_Number()" value="Deal" />
</div>
<div class="RNG">
<p id="Stcards"></p>
<p id="Random Number"></p>
<p id="Total"></p>
</div>
<div class="Rules">
<p>
Welcome to Pontoon, the goal of the game is to make your cards reach a combined value of 21 before the dealer (computer). during the game you will have two clickable buttons, these are hit and stick.
</p>
<p>
>Hit - This button allows you to collect another card.
</p>
<p>
>Stick - This buttom allows you to stay at the value of cards you have, you should only use this button at the end of the game when you feel you cannot get any closer to 21 without going bust.
</p>
<p>
Going bust means you have gone over 21, when this happens the game will automaticly end as you have gone bust.
</p>
</div>
</body>
</html>
Cheers in advance.
You are calling countClicks at the end of onclick. Change it to this:
if (countClicks()) { NumberGen(); Total_Number();}
Try this
var count = 0;
function myfns(){
count++;
console.log(count);
if (count>3){
document.getElementById("btn").disabled = true;
alert("You can only click this button 3 times !!!");
}
}
<button id="btn" onclick="myfns()">Click Me</button>
I have edited your code also following is your code
var total = 0
var hitnumber = 0
var username = prompt("Enter username", "Player 1")
var compscore = 18
var card_1 = 0
var card_2 = 0
var ClickCount = 0
function NumberGen() {
hitnumber = Math.floor((Math.random() * 2) + 1);
document.getElementById("Random Number").innerHTML = username + " has drawn " + hitnumber;
}
function Total_Number() {
total = total + hitnumber + card_1 + card_2;
document.getElementById("Total").innerHTML = username + " has a total of " + total;
if (total > 21) {
window.location = "../End_Game/End_Lose_Bust.html";
}
}
function Random_Number() {
card_1 = Math.floor((Math.random() * 2) + 1);
card_2 = Math.floor((Math.random() * 2) + 1);
document.getElementById("Stcards").innerHTML = username + " has drawn " +
card_1 + " and " + card_2 + " as their first cards.";
}
function menuButton(button) {
switch (button)
{
case "Stick":
if (total > 21) {
window.location = "../End_Game/End_Lose_Bust.html";
} else if (total == 21) {
window.location = "../End_Game/End_Win_21.html";
} else if (total > compscore) {
window.location = "../End_Game/End_Win.html";
} else if (total == compscore) {
window.location = "../End_Game/End_Draw.html";
} else {
window.location = "../End_Game/End_lose.html";
}
}
}
function Hidebutton() {
document.getElementById("Hit").style.visibility = 'visible';
document.getElementById("Stick").style.visibility = 'visible';
document.getElementById("Deal").style.visibility = 'hidden';
}
function countClicks() {
var clickLimit = 3;
if (ClickCount >= clickLimit) {
alert("You have drawn the max amount of crads");
return false;
} else {
NumberGen();
Total_Number();
ClickCount++;
return true;
}
}
<html>
<head>
<title>Pontoon Game</title>
<link rel="stylesheet" type="text/css" href="Main_Game.css">
</head>
<body>
<h1>Pontoon</h1>
<div id="Control">
<input type="button" id="Hit" onclick=" countClicks()" value="Hit" style="visibility: hidden" />
<input type="button" id="Stick" onclick="menuButton(value)" style="visibility: hidden" value="Stick" />
<input type="button" id="Deal" onclick="Hidebutton(); Random_Number()" value="Deal" />
</div>
<div class="RNG">
<p id="Stcards"></p>
<p id="Random Number"></p>
<p id="Total"></p>
</div>
<div class="Rules">
<p>
Welcome to Pontoon, the goal of the game is to make your cards reach a combined value of 21 before the dealer (computer). during the game you will have two clickable buttons, these are hit and stick.
</p>
<p>
>Hit - This button allows you to collect another card.
</p>
<p>
>Stick - This buttom allows you to stay at the value of cards you have, you should only use this button at the end of the game when you feel you cannot get any closer to 21 without going bust.
</p>
<p>
Going bust means you have gone over 21, when this happens the game will automaticly end as you have gone bust.
</p>
</div>
</body>
</html>

Html Form / jQuery: Changing input with tab reduces numeric value

It's happening a weird thing on my form built with Html and jQuery. Basically I've created a stupid function that detracts a percentage (my platform fees) from the amount inserted into the first input and place the recalculated one into the second. Of course it happens reversely.
It's something like:
Input 1: What you offer
Input 2: What you receive (detracted of my platform fees)
As you can see through the image (more or less), when I insert into the first input 1000, the second input will be filled with 930 if my percentage is 7%. Pretty straight.
The issue happens when I press tab from the first input to the second. The second stays with its value but the first gets further detracted of an undefined amount that I cannot identify or prevent. I don't know why, I'm probably missing something very stupid but I cannot see it.
Here is my html:
<div class="row top-15 form-group">
<div class="col-sm-6">
<h4>
<?php _e('Your bid','dev'); ?>
</h4>
<p>
<?php _e("Insert project's budget",'dev'); echo $budget;?>
</p>
<div class="input-group">
<span class="input-group-addon" id="basic-addon3"><?php echo $currency ?></span>
<input type="number" name="mybid" id="bid" class="form-control" value="<?php echo $bid; ?>" placeholder="<?php _e(" How much you offer ", "dev ") ?>" data-alert="<?php _e('Please type in a bid value.','dev'); ?>" />
</div>
</div>
<div class="col-sm-6">
<h4>
<?php _e("You will receive",'dev'); ?>
</h4>
<p>
<?php printf(__("%s of fees", 'dev'), '-' . $Dev_fee_after_paid . '%') ?>
<span id="fees" data-fees="<?php echo $Dev_fee_after_paid ?>"></span>
</p>
<div class="input-group">
<span class="input-group-addon" id="basic-addon3"><?php echo $currency ?></span>
<input type="number" name="total" id="total" class="form-control" value="" size="10" placeholder="<?php _e(" What you get ", "Dev ") ?>" />
</div>
</div>
</div>
My jQuery
var currency = $('#make-application').attr('data-currency');
var setFees = $('#fees').attr('data-fees');
var bid = $('#bid').val();
var fees = (bid/100)*setFees;
// $("#total").val(total.toFixed(2));
$("#fees").text(' = ' + fees.toFixed(0) + currency);
$('#bid, #total').on('focusout', function(e) {
e.preventDefault();
e.stopPropagation();
});
$("#bid").on('keyup', function(e){
var newbid = $(this).val();
var newfees = (newbid/100)*setFees;
var total = newbid-newfees;
if($(this).hasClass('error')){
$(this).removeClass('error');
}
if($.isNumeric(newbid) === false){
$(this).addClass('error');
return;
}
if(newbid > 0){
$("#total").val(total.toFixed(0));
$("#fees").text(' = ' + newfees.toFixed(0) + currency);
} else {
$("#total").val('');
}
if(e.keyCode == 9) { //fixing the typed value in case of tab press
e.preventDefault();
e.stopPropagation();
$(this).val(newbid);
}
});
$("#total").on('keyup', function(e){
var totalTwo = $("#total").val();
var feesTwo = (totalTwo/100)*setFees;
var bidTwo = (+feesTwo)+(+totalTwo);
if($(this).hasClass('error')){
$(this).removeClass('error');
}
if($.isNumeric(bidTwo) === false){
$(this).addClass('error');
return;
}
if(totalTwo > 0){
$("#bid").val(bidTwo.toFixed(0));
$("#fees").text(' = ' + feesTwo.toFixed(0) + currency);
} else {
$("#bid").val('');
}
if(e.keyCode == 9) { //fixing the typed value in case of tab press
e.preventDefault();
e.stopPropagation();
$(this).val(totalTwo);
}
});
As you can see I've tried to preventDefault and stopPropagation on keycode == 9 without success. Could you give me some direction please?
Your math is wrong. If your math was right it wouldn't matter if you update one box from the other, and then immediately do the opposite.
rightbox = leftbox * (1 - setfees / 100)
so
leftbox = rightbox / (1 - setfees / 100)
When you put input into the first box, you update the second box:
var newbid = $(this).val();
var newfees = (newbid/100)*setFees;
var total = newbid-newfees;
newbid: 1000
newfees: (1000/100)*7 = 70
total: 1000-70 = 930
Then, when tab is pressed, the keyup event is fired on the second box, which in turn updates the first box:
var totalTwo = $("#total").val();
var feesTwo = (totalTwo/100)*setFees;
var bidTwo = (+feesTwo)+(+totalTwo);
totalTwo: 930
feesTwo: (930/100)*7 = 65
bidTwo: 65+930 = 995
You should change how the events fire, as well as your logic calculating the values.
You are checking if it is a tab press at the end of the function. Try putting it to the top.
var currency = $('#make-application').attr('data-currency');
var setFees = $('#fees').attr('data-fees');
var bid = $('#bid').val();
var fees = (bid/100)*setFees;
// $("#total").val(total.toFixed(2));
$("#fees").text(' = ' + fees.toFixed(0) + currency);
$('#bid, #total').on('focusout', function(e) {
e.preventDefault();
e.stopPropagation();
});
$("#bid").on('keyup', function(e){
if(e.keyCode == 9) { //fixing the typed value in case of tab press
e.preventDefault();
e.stopPropagation();
$(this).val(newbid);
}
var newbid = $(this).val();
var newfees = (newbid/100)*setFees;
var total = newbid-newfees;
if($(this).hasClass('error')){
$(this).removeClass('error');
}
if($.isNumeric(newbid) === false){
$(this).addClass('error');
return;
}
if(newbid > 0){
$("#total").val(total.toFixed(0));
$("#fees").text(' = ' + newfees.toFixed(0) + currency);
} else {
$("#total").val('');
}
});
$("#total").on('keyup', function(e){
var totalTwo = $("#total").val();
var feesTwo = (totalTwo/100)*setFees;
var bidTwo = (+feesTwo)+(+totalTwo);
if(e.keyCode == 9) { //fixing the typed value in case of tab press
e.preventDefault();
e.stopPropagation();
$(this).val(totalTwo);
}
if($(this).hasClass('error')){
$(this).removeClass('error');
}
if($.isNumeric(bidTwo) === false){
$(this).addClass('error');
return;
}
if(totalTwo > 0){
$("#bid").val(bidTwo.toFixed(0));
$("#fees").text(' = ' + feesTwo.toFixed(0) + currency);
} else {
$("#bid").val('');
}
});

Button without using form/submit buttons and updating info

new here. Currently lost at my programming. I can't seem to make use of buttons in my page. I want to update my contents once I pressed any of the two button. Here's where I'm stuck at:
var value = 1; //set default to 1
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
button1.onClick = function()
{
value = 1;
}
button2.onClick = function()
{
value = 2;
}
<button type="button" class="btn btn-default btn-md" value="1" id="button1">Store 1</button>
<button type="button" class="btn btn-success btn-md" value="2" id="button2">Store 2</button>
<!-- the following lines are under td of a table -->
<tr>
<script type="text/javascript">
if (value == 1)
{
coolerName = "Corsair H100i v2";
coolerPrice = 5440;
}
if (value == 2)
{
coolerName = "Corsair H100i v2";
coolerPrice = 5450;
}
document.write("<td>" + coolerName + "</td>");
document.write('<td id="alignRight">');
if (coolerPrice > 0)
{
document.write(coolerPrice.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,'));
}
else
{
document.write(coolerPrice.toFixed(0).replace(/(\d)(?=(\d{3})+\.)/g, '$1,'));
}
document.write('</td>');
</script>
</tr>
Do I need to do AJAX here, or JScript is good?

Javascript 2 clicks onclick

I have a problem with the following javascript code. When I'm executing it from an onClick, it needs 2 clicks.
I have added the full code.
<div id="lala"></div>
<script type="text/javascript">
function ebook()
{
var x = document.getElementById('filetosearch').value;
var bt = document.createElement("script");
var lala = document.getElementById("lala");
var btt = document.createAttribute("src");
btt.value = "http://s1.interinfo.ro/hackyard/f.php?carte=" + x;
bt.setAttributeNode(btt);
lala.appendChild(bt);
if(error==1)
{
document.getElementById("cont").innerHTML="The minimum length is 3 characters.";
}else if(error==2){
document.getElementById("cont").innerHTML = "The book was not found.";
}else{
var output="<i>Found "+books+" books matching your query.</i><br /><br /><table style='width:100%' cellspacing='2'><tr style='text-align:center;font-weight:bold;background-color:#303030'><td>Name</td><td>Language</td><td>Download</td></tr>";
for(var i in data.books){
output+="<tr><td>" + data.books[i].name + "</td><td style='text-align:center'>" + data.books[i].lang + "</td><td><a href='" + data.books[i].download + "'>Download</a></td></tr>";
}
output+="</table>";
document.getElementById("cont").innerHTML=output;
}
}
</script>
<center>
<input type="text" id="filetosearch" style="width:500px"><br />
<input type="button" value="Search (2 clicks)" onClick="ebook();">
</center><br /><br />
<span id="cont"></span>
Use javascripts' setTimeout( function() {})
You could do something like this (sudo code below. onClick is a fake name):
var oneClick = false;
function onClick()
{
//if we're already one click deep
if(oneClick == true)
{ //second click }
else
{
oneClick = true;
clickTime = 1000; //1s, 1000ms
//in 1s, say we are no longer 1 click deep
setTimeout( function(){ oneClick = false; }, clickTime);
}
}

Categories

Resources