Javascript/jQuery disable buttons by classname - javascript

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

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;

Disable certain buttons javascript when id's are different

I want to disable a certain group of buttons at a specific time. Using this js:
document.getElementById("reset").setAttribute('disabled','disabled');
But all IDs are different, the buttons is like <button id=1> <button id=2> etc. Can I set some made up variable like <button group="hello">
And then do something like this:
document.getElementById("group:hello").setAttribute('disabled','disabled');
to disable all of the buttons, even though the ID attribute is different from button to button?
what you can do is use the data attribute, see next:
<button data-group="hello" id="button1">test1</button>
<button data-group="hello" id="button2">test2</button>
<button data-group="hello" id="button3">test3</button>
and the JS
document.querySelectorAll('[data-group="hello"]').forEach(function(button) {
button.disabled = true;
});
edit, here is the fiddle https://jsfiddle.net/xycmj4gv/2/
Use class instead of ID.
Code is easy:
document.getElementsByClassName("group1").setAttribute('disabled','disabled');
Since you tagged jquery
$(".mybutton").attr("disabled", true);
Where mybutton is
<button class= "mybutton"> </button>
Use class instead of id as follows:
var elements = document.getElementsByClassName("{yourClassName}");
var i;
for (i = 0; i < x.length; i++) {
elements[i].setAttribute(“disabled”, “red");
}
<button class="{yourClassName}”></button>
You can use getElementsByTagName to get all buttons and then You can use Array.Prototype.forEach to disable all buttons like below. forEach will loop through all element and add desired attribute(in your case disabled) to all found elements.
Array.prototype.forEach.call
(document.getElementsByTagName("button"), function(e) {
e.setAttribute('disabled','disabled');
});
<button id="1">12</button> <button id="2">12</button>
<button id="3">12</button> <button id="4">12</button>
You can use wildcards for Id's:
Starts-with selector
document.querySelector("[id^=myId]")
works for
id="myId1"
id="myId2"
...
or Ends-with selector
document.querySelector("[id$=myId]")
works for
id="firstMyId"
id="secondMyId",...
Hint:
Please don't start Id's with numbers like: id="1myId". That's not w3c conform
use class to group buttons, like this:
var btnsGroup = document.getElementsByClassName('group');
Array.prototype.forEach.call(btnsGroup, function(button) {
button.setAttribute('disabled','disabled');
});
You can do something like this-
var buttons = document.querySelectorAll("[reset='true']");
for (i = 0; i < buttons.length; ++i)
{
buttons[i].setAttribute('disabled','disabled');
}
And HTML goes like this-
<button reset="true" >1 Candy</button>
<button reset="true" >2 Candy</button>

Rotate button settings and values on each click, repeating

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

Show/Hide onClick button not working

Hey guys I have searched for many answers and none of them seem to be working so I am going to put my code here and hopefully you can help me figure this out.
I am going to have two buttons. The first button (show_Chappie) is going to show the hidden contents and another button (hide_Chappie) and hides it self when clicked.
The second button (hide_chappie) is going to hide the contents and bring back the first button (show_chappie). The hide_chappie button itself would also be hidden.
The information div is already hidden from the start. I did this on the CSS using the display:none;
Here's my HTML code so far:
<button class ="show_chappie" onclick="showInfo()">Show More</button>
<div class="info">Info here.</div>
<button class ="hide_chappie" onclick="hideInfo()">Show Less</button>
Here's my JavaScript code so far:
function showInfo(){
document.getElementById('chappie_info').style.display = "inline-block";
document.getElementById('show_chappie').style.display = "none";
document.getElementById('hide_chappie').style.display = "inline-block";
}
I haven't written the code for the hide_chappie button because I wanted to see this working first.
So where have I gone wrong here? Thanks for the help in advance.
You are trying to get the elements by id while they have a class, you should change the elements class to id like this:
<button id="show_chappie" onclick="showInfo()">Show More</button>
<div id="info">Info here.</div>
<button id="hide_chappie" onclick="hideInfo()">Show Less</button>
you should change your code to:
<button id ="show_chappie" onclick="showInfo()" >Show More</button>
<div class="info">Info here.</div>
<button id= "hide_chappie" onclick="showInfo()">Show Less</button>
if you want to use class here,you should change your Javascript Code to
function showInfo(){
document.getElementByClass('chappie_info')[0].style.display = "inline-block";
document.getElementByClass('show_chappie')[0].style.display = "none";
document.getElementByClass('hide_chappie')[0].style.display = "inline-block";
}
because function getElementsByClass returns a collection,so you should add [] to find out the result you want!
It's kind of annoying to turn all id's into classes, you can use:
function showInfo(){
document.getElementsByClassName('chappie_info').style.display = "inline-block";
document.getElementsByClassName('show_chappie').style.display = "none";
document.getElementsByClassName('hide_chappie').style.display = "inline-block";
}
This is supported by practically every browser these days so I wouldn't worry about that. If that is still an issue an you need to support ancient browsers, use this:
document.getElementsByClassName = function (a) {
var b = document.getElementsByTagName('*'), i, c=[];
for (i = 0; i < b.length; i += 1) { b[i].getAttribute('class')===a&&c.push(b[i]); }
return c;
};

Analysing button in html to check if can register for events

I want to register for events on a button in a web page using javascript addEventListener or something equivalent. But the web page doesn't appear to have standard form buttons. The html snippet below is the html markup for what appears as a button on the page.
I want to detect mousedown (or mouseclick or equiv). Is there any way I could detect the user clicking on this button?
<a href="javascript:" id="WIN_0_536870914" arid=536870914 artype="Control" ardbn="Dial" artcolor="null" class="btn btn3d arfid536870914 ardbnDial" style="top:247; left:115; width:46; height:21;z-index:1001;">
<div class="btntextdiv" style="top:0; left:0; width:46; height:21;">
<div class="f1" style=";width:46">Dial</div>
</div>
</a>
The only tricky bit will be getting the elements from the DOM in the first place. If you know the id then it's trivial to get this specific button:
var elem = document.getElementById('WIN_0_536870914');
elem.addEventListener('click', function () {
alert('click!');
});
http://jsfiddle.net/ugsYB/
Although you probably want to target all the buttons by their class:
var elems = document.getElementsByClassName('btn');
var i;
for(i = 0; i < elems.length; i++) {
var elem = elems[i];
elem.addEventListener('click', function () {
alert('click!');
});
}
http://jsfiddle.net/ugsYB/1/ (Note: there are cross browser issues with getElementByClassName)
Of course, jQuery makes this sort of thing trivial:
$('.btn').click(function () { alert('click!'); });
http://jsfiddle.net/ugsYB/2/
But it might be overkill for your needs.

Categories