document.getElementById.onClick doesn't work (Javascript) [duplicate] - javascript

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>

Related

How to install Facebook pixel event code in a php button?

So I have a simple PHP share button fo facebook and I want to add pixel event code in it that tracks the button when it's clicked
Here is the code for the button:
<div class="row" style="margin-top: 10px;">
<div class="col-md-5 col-md-offset-1">
<a target="_blank" class="btn btn-block btn-social c-btn-square c-btn-uppercase btn-md btn-facebook" href="{{$facebook_link}}">
<i class="fab fa-facebook"></i> Share on Facebook
Where should I exactly put the code for the event which is:
<script>
fbq('track', 'SubmitApplication');
</script>
Welcome. You must handle event when button click.
Try this:
<script type="text/javascript">
var facebookButton = document.querySelector('a.btn-facebook');
facebookButton.addEventListener("click", () => {
fbq('track', 'SubmitApplication');
});
</script>

Rewrite inline javascript to external function - this reference

I'm trying to rewrite some javascript code from an inline button onclick call to an regular javascript function.
I used the this reference in my code to remove a table column, which worked perfectly fine. Since I need to use the line of code on a few places I want it to be in a regular javascript function.
What I had:
<button type="button" tabindex="-1" class="btn btn-secondary btn-tblrmv" onclick="if(!$(this).closest('tr').hasClass('notDeletable')){ $(this).closest('tr').remove(); }">
<i class="mdi mdi-minus"></i>
</button>
as for the javasript function itself:
function removeTableRow(){
if(!$(this).closest('tr').hasClass('notDeletable')){
$(this).closest('tr').remove();
}
}
Could someone please explain, why this isn't working as intended?
This do not work because this is not referring to the current element. Try with:
HTML:
<button type="button" tabindex="-1" class="btn btn-secondary btn-tblrmv" onclick="removeTableRow(this)">
<i class="mdi mdi-minus"></i>
</button>
JS:
function removeTableRow (row) {
if (!$(row).closest('tr').hasClass('notDeletable')) {
$(row).closest('tr').remove();
}
}

Unable to find the specific items value jQuery

I am facing an easy problem but unable to find a solution the problem is
i am creating a dynamic div with some elements also with some data
$("#divSearchedIssue").append(`
<div class="statistic d-flex align-items-center bg-white has-shadow">
<div class="icon bg-red">
<i class="fa fa-tasks"></i>
</div>
<div class="text">
***//want to get this below id value//**
Mobile Code :
<small id="mbCode">
${ data[0].MobileCode }
</small>
***/want to find/**
<br>
Failed From:
<small>
${ data[0].FailedStation }
</small>
<br>
Issues :
<small>
${ data[0].Issues }
</small>
</div>
<div class="text"><strong> </strong></div>
<div class="text">
<button type="button" id="btn" class="btn btn-warning pull-right">Start</button>
</div>
<div class="text"><br></div>
</div>`);
Here I have a button .On this button click i want to fetch the value of
small text which id is #mbCode as mentioned above inside the code
I am trying this by using the following button click code
$(document).on('click', '#btn', function () {
var data = $(this).closest('small').find('#mbCode').val();
alert(data);
});
but its not working.I mean I cant fetch the value of #mbCode on this button click .So help needed
Thanks for helping
Based on .closest()
Description: For each element in the set, get the first element that
matches the selector by testing the element itself and traversing up
through its ancestors in the DOM tree.
As <small> is not an ancestors to button in hierarchy(while traversing-up),
So You need to first go the parent of <small> through .closest() and then try to find <small> html using .find() and .html()
$(document).on('click', '#btn', function () {
var data = $(this).closest('.statistic').find('small').html();
alert(data);
});
Working snippet:-
data = [{'MobileCode':20,'FailedStation':'WATERLOO','Issues':'broken'}];
$("#divSearchedIssue").append('<div class="statistic d-flex align-items- center bg-white has-shadow"><div class="icon bg-red"><i class="fa fa-tasks"></i></div><div class="text">Mobile Code :<small id="mbCode">' + data[0].MobileCode + '</small><br>Failed From: <small> ' + data[0].FailedStation + '</small><br>Issues :<small> '+ data[0].Issues + '</small></div><div class="text"><strong> </strong></div><div class="text"><button type="button" id="btn" class="btn btn-warning pull-right">Start</button></div><div class="text"><br></div></div>');
$(document).on('click', '#btn', function () {
var data = $(this).closest('.statistic').find('small').each(function(){
alert($(this).html());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divSearchedIssue"></div>
Note:- .text() will work too
https://jsfiddle.net/tyz4ox50/
As identifiers must be unique, Directly use ID Selector with .text()/.html() method
var data = $('#mbCode').text()
However if you are appending multiple elements I would recommend an alternative to persist Mobile code arbitrary data using custom data-* attribute along with <button> which can be fetched using .data(key) and attach event handler using Class Selector
$("#divSearchedIssue").append('<button type="button" id="btn" class="btn btn-warning pull-right" data-mobilecode="' + data[0].MobileCode + '" >Start</button>');
var counter = 0;
function append() {
$("#divSearchedIssue").append('<button type="button" id="btn" class="btn btn-warning pull-right" data-mobilecode="' + ++counter + '" >Start</button>');
}
append();
append();
append();
$(document).on('click', '.btn', function() {
var data = $(this).data('mobilecode');
console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divSearchedIssue"></div>
Try the following code snippet
var value = $('#mbCode').val();
Make sure the id is unique
Ids shouldn't be duplicate in an web-page.
Also, small is not one of the parent nodes of btns, and use html instead of val.
You need to go two-level higher to statistic Make it
$(document).on('click', '.text #btn', function () {
var data = $(this).closest('.statistic').find('#mbCode');
console.log(data.html());
});
Demo
var counter = 0;
function append() {
$("#divSearchedIssue").append(
`<div class="statistic d-flex align-items-
center bg-white has-shadow">
<div class="icon bg-red"><i class="fa fa-tasks">
</i></div>
<div class="text">
Mobile Code :<small id="mbCode">` +
(counter++) +
`</small><br>Failed From: <small> ' +
data[0].FailedStation + '</small><br>Issues :<small> ' + data[0].Issues +
'</small></div>
<div class="text"><strong> </strong>
</div>
<div class="text"><button type="button" id="btn" class="btn btn-
warning pull-right">Start</button></div>
<div class="text"><br></div>
</div>`
);
}
append();
append();
append();
$(document).on('click', '.text #btn', function () {
var data = $(this).closest('.statistic').find('#mbCode');
console.log(data.html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divSearchedIssue"></div>
If your element already has an ID attribute you should be able to find the element by the ID. $("#mbCode")
Your js code
$(this).closest('small').find('#mbCode').val(); // "$(this)", in your code, represents the "button" that was clicked.
is looking for "small" tag inside "button" element, but it's not there. It would work if your button was like
<button type="button" id="btn" class="btn btn-warning pull-right"><small id="mbCode"></small></button>
This should work:
$(document).on('click', '#btn', function () {
var $mbCode = $('#mbCode');
console.log($mbCode);
});

getElementById with multiple buttons

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>

How to set `aria-disabled` as true using JavaScript

I have no idea about JS. But there is needed one line of code in my Ruby. I have the below html.
<div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix">
<div class="ui-dialog-buttonset">
<button class="otherButtonClass ui-state-hover ui-state-focus" type="button" role="button" aria-disabled="false">
<button class="otherButtonClass" type="button" role="button" aria-disabled="false" style="display: none;">
<button class="cancelButtonClass" type="button" role="button" aria-disabled="false">
</div>
</div>
I want JS code to make the first and second button to make them visible. What would be the code?
Please help.
http://jsfiddle.net/SQ7SH/1/
var buttons = document.querySelectorAll('.ui-dialog-buttonset button');
buttons[0].setAttribute('aria-disabled', true);
buttons[1].setAttribute('aria-disabled', true);
Also button require close tag
The current way of setting aria- attributes is to reference the properties directly.
To get:
let el = document.getElementById('foobar');
console.log(el.ariaDisabled); // Should log the current value of aria-disabled.
To set:
let el = document.getElementById('foobar');
el.ariaDisabled = 'true';
console.log(el.ariaDisabled); // Should log 'true'.
Reference: Element.ariaDisabled MDN
var buttons = document.getElementsByClassName('otherButtonClass');
for(var i = 0; i < buttons.length; i++){
buttons[i].setAttribute('aria-disabled', 'true');
}
As asked there is needed one line of code:
document.querySelectorAll('.ui-dialog-buttonset .otherButtonClass').forEach(function (item) {item.setAttribute('aria-disabled', true);});

Categories