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>
Related
I have several buttons on my webpage and want to style the background colors when I click on them according to the button's name. I want all the "Toms" to be lightgray, all the "Dicks" to be lightgreen, and all the rest ("Harrys") to be lightyellow. I added the following code to my external Javascript page, but it's not working:
function bgColor() {
var x = document.getElementsByTagName("button").name;
if (x == "Tom") {
document.getElementsByTagName("button").style.backgroundColor=
"lightgray";
} else if (x == "Dick") {
document.getElementsByTagName("button").style.backgroundColor=
"lightgreen";
} else {
document.getElementsByTagName("button").style.backgroundColor=
"lightyellow";
}
}
The HTML reads something like this but between less than/greater than symbols, of course:
button type="button" name="Tom" onclick="bgColor()"
button type="button" name="Dick" onclick="bgColor()"
button type="button" name="Harry" onclick="bgColor()"
EDITED TO ADD
I can't figure out how to reply to Mikkel's comment directly. I tried simply posting another comment, but it wouldn't let me add code. Anyway, I tried the fix that he suggested using the following but it didn't work for me either.
function bgColor() {
var tom = document.querySelector('button[name="Tom"]')
.style.backgroundColor = 'lightgray';
var dick = document.querySelector('button[name="Dick"]')
.style.backgroundColor = 'lightgreen';
var harry = document.querySelector('button[name="Harry"]')
.style.backgroundColor = 'lightyellow';
}
What am I doing wrong?
As #Mikkel has said, your selector is wrong - You'll want to use an attribute selector to get the elements that match your name attribute
However, in this specfic case as well you've got a more weird issue - You'll have to change the name of your function - bgColor is also the name of a property on the elements which I believe is causes your further issues. - You can read more about that here
If you change the name to something like changeColors you shouldn't have this issue
As an aside, there's no need to assign your querySelectors to a variable, you can just run them in this case
function changeColors() {
document.querySelector('button[name="Tom"]').style.backgroundColor = 'lightgray';
document.querySelector('button[name="Dick"]').style.backgroundColor = 'lightgreen';
document.querySelector('button[name="Harry"]').style.backgroundColor = 'lightyellow';
}
<button type="button" name="Tom" onclick="changeColors()"> X </button>
<button type="button" name="Dick" onclick="changeColors()"> X </button>
<button type="button" name="Harry" onclick="changeColors()"> X </button>
document.getElementsByTaName("button") is getting all your buttons. What you want to do, is check each of the buttons individually and apply the color.
You can do it with the code below, that'll change the color of "Tom". You can repeat it to make it work for your other buttons.
function bgColor() {
var tom = document.querySelector('button[name="Tom"]').style.backgroundColor = 'purple'
}
First, using bgColor as a user-defined function name will throw a type error since it's a reserve keyword for JS (Object's property) though deprecated.
Second -> var x = document.getElementsByTagName("button").name; will obviously throw an error x is undefined because this syntax without '.name' should return all buttons on the page in an array, with that you can loop through and access properties of individual button eg. name
So we use this instead var x = document.getElementsByTagName("button") which returns an array of buttons on the page.
That being said, let's see how we can modify your code to achieve what you're looking for:
HTML:
<button type="button" name="Tom" onclick="buttonBgColor(event)"> Tom</button>
<button type="button" name="Dick" onclick="buttonBgColor(event)"> DicK </button>
<button type="button" name="Harry" onclick="buttonBgColor(event)"> Harry </button>
JS:
function buttonBgColor(e) {
const buttons = document.getElementsByTagName("button").name;
for(button of buttons){
const current_button = e.target;
if(current_button.name == 'Tom'){
current_button.style.backgroundColor = 'lightgray'
}else if(current_button.name == 'Dick'){
current_button.style.backgroundColor = 'lightgreen'
}else if(current_button.name == 'Harry'){
current_button.style.backgroundColor = 'lightyellow'
}
}
}
This method is useful because assuming you have two buttons with same name say 'Tom' and yet you want one of them to do something extra aside changing their background colors, you can reference their ID to achieve that using e.target.id or current_button.id in a condition to wire up another handler for that particular 'Tom' button.
Hope this helps.
i create some Tiles in a foreach loop:
#foreach (var a in Model.AA)
{
<partial name="Partial/A/Tile" model="a" />
}
each of this Tiles have a Button to Start something. (Yes if the JS works i dont need the asp calls at the button)
my Problem is now: The js call works only at the first Tile but not at all others. But Why?
Button
<div class="Infos" Id=#Model.Id>
<a class="button" id="startsomething" url="#Url.Action(nameof(AController.Start), "A")" asp-action="Start" asp-route-Id="#Model.Id">Start me</a>
</div>
JS
$('#startsomething').click(function (event) {
var Id = $(this).parents('.Infos').attr('Id');
var url = $(this).attr('url');
event.preventDefault();
event.stopPropagation();
Start(url, Id)
});
ids are meant to be unique, so the event only registers to one id when you use #startsomething. Use a class name, and the selector .somethingClass.
I can't edit this code to work in buttons based on text instead of class or make it for both by class name and text.
For example:
<button class="same">plz-click-me</button>
<button class="same">dont-click-me</button>
Now I want code to click on the "click-me" button
This what I used in my code to click by class
var inputs = document.querySelectorAll('.same:not(.hidden_elem)');
Thanks and hope to find answers help me
You'll have to iterate through the possible matching elements and select those whose textContent matches what you want. You can't use jQuery's .contains because the substring click-me is included in don't-click-me:
const matching = Array.prototype.filter.call(
document.querySelectorAll('.same'),
({ textContent }) => textContent === 'click-me'
);
console.log(matching);
<button class="same">click-me</button>
<button class="same">dont-click-me</button>
Note that if the substring of the one you want to select is not included in the elements you don't want to select, you can use .contains:
$('.same:contains("click-this-here")').click(() => console.log('clicked'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="same">click-this-here</button>
<button class="same">dont-click-me</button>
var buttons = document.querySelectorAll("button");
var clickButton = Array.from(buttons).filter( button => button.textContent === "click-me")[0];
<button class="same">click-me</button>
<button class="same">dont-click-me</button>
I was trying to make the color of the buttons change using onclick and getElementsByClassName and came up with something like this:
HTML:
<button onclick="submitButtonStyle()" type="submit" class="stylebutton">
Submit </button>
JS:
function submitButtonStyle() {
document.getElementsByClassName("stylebutton").style.backgroundColor = "red"; }
I would be really grateful if you guys gave me a hint about what is lacking in my code/what I should add etc.
getElementsByClassName returns an HTMLCollection so you need to get the elements using an index, in your case index === 0 getElementsByClassName[0].
Actually, you don't need to call the function getElementsByClassName, pass the element as param.
function submitButtonStyle(_this) {
_this.style.backgroundColor = "red";
}
<button onclick="submitButtonStyle(this)" type="submit" class="stylebutton">
Submit </button>
Better approach using Event binding and function querySelectorAll
document.querySelectorAll('.stylebutton').forEach(function(e) {
e.addEventListener('click', function() {
this.style.backgroundColor = "red";
})
});
<button type="submit" class="stylebutton"> Submit </button>
document.getElementsByClassName returns an array of objects, since many tags may have the same class. If you know that only one object has a given class, use
document.getElementsByClassName("stylebutton")[0].style.backgroundColor = "red";
The className property sets or returns the class name of an element (the value of an element's class attribute).
function submitButtonStyle() {
document.getElementsByClassName("stylebutton")[0].style.backgroundColor = "red"; }
<button onclick="submitButtonStyle()" type="submit" class="stylebutton">
Submit </button>
JS:
The getElementsByClassName() method returns a collection of all
elements in the document with the specified class name, as a NodeList
object.
The NodeList object represents a collection of nodes. The nodes can be
accessed by index numbers. The index starts at 0.
Source
Using jquery, try this. if your button id is say id= clickme
$("clickme").on('çlick', function(){
$(this).css('background-color', 'grey'); .......
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);
});