Button without using form/submit buttons and updating info - javascript

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?

Related

I have ten buttons I want when I press a button all buttons stop

I have ten buttons I want when I press a button all the other buttons stop
You did it and it worked, but if you do a reload, you can press another button. I want to prevent the user from pressing another button than the one he pressed.
html
<button class="button" id="movetool" onclick="movetool()">click 1</button>
<button class="button" id="movetool2" onclick="movetool2()">click 2</button>
<button class="button" id="movetool3" onclick="movetool3()">click 3</button>
<button class="button" id="movetool4" onclick="movetool4()">click 4</button>
<button class="button" id="movetool5" onclick="movetool5()">click 5</button>
<button class="button" id="movetool6" onclick="movetool6()">click 6</button>
<button class="button" id="movetool7" onclick="movetool7()">click 7</button>
<button class="button" id="movetool8" onclick="movetool8()">click 8</button>
<button class="button" id="movetool9" onclick="movetool9()">click 9</button>
<button class="button" id="movetool10" onclick="movetool10()">click 10</button>
javascript
var clickCounter10 = window.localStorage.getItem('clickCounter10') || 0;
var movetool10 = document.getElementById('movetool10');
var man10 = 10;
changeBtn10();
movetool10.onclick = function() {
clickCounter10++;
window.localStorage.setItem('clickCounter10', clickCounter10);
changeBtn10();
};
function changeBtn10() {
clickCounter10 = parseInt(clickCounter10, 10);
if (clickCounter10 === 2) {
clickCounter10 = 0;
document.getElementById('movetool10').innerHTML = 'ok 1';
document.getElementById("man10").innerHTML = man10;
document.getElementById("movetool").disabled = false;
document.getElementById("movetool2").disabled = false;
document.getElementById("movetool3").disabled = false;
document.getElementById("movetool4").disabled = false;
document.getElementById("movetool5").disabled = false;
document.getElementById("movetool6").disabled = false;
document.getElementById("movetool7").disabled = false;
document.getElementById("movetool8").disabled = false;
document.getElementById("movetool9").disabled = false;
} else if(clickCounter10 !== 0) {
document.getElementById('movetool10').innerHTML = 'no ok 1';
document.getElementById("man10").innerHTML = man10 - 1;
document.getElementById("movetool").disabled = true;
document.getElementById("movetool2").disabled = true;
document.getElementById("movetool3").disabled = true;
document.getElementById("movetool4").disabled = true;
document.getElementById("movetool5").disabled = true;
document.getElementById("movetool6").disabled = true;
document.getElementById("movetool7").disabled = true;
document.getElementById("movetool8").disabled = true;
document.getElementById("movetool9").disabled = true;
}
}
EDIT: I've added some comments so you can read about it. Made it all if-else conditions.
Remove all your inline HTML event attributes. That's highly unmanageable. Imagine creating a function and an action handler per button. It could get messy. Use delegation:
JavaScript event delegation is a simple technique by which you add a
single event handler to a parent element in order to avoid having to
add event handlers to multiple child elements
You can achieve this with these few lines of code:
//get the active button
var activeButton = localStorage.getItem('activeButton');
var isActive = localStorage.getItem('isActive');
//get all the button
const allButtons = document.querySelectorAll(".button");
[...allButtons].forEach(function(thisButton) {
/*
If isActive equals true,
set thisButton disabled to true if activeButton is not equal to thisButton's id
*/
if (isActive === 'true') {
if (activeButton !== thisButton.id) {
thisButton.disabled = true;
}
}
});
const movetool = event => {
/*get current activeButton*/
activeButton = localStorage.getItem('activeButton');
/*
get the closest button on call
*/
const target = event.target.closest("button");
/*
diables all buttons
*/
/*if active button is equal to target.id*/
if (activeButton === target.id) {
var enableAll = false;
/*get the array from all the buttons*/
Array.from(allButtons).forEach(function(thisButton) {
if (thisButton.disabled) {
enableAll = true;
return;
}
});
if (enableAll) {
/*get the array from all the buttons*/
Array.from(allButtons).forEach(function(thisButton) {
thisButton.disabled = false;
});
localStorage.setItem('isActive', false);
} else {
Array.from(allButtons).forEach(function(thisButton) {
thisButton.disabled = true;
});
if (target.classList.contains("button")) {
/*
sets disable to false on the closest button
}
*/
target.disabled = false;
/*
sets local storage new activeButton to the closest button's id
*/
localStorage.setItem('isActive', true);
localStorage.setItem('activeButton', target.id);
}
}
} else {
Array.from(allButtons).forEach(function(thisButton) {
thisButton.disabled = true;
});
if (target.classList.contains("button")) {
/*
sets disable to false on the closest button
}
*/
target.disabled = false;
/*
sets local storage new activeButton to the closest button's id
*/
localStorage.setItem('isActive', true);
localStorage.setItem('activeButton', target.id);
}
}
}
/*
a single event listener
*/
document.querySelector('.button_container').addEventListener('click', movetool);
<!-- wrap all buttons in a container to remove the event handlers -->
<div class="button_container">
<button class="button" id="movetool">click 1</button>
<button class="button" id="movetool2">click 2</button>
<button class="button" id="movetool3">click 3</button>
<button class="button" id="movetool4">click 4</button>
<button class="button" id="movetool5">click 5</button>
<button class="button" id="movetool6">click 6</button>
<button class="button" id="movetool7">click 7</button>
<button class="button" id="movetool8">click 8</button>
<button class="button" id="movetool9">click 9</button>
<button class="button" id="movetool10">click 10</button>
</div>
just pre disable all buttons
if clickCounter10 != 0 or whatever you want
you can use querySelectorAll to do it all at once
var clickCounter10 = window.localStorage.getItem('clickCounter10') || 0,
movetool10 = document.getElementById('movetool10'),
man10 = 10,
all_button = document.querySelectorAll(`button[id^="movetool"]`);
clickCounter10 = parseInt(clickCounter10, 10);
// pre disable all buttons if clickCounter10 != 0
all_button.forEach(button => {
if (clickCounter10 != 0) {
button.disabled = true;
} else {
button.disabled = false;
}
});
// short version
all_button.forEach(button => button.disabled = (clickCounter10 != 0) ? true : false);
changeBtn10();
movetool10.onclick = function () {
clickCounter10++;
window.localStorage.setItem('clickCounter10', clickCounter10);
changeBtn10();
};
function changeBtn10() {
if (clickCounter10 === 2) {
clickCounter10 = 0;
document.getElementById('movetool10').innerHTML = 'ok 1';
document.getElementById("man10").innerHTML = man10;
all_button.forEach(button => button.disabled = false);
} else if (clickCounter10 !== 0) {
document.getElementById('movetool10').innerHTML = 'no ok 1';
document.getElementById("man10").innerHTML = man10 - 1;
all_button.forEach(button => button.disabled = true);
}
}

use location.hash to keep page status in javascript

I am doing a practice that use location.hash to keep page's state, what i have done using the below code is
1.click any button, the button's innerHTML will be written into the div#cont
2.refresh the page, it keeps the changes in the div#cont
<body>
<button id="a">A</button>
<button id="b">B</button>
<button id="c">C</button>
<div id="cont"></div>
<script>
// var hashValue;
function getHash() {
var hashValue = location.hash;
return hashValue;
}
function draw() {
var cont = getHash();
if (cont) {
document.getElementById('cont').innerHTML = cont.slice(1);
}
}
btns = document.getElementsByTagName('button');
for (i = 0; i < btns.length; i++) {
btns[i].index = i;
btns[i].onclick = function() {
location.hash = btns[this.index].innerHTML;
}
}
window.onhashchange = function() {
draw();
}
draw();
</script>
</body>
And what i want to achieve next is add three other buttons(D,E,F) and a new div, when clicking one of the D\E\F, the innerHTMl will written into the new div.
The final goal is
click one of the A\B\C, the value will be written into 'contABC'
click one of the D\E\F, the value will be written into 'contDEF'
keep the changes when the page refresh
because this time it has to record two value, and i have no idea how to use hash to do that, anyone can help? Thanks in advance!
This is HTML:
<button id="a">A</button>
<button id="b">B</button>
<button id="c">C</button>
<button id="d">D</button>
<button id="e">E</button>
<button id="f">F</button>
<div id="contABC"></div>
<div id="contDEF"></div>
Try by structuring the way you store the hash value , like using a separator -
<body>
<button data-attr='ABC' id="a">A</button>
<button data-attr='ABC' id="b">B</button>
<button data-attr='ABC' id="c">C</button>
<button data-attr='DEF' id="d">D</button>
<button data-attr='DEF' id="e">E</button>
<button data-attr='DEF' id="f">F</button>
<div id="contABC"></div>
<div id="contDEF"></div>
<script>
// var hashValue;
function getHash() {
var hashValue = location.hash && location.hash.slice(1);
return hashValue && hashValue.split('-');
}
function draw() {
var cont = getHash();
if (cont && cont.length>0) {
document.getElementById('contABC').innerHTML = cont[0];
document.getElementById('contDEF').innerHTML = cont[1];
}
}
btns = document.getElementsByTagName('button');
var seperator = '-';
for (i = 0; i < btns.length; i++) {
btns[i].index = i;
btns[i].onclick = function() {
var cont = getHash() || [];
if(btns[this.index].dataset.attr=='ABC'){
location.hash = btns[this.index].innerHTML + seperator + cont[1];
}else{
location.hash = cont[0] + seperator + btns[this.index].innerHTML ;
}
}
}
window.onhashchange = function() {
draw();
}
draw();
</script>
</body>

Count on click button1 and recount if on click button2

I have two buttons and a counter, I have to reset counter every time I change the button. I don't know how to reset the counter.
var count = 0;
var button1 = document.getElementById("Button1");
var button2 = document.getElementById("Button2");
var display = document.getElementById("displayCount");
function clickCount(){
count++;
display.innerHTML = count;
}
button1.onclick = function(){
clickCount();
count=0;
}
button2.onclick = function(){
clickCount();
}
<input type="button" value="button1" id="Button1" />
<input type="button" value="button2" id="Button2" />
<p>Clicks: <span id="displayCount">0</span> times.</p>
Pass a parameter to your clickCount function with the button name, and check if it has changed.
var count = 0;
var lastButtonClicked = "";
var button1 = document.getElementById("Button1");
var button2 = document.getElementById("Button2");
var display = document.getElementById("displayCount");
function clickCount(buttonName){
if (buttonName === lastButtonClicked)
{
count++;
}
else
{
count = 1;
lastButtonClicked = buttonName;
}
display.innerHTML = count;
}
button1.onclick = function(){
clickCount("1");
}
button2.onclick = function(){
clickCount("2");
}
<input type="button" value="button1" id="Button1" />
<input type="button" value="button2" id="Button2" />
<p>Clicks: <span id="displayCount">0</span> times.</p>
Just add the extra parameter that determines which button the counter is from.
var isFirstButton = true;
var count = 0;
var button1 = document.getElementById("Button1");
var button2 = document.getElementById("Button2");
var display = document.getElementById("displayCount");
function clickCount(){
count++;
display.innerHTML = count;
}
button1.onclick = function(){
if (!isFirstButton){
count = 0;
}
isFirstButton = true;
clickCount();
}
button2.onclick = function(){
if (isFirstButton){
count = 0;
}
isFirstButton = false;
clickCount();
}
I updated your original code, added a active button variable which is chosen from the event target, this way, it doesn't matter how many buttons you want to count, they will all be unique, and you don't need a variable for each one.
This is similar to [stephen.vakil] post, however with this code, you do not need to name the buttons, just use the DOM and event target to define the uniqueness.
var count = 0;
var button1 = document.getElementById("Button1");
var button2 = document.getElementById("Button2");
var display = document.getElementById("displayCount");
var activeTarget; // which target are we counting
function clickCount(e){
var e = e || window.event; // IE or other browser event
var target = e.target || e.srcElement; // target from different browsers
if(target != activeTarget) { // Is this the current target?
count = 0; // No, reset counter
activeTarget = target; // and make it the active target
}
count++; // No matter which target, incr counter
display.innerHTML = count; // and display result
}
button1.onclick = function(e) { // don't forget the event arg
clickCount(e); // and pass it to the count function
}
button2.onclick = function(e) { // same as above
clickCount(e);
}
<input type="button" value="button1" id="Button1" />
<input type="button" value="button2" id="Button2" />
<p>Clicks: <span id="displayCount">0</span> times.</p>
The reference for the source event target onclick calling object

change the load() text based on variable?

In the following script, all I need to do is change the integer before the .php in each of the .load() functions.
That is, as bio_id is either incremented or decremented, the filename 1.php will increment or decrement with bio_id. I'm not sure how to do that.
<script>
$("#bio").load("assets/includes/bios/1.php");
</script>
<div class="btn-group" role="group">
<button id="prev" type="button" class="btn btn-default disabled" onclick="prevBio()">Previous</button>
<button id="next" type="button" class="btn btn-default" onclick="nextBio()">Next</button>
</div>
<script>
/* bio id number */
var bio_id = 1;
var new_bio = 1;
function nextBio() {
bio_id++;
new_bio = bio_id;
console.log(bio_id);
$('#bio').load("assets/includes/bios/2.php");
if (new_bio > 1 && bio_id < 12) {
$('#prev').removeClass('disabled');
$('#next').removeClass('disabled');
}
else if (new_bio == 12) {
$('#next').addClass('disabled');
}
return bio_id;
}
function prevBio() {
bio_id--;
new_bio = bio_id;
console.log(bio_id);
$('#bio').load("assets/includes/bios/2.php");
if(new_bio == 1) {
$('#prev').addClass('disabled');
}
else if (new_bio > 1 && bio_id < 12) {
$('#prev').removeClass('disabled');
$('#next').removeClass('disabled');
}
else if (new_bio == 12) {
$('#next').addClass('disabled');
}
return bio_id;
}
</script>
What's great about javascript is that the typing is so loose, so you can just do something like this to concatenate your strings:
bio_id=12;
alert('hello' + bio_id);
Yes, in your case it would be:
$('#bio').load("assets/includes/bios/" + bio_id + ".php");

Buttons doesn't appear after clicks on them

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');
}

Categories

Resources