I'm struggling to get my links to enable their respective buttons. For instance the first link should enable the first button and the second should enable button 2.
Can anyone help?
Link 1
Link 2
<button disabled class="btn btn-primary pull-left" id="butt1">Button 1</button>
<button disabled class="btn btn-primary pull-left" id="butt2">Button 2</button>
Your problem is your use of quotation marks. There are two options:
Use single quotes
Use " or \22 instead of your double quotes
Explanation
Your onclick is wrapped in double quotes. As soon as you use a double quote, it's the end of the onclick.
Solution
Link 1
Link 2
Demonstration
See this fiddle (Thanks #JamesThorpe for updating the escaped quote option)
Note, I removed the href because it doesn't make sense to link somewhere if you're going to do something on the current page.
removeAttribute(:attribute) can do the trick as well.
Link 1
<button disabled class="btn btn-primary pull-left" id="butt1">Button 1</button>
Just change the quatation marks for the id from double to single ones:
document.getElementById('butt1').disabled=false;
If the anchor is just for the activation, add an return false at the end:
document.getElementById('butt1').disabled=false; return false;
Change the "butt*" with 'butt*' , otherwise the browser read this
onclick="document.getElementById("
and edit the href="link" with href="#" (this is not mandatory, but the question as it is now is a little strange)
Link 1
Link 2
<button disabled class="btn btn-primary pull-left" id="butt1">Button 1</button>
<button disabled class="btn btn-primary pull-left" id="butt2">Button 2</button>
you problem in this string
"document.getElementById("butt1").disabled=false"
it should be
"document.getElementById('butt1').disabled=false"
Fiddle here
With a bit more work you start enabling a bit more elements, or add functionality that you could expand on easier in the future.
As a simple example, i added a small javascript file where you could set the elements that upon click activate/deactivate the other elements.
Currently i am preventing the default action, so you wouldn't be navigating towards the link you are actually setting, but that is entirely up to you ;)
;(function (ns) {
var actionElements = {
l1: ['butt1'],
l2: ['butt2']
};
function bootstrap() {
var prop, value, element;
for (prop in actionElements) {
if (actionElements.hasOwnProperty(prop)) {
element = document.getElementById(prop);
value = actionElements[prop];
if (element) {
element.addEventListener('click', function(e) {
if (typeof e === 'undefined') {
var e = window.event;
}
e.preventDefault();
for (var i = 0; i < this.length; i++) {
var el = document.getElementById(this[i]);
el.disabled = false;
}
return false;
}.bind(value));
}
}
}
}
ns.addEventListener('load', bootstrap);
}(window));
Link 1
Link 2
<button disabled class="btn btn-primary pull-left" id="butt1">Button 1</button>
<button disabled class="btn btn-primary pull-left" id="butt2">Button 2</button>
Related
I was trying to manipulate the css when clicking on button using javascript . I want to just make a single button active the one which is recently clicked.
I am able to make it active but somehow i am not able to remove active for other which is not selected
here is what i tried in js
const myFunction = (event) => {
const clickedElem = event.target
const allBtns = document.querySelectorAll('.btn.lightblue')
allBtns.forEach(btn => btn.classList.remove('.btn.lightblue.active'))
clickedElem.classList.add('active')
}
<p>
<button onclick="myFunction(event)" class="btn lightblue">XASD</button>
<button onclick="myFunction(event)" class="btn lightblue">QWER</button>
<button onclick="myFunction(event)" class="btn lightblue">ASDF</button>
<button onclick="myFunction(event)" class="btn lightblue">ZXCV</button>
</p>
Look at the definition of the remove method:
tokenList.remove(token1[, token2[, ...tokenN]]);
It takes each class that you want to remove as a separate argument (strings with one class name in each).
It doesn't take a single argument with a CSS selector.
… and you probably only want to remove the active class anyway, not btn or lightblue.
When using remove function on btn.classList.remove, pls put className only.
const myFunction = (event) => {
const clickedElem = event.target
const allBtns = document.querySelectorAll('.btn.lightblue')
allBtns.forEach(btn => btn.classList.remove('active'))
clickedElem.classList.add('active')
}
.active {
background: red;
}
<p>
<button onclick="myFunction(event)" class="btn lightblue">XASD</button>
<button onclick="myFunction(event)" class="btn lightblue">QWER</button>
<button onclick="myFunction(event)" class="btn lightblue">ASDF</button>
<button onclick="myFunction(event)" class="btn lightblue">ZXCV</button>
</p>
you can use 1) Element.style = "..." or 2) Element.classList.add("...")
to
overwrite the css with the style attribute
add a class to the element to have it use a predefined styling. (note that elements can have multiple classes)
I have a div in which there are 3 buttons. What I am expecting is that when I click the 3rd button, the 2nd and the 3rd buttons should fadeOut ... but in reality, only the 3rd button is fading out ... why so?
Here's, my code
<div id="bttns">
<button class="btn btn-danger"> Delete </button> //1st Button
<button class="btn btn-warning"> Modify </button> //2nd Button
<button class="btn btn-success"> Complete </button> //3rd Button
</div>
And here is the jQuery
$(".btn-success").on("click", function(){
$( $(this) , $(this).parent().children(".btn-warning") ).fadeOut(500)
})
I couldn't find a question similar to mine ... and also I am new to all of this so if you do find that such a question exists, please redirect me to it.
This happens becuse:
$( $(this) , $(this).parent().children(".btn-warning") )
this is not a valid selector here. To chain multiple jQuery objects you can use .add() method and then call .fadeOut(500) on the collection like:
$(".btn-success").on("click", function() {
var $btn3 = $(this);
var $btn2 = $(this).parent().children(".btn-warning");
$btn2.add($btn3).fadeOut(500)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="bttns">
<button class="btn btn-danger"> Delete </button>
<button class="btn btn-warning"> Modify </button>
<button class="btn btn-success"> Complete </button>
</div>
As you have assigned classes. You can go like this :-
$(".btn-success").on("click", function () {
$('.btn-warning, .btn-success').fadeOut(500);
})
you are fading out only the button with the btn-warning class. instead use two selectors.
$(".btn-success").on("click", function(){
$(this).parent().children(".btn-warning, .btn-success").fadeOut(500)
})
Instead of creating a new function for every button handler i wanna create just one function and handle all the buttons there.I wanna the first button to do something different than the second one....My idea was to have one eventlistener but how do i know the target.id is the same as btn1 for example?
<div class="col-11" id="btns">
<button class="btn btn-dark" id="btn1">Button 1</button>
<button class="btn btn-dark" id="btn2">Button 2</button>
<button class="btn btn-red" id="btn3">Button 3</button>
<button class="btn btn-blue" id="btn4">Button 4</button>
</div>
let btn1=document.getElementById('btns');
btn1.addEventListener("click",doStuff);
function doStuff(e){
if(e.target.id===document.getElementById('btn1')){ //doesnt work
console.log("Hello");
}else if(e.target.id===.getElementbyId('btn2'){
//doSomething...
}
}
You have the right approach, there's just an error in your code:
e.target.id===document.getElementById('btn1')
This compares the ID of the element that was clicked to the element with the ID of 'btn1'.
That is, it compares a string to an element.
Naturally, this will always return false.
Instead, try:
e.target===document.getElementById('btn1')
This compares an element to an element.
Or:
e.target.id==='btn1'
This compares a string to a string.
Optional: You could simplify your code by using a switch/case block instead of a bunch of if statements. Here's how I would write your click handler:
function doStuff(e) {
switch(e.target.id){
case 'btn1':
// Do something for btn1...
break;
case 'btn2':
// Do something for btn2...
break;
}
}
More information about switch/case: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
first of all, thank you for your time to read this question, and two things, I'm using ES5 and I don't use jQuery.
Right now I'm struggling a lot to figure what's the correct solution for the addEventListener, because for some reason it does not trigger for the second button which is only for the mobile screen dimensions, the problem is that the second button have the same id but different class, for example this:
<div class="product-bg-container product-general-info variation-info">
<input type="hidden" name="sku" value="Something-15892290" id="selected-option">
{/* Desktop screen button */}
<button id="buy-now" class="btn btn-lg hidden-sm-down btn-primary">
Add to Cart
</button>
{/* Mobile screen button */}
<button id="buy-now" class="btn btn-lg hidden-md-up btn-primary">
Add to Cart
</button>
</div>
Where I am trying to trigger the second button but it does not where I don't understand why it does, if the id is the same, should not matter, so I'm trying to figure how to trigger from the first button if it's clicked and also with the second if it's clicked, but I'm out of ideas...
var button = document.getElementById('buy-now');
if (!button) {
return;
}
button.addEventListener('click', function trackAddToCart() {
// more code for the event
}
I thought an idea to capture the attribute of the button, but it works in the first button but not for the second one:
var button = document.getElementById('buy-now');
var att = button.getAttribute('class');
button.addEventListener('click', function() {
console.log('class ' + att); //shows: class: btn btn-lg hidden-sm-down btn-primary
console.log('button class? '+ button); //shows: button element: [object HTMLButtonElement]
});
But when I click the second button... does not trigger or happening nothing, not sure why... and I can't change the id value (which it should be easy but I can't "company standard")
Can anyone help me to have an idea how to capture and trigger the event for the second button ??
The attribute id must be unique in a document. You can use attributeStartsWith selector or class with querySelectorAll(). Then loop through all the button to attach the event (click) individually:
//var button = document.querySelectorAll('.btn.btn-primary');
var button = document.querySelectorAll('[id^=buy-now]');
button.forEach(function(btn){
btn.addEventListener('click', function() {
console.log('class ' + this.classList);
console.log('button class? '+ this.id);
});
});
<div class="product-bg-container product-general-info variation-info">
<input type="hidden" name="sku" value="Something-15892290" id="selected-option">
<button id="buy-now" class="btn btn-lg hidden-sm-down btn-primary">
Add to Cart
</button>
<button id="buy-now2" class="btn btn-lg hidden-md-up btn-primary">
Add to Cart
</button>
</div>
nextElementSibling seems working in this case.
var btn1 = document.getElementById("btn");
var btn2 = btn1.nextElementSibling;
btn1.addEventListener("click",function(e){
console.log("btn1");
});
btn2.addEventListener("click",function(e){
console.log("btn2");
});
<div>
<button id="btn" class="btn1">butotn 1</button>
<button id="btn" class="btn2">butotn 2</button>
</div>
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 6 years ago.
My problems is: I am trying to count all downloads. I do that by adding +1 to my database everytime the button is clicked and then I simply take the database value and display it. I've tried numerous ways but no matter what I do the downloads stay zero. I prefer raw javascript/html because I am not that advanced and I want to do it a way that I understand it.
I've also tried pasting the script in the body and the head but without effect.
<div style="padding: 10px">
<img src="http://localhost:3000/uploads/{{article.imgName}}" width="100%" style="margin-bottom: 15px">
<p>
{{#each article.tags }}
<a class="btn btn-default btn-xs"
href="/tag/{{this}}">{{this}}</a>
{{/each}}
</p>
<small class="author">
{{article.author.fullName}}
</small>
<footer>
<script type="text/javascript">
var article = require("mongoose/lib/model.js");
const downloadCount = function () {
article.downloads += 1;
article.save();
}
document.getElementById('download').onClick = downloadCount;
</script>
<p><br>Views: {{article.views}} </p>
<p>Downloads: {{article.downloads}}</p>
<div class="pull-right">
<a class="btn btn-default btn-sm" href="/">« Back</a>
<a id="download" class="btn btn-default btn-sm" href ="/uploads/{{article.imgName}}" download="{{article.imgName}}" onClick="downloadCount()">Download</a>
{{#if isUserAuthorized}}
<a class="btn btn-success btn-sm"
href="/article/edit/{{article.id}}">Edit</a>
<a class="btn btn-danger btn-sm"
href="/article/delete/{{article.id}}">Delete</a>
{{/if}}
</div>
</footer>
</div>
I don't know which js library you used.
but about handling the on click event in javascript is by using addEventListener function.
document.getElementById('download').addEventListener('click',downloadCount);
Can you specify more about what technologies you used.
My approach will be the following:
1) Wrap your function call with:
// pure JavaScript equivalent to jQuery's $.ready()
// doesn't work in older IEs
document.addEventListener('DOMContentLoaded', function(){
// your code goes here
}, false);
For further support take a look here: http://youmightnotneedjquery.com/#ready
2) Remove the inline handler and use addEventListener
const article = require("mongoose/lib/model.js");
const el = document.getElementById('download');
el.addEventListener('click', downloadCount);
function downloadCount(e) {
e.preventDefault();
article.downloads += 1;
article.save();
}
All together:
<a id="download" class="btn btn-default btn-sm" href ="/uploads/{{article.imgName}}" download="{{article.imgName}}">Download</a>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function(){
const article = require("mongoose/lib/model.js");
const el = document.getElementById('download');
el.addEventListener('click', downloadCount);
function downloadCount(e) {
e.preventDefault();
article.downloads += 1;
article.save();
}
}, false);
</script>