Rotate button settings and values on each click, repeating - javascript

I am trying to display a button, starting with "unmarked". As the user clicks the button, I need it to change to the next button, "form". When each of these clicks happen, I would like a post request made through ajax to update the value in the database associated with the ID of the button. This ID comes from the database where other information is being shown next to the button. I believe that part is done with an onclick=functionname(123456) event? When the user reaches the end (completed), another click simply starts it over at unmarked.
I've been searching stackoverflow for hours however have not been able to find anything related to what I am trying to do and very new to jquery/ajax/javascript
<button type="button" name="Unmarked" value="0" class="btn btn-default"/>Unmarked</button>
<button type="button" name="Form" value="1" class="btn btn-info"/>Form</button>
<button type="button" name="Frame" value="2" class="btn btn-primary"/>Frame</button>
<button type="button" name="S/NB" value="3" class="btn btn-warning"/>S/NB</button>
<button type="button" name="S/B" value="4" class="btn btn-danger"/>S/B</button>
<button type="button" name="Completed" value="5" class="btn btn-success"/>Completed</button>
I'm hoping someone can at least point me in the right direction.

Based on your comment...
We have an array of the item id's that you want to iterate through.
var buttonArray = ["unmarked", "form", "frame", "snb", "sb", "completed"];
We keep track of which items is currently visible
var currentItemIndex = 0;
Finally we will call the function to change visibility on every button click.
function changeButtonVisibility() {
var buttonClicked = $("#" + buttonArray[currentItemIndex]);
var nextItemIndex = 0;
if(currentItemIndex + 1 > buttonArray.length - 1) {
nextItemIndex = 0;
} else {
nextItemIndex = currentItemIndex + 1;
}
var nextButton = $("#" + buttonArray[nextItemIndex]);
currentItemIndex = nextItemIndex;
buttonClicked.addClass("hidden");
nextButton.removeClass("hidden");
}
Essentially you take the current button, add the class hidden, take the next button, remove the class hidden. The if statement ensures that if you hit the last item, you start over again with the first item.
Lastly, bind the function as a click event to your buttons.
$("#unmarked").click(function() {
changeButtonVisibility();
});
$("#form").click(function() {
...
Depending on your specific use case, you could probably come up with a more elegant way to solve this. Also you can definitely eliminate some lines of code. However, I hope the example gives you a good starting point or idea on how to tackle the problem.
Working example: jsbin.com/xeyejesaxe

Related

Javascript - Click multiple elements with class or id when clicking a different button

I want to click one button that clicks other buttons at the same time or with a delay between each one. These additional buttons share the same class and their id's start with the same nomenclature. I know I can accomplish this easily with jQuery, but I want to make it work with Vanilla Javascript.
I tried using the querySelector, but this only triggers the first element.
Also, I found another solution that sets a Timeout for each button, the problem is that this gets triggered when the window loads and I need it to work when I click the other button.
This is my html code:
<div>
<button class="bundle-product-button" id="button1" onClick="alert('click button1');">Button 1</button>
<button class="bundle-product-button" id="button2" onClick="alert('click button2');">Button 2</button>
<button class="bundle-product-button" id="button3" onClick="alert('click button3');">Button 3</button>
</div>
<button class="add-bundle-to-cart">Trigger</button>
This only triggers the first button:
function testOne() {
document.querySelector(".bundle-product-button").click();
}
document.querySelector(".add-bundle-to-cart").onclick = testOne;
And this triggers when the window loads:
var clickcallback = function(i) {
setTimeout(function() {
let id = "button" + i;
document.getElementById(id).click();
}, 1000); // one second
if(i <= 3) {
clickcallback(i+1);
}
};
clickcallback(1);
I know this might be simple but how can I trigger multiple clicks when clicking one element.
querySelector only match the first element, you have to use querySelectorAll and then for each
function testOne() {
document.querySelectorAll(".bundle-product-button").forEach(function(el) {
el.click();
});
}
document.querySelector(".add-bundle-to-cart").onclick = testOne;

How to make two counters buttons independent of each other in jquery?

Actually I was struggling in making 'like' buttons which on clicking increases or decreases the count whenever clicked and the problem I am facing is ,the interference of one button on other buttons.Here is my html code for one button:
<button class="btn btn-default buttonattr"style="font-family:Pangolin" onclick="myhit1(\''+this["post"]+'\',\''+this["id"]+'\',\''+this["love"]+'\');myclick()">
<span class="glyphicon glyphicon-heart fa-lg active1"></span> Love
</button>;
where myhit() and myclick()are javascript functions, called on clicking this button . Here is my javascript functions:
var toAdd=1;var newValue=0;
var overall=1;var pvalue=0;
function myhit(post,id,love){
oldValue=parseInt(love);
if(toAdd>0){
newValue=oldValue+toAdd;
}
else{
newValue= overall + toAdd;
}
pvalue=pvalue+toAdd;
toAdd*=-1;
overall=newValue;
$.post('porthome4_.php',{post1:post,id1:id,love:newValue,plove:pvalue},function(info){});
}
I have made more 'like' buttons for each post. The problem is for eg. if I click on one button and the counter is increased from 0->1 state ,but if click on another button its state change is absurd , and I know is the reason is toAdd variable state change from +1 to -1 because its state change for every click on button ,,it would have worked fine if there would have been only 1 button but
for multiple buttons this wont work...Can someone suggest me better way to tackle this or a change in my function code would be much more appreciated . Would be glad if someone helps.Thank u
<button class="btn btn-default buttonattr"style="font-family:Pangolin" data-state="1" onclick="myhit1(\''+this["post"]+'\',\''+this["id"]+'\',\''+this["love"]+'\');myclick()">
<span class="glyphicon glyphicon-heart fa-lg active1"></span> Love
</button>
var newValue=0;
var overall=1;
var pvalue=0;
function myhit(post,id,love)
{
oldValue = parseInt(love);
var toAdd = parseInt($(this).attr("data-state"));
if(toAdd>0)
{
newValue=oldValue+toAdd;
}
else
{
newValue= overall + toAdd;
}
pvalue=pvalue+toAdd;
toAdd*=-1;
overall=newValue;
$(this).attr("data-state",toAdd);
$.post('porthome4_.php',{post1:post,id1:id,love:newValue,plove:pvalue},function(info){});
}
You can used separate state variable for each button. Set data-state attribute to button and after that you can used this attribute to function $(this).data("data-state"); you can get and set this value each time whne button click.

Javascript/jQuery disable buttons by classname

I have a complex Javascript app which populates a button depending on the app state and readonly permissions:
But essentially the button looks like this when it is added to the document:
<button type="button" id="..." class="btn btn-link btn-table-action btn-table-add-row" title="Add"></button>
The id is auto generated and is not known before hand. Besides we have several of these buttons, that all need to be disabled/enabled simultaneously.
I tried the following with no luck:
$(".btn-table-add-row").prop('disabled', true);
setInterval(function() {
$(".btn-table-add-row").prop('disabled', true);
}, 1000);
var elems = document.getElementsByClassName("btn-table-add-row");
console.log(elems);
for(var i = 0; i < elems.length; i++) {
elems[i].disabled = true;
}
The above examples were all tried on page load, after the document has loaded and the buttons are visible. I am able to read the elems list in the last example, but they will not disable. Any suggestions?
I created a fiddle http://jsfiddle.net/mfleshman/yR9U3/
<button type="button" class="btn btn-link btn-table-action btn-table-add-row" title="Add">test</button>
<button type="button" class="btn btn-link btn-table-action btn-table-add-hide" title="Add">test</button>
$(".btn-table-add-row").prop('disabled', true);
$(".btn-table-add-hide").hide();
You stated the buttons are "visible". Disabling a button will not hide it from the page unless you have additional CSS selectors doing this.
If you are trying to hide the buttons you need to call .hide() on the element.
As Satpal and yourself have mentioned, the code is correct (at least the first sentence i tried), so the problem will be either in the order in which the buttons are created, or maybe in an error during the execution of other JS code that causes yours to not run.
I also created a fiddle for this and your code is working: http://jsfiddle.net/gx7zC/
$(document).ready(function(){
var btnAmount = Math.floor((Math.random() * 10) + 1);
for(var i=0; i<btnAmount;i++){
var newButton = document.createElement("button");
$(newButton).addClass("btn btn-link btn-table-action btn-table-add-row");
newButton.id = "btn"+i;
$(newButton).text("btn"+i);
document.body.appendChild(newButton);
}
$(".btn-table-add-row").prop('disabled', true);
});

JS expand onClick multiple events

Please check this page first : Solarking - About Us
Check first 2 boxes which has a READ MORE button. On clicking them, they expand a paragraph.
Now I want it to be like when I click on it, it should expand the text and change the button value to "CLOSE" from "READ MORE". And on again clicking on "CLOSE", it should change value to "READ MORE".
I searched for long time to see how to fire multiple events on onClick, but I saw that some said to use a ; in them, some said make a new function and put 2 functions in it.
Now I tried to make a new function with 2 functions inside it (one to expand the paragraph, other to change value of button, but I failed. (I am new to JS).
Help please. Thank you in advance!
Code I have on the page :
button code:
<p style="text-align: right;"><input id="button12" style="background-color: #eca200; color: #ffffff;" onclick="return toggleMe('para1')" type="button" value="Read more" /></p>
Script :
<script type="text/javascript">
function toggleMe(a){
var e=document.getElementById(a);
if(!e)return true;
if(e.style.display=="none"){
e.style.display="block"
}
else{
e.style.display="none"
}
return true;
}
</script>
I think the easiest way to do this would be to set a boolean variable. In other words, let's say that it starts off with the dclaration at the beginning of the page.
var hasbeenclicked = false;
Then, after the first click
hasbeenclicked = true;
After a second click
hasbeenclicked = false;
When the function is called, it checks the variable and operates accordingly. The following is not real JS....
if hasbeenclicked = true {
do some stuff;
}
else {
do some other stuff;
}
That is a simple way to accomplish what you are trying to do.
Additional info:
Use two DIV tags with separate ID's. One for the paragraph and one for the "label". Use getelementbyID to alter each one appropriately.
I noticed you are using jQuery.
You could use a toggle method.
Alter the html link. Add a class of expander and use the data attribute to identify the paragraph id
<p style="text-align: right;">
<input id="button12" data-toggle="para1" class="expander" style="background-color: #eca200; color: #ffffff;" type="button" value="Read more" />
</p>
The JS
$(".expander").click(function() {
var self = $(this);
$("#" + self.data('toggle')).slideToggle(500, function () {
if ($("#" + self.data('toggle')).is(':visible')) { // paragraph is open
self.val("Close");
} else { // paragraph is closed
self.val("Read More");
}
});
});

Javascript variable scroll issue

I have a page whereby the user can press left + right buttons to scroll through numbers between 1-10.
The default value is 0 which displays blank.
There are two buttons at the bottom which allow the user to 'Clear' the number - reseting it to 0. Or to 'Shuffle', picking a random number.
After this the user can submit these numbers into a database.
My issue is, if the user were to scroll to 5 (for example), click shuffle then submit, it would submit '5' instead of the random number it should have generated.
Also if the user only clicks 'shuffle' then submit, it'll input '0'.
The issue with the 'clear' button is similar, if the user scrolls to 5, then hits reset, the variable would stay at '5' when submitted.
I'm probably overcomplicating something very simple, and im sorry if i am, but this is annoying me.
Thankyou ~
I'm not entirely certain what the problem is without looking at your code. I get the feeling it is something like this:
Javascript
var opNumb = 0; //default number
left = function(){if (opNumb>0) opNumb--;
updateNumb(opNumb);}
right = function(){if (opNumb<10) opNumb++;
updateNumb(opNumb);}
def = function(){opNumb=0;
updateNumb(opNumb);} //function to return to default
randomNumb = function(){opNumb = Math.floor(Math.random() * 11);
updateNumb(opNumb);}
updateNumb = function(Numb){document.forms[0].opVal.value = Numb;}
window.onkeydown = press; //bind keydown to press function
function press(e){
if (e.keyCode == 37) left();
if (e.keyCode == 39) right()
}
HTML form
<form id="frm1">
<input type="text" name="opVal" value="0"/><br />
<input type="button" value="left" onclick="left()"/><input type="button" value="right" onclick="right()"/><input type="button" value="Clear" onclick="def()"/><input type="button" value="Shuffle" onclick="randomNumb()"/><br />
<input type="button" value="Submit form" onclick="alert(opNumb);"/>
</form>​
What does your form look like? You're most likely having a problem setting a value?
Link to example
It sounds like your number isn't saving so whenever you update the number on the screen I would save the number then that way you should always be sending the number that you see.
var number = 0;
//All your events to call the different functions
function moveLeft{
//logic
reset(num);
}
function moveRight{
//logic
reset(num);
}
function shuffle{
//logic
reset(num);
}
function reset{
//logic
reset(num);
}
reset(num){
number = num;
//update the HTML
}

Categories