hooking up button in JS without using the onclick event - javascript

<button id=trainingbutton document.getElementById("trainingbutton").addEventListener("click",
}); ></button>
function(){
trainingbuttonclicked=()=>document.getElementById("trainingbtn").innerHTML = "Hello World";
Completely new to JavaScript and am trying to hook up a button to show an alert. Above is my HTML first and my app.js is below. I would like to try to hook up the event without using a simple onclick event handler. My preferred method would be either the event handler or the inner HTML method. Any advice appreciated. I know it's something simple but maybe Ive been staring at it too long, because I can't see the answer

You need your script tag in order to insert an eventlistener, like so
<script>
const button = document.querySelector('#trainingButton"); // # id's and . for selecting a
class in the dom (document object model)
button.addEventListener('click', function(event) {
const string = 'some string';
alert(string);
});
</script>
Your Button id should only contain a string like trainingButton so that it becomes <button id="trainingButton">
> the script tag should be placed in the bottom of your body tag, in order for the DOM to load properly before any javascript runs
for more info
https://www.w3schools.com/jsref/met_element_addeventlistener.asp

You need to separate your HTML from your javascript. You can either have them in separate files or in the same.
If you'd like them in the same file you can do the following. (Note: the script has to be after the button because we want it to run after the button has been created)
<button id="trainingbutton">Training Button</button>
<script>
var trainingbutton = document.getElementById("trainingbutton");
trainingbutton.addEventListener('click', function(event) {
trainingbutton.innerHTML = "Hello World";
});
</script>
You can also define the script above between the script tags in a seperate file (*.js) and link it to your HTML file using <script src='*.js'></script>. As you add more to your HTML and JS it can help to organize.

Related

SharePoint 2013 JavaScript OnClick event

On our SharePoint 2013 page we have a button which runs an EXE
I want to generate a JS Alert when the button is clicked so that users know to click RUN
The buttons are being generated by a Content Search Web Part which is reading from a list with a Title and URL field.
For the EXE my url is this: file:///S:/Web/EmailSignature_WPF/EmailSignature_WPF.exe
I tried to embed the JavaScript inline using code such as: javascript:open('file:///S:/Web/EmailSignature_WPF/EmailSignature_WPF.exe') or more basically: JavaScript:alert('TEST');
But SharePoint is giving me an "Invalid URL" message when I try to embed JS in this manner.
I have instead now moved to a Script Editor Web Part and am trying to add the Alert to the OnClick event of my button but this is where I am stuck.
My Script Editor code:
<script style="javascript;">
var img = document.getElementById('ctl00_ctl40_g_a225dbb9_1900_49f2_afe2_ab6f5bf77adf_csr4_pictureOnTop_line1');
img.onclick="javascript:alert('event has been triggered')";</script>
Here is an image of the IE Debug screen which is how I'm pulling the ID. This H2 element is wrapped in an HREF which is wrapped in two DIV tags which make up an LI
With the above snippet IE Debug is giving me this error message:
Unable to set property 'onclick' of undefined or null reference
I am hoping that this is as simple as misplaced quotations, or assigning the OnClick event to the wrong element, but I'm spinning my wheels. Any help appreciated and I'm happy to clarify
You should associate a function to the onclick event on img
<script type="text/javascript">
var img = document.getElementById('ctl00_ctl40_g_a225dbb9_1900_49f2_afe2_ab6f5bf77adf_csr4_pictureOnTop_line1');
img.onclick = function () {
alert('event has been triggered');
};
</script>
Say that your page is in the SitePages library and you use jQuery, you can add it to a folder called "js" in the SiteAssets folder, then go back to your Script Editor WP and do it like this:
<script src="../SiteAssets/js/jquery-3.6.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$('input[id*="csr4_pictureOnTop_line1"]').on('click', function() {
alert('event has been triggered');
});
</script>

Catch22 - HTML waiting for JS, JS waiting for HTML

I'm a newbie trying to write a JS/HTML report generator based on criteria which I submit in an HTML form. The plan eventually is to use PHP/mySQL to manipulate a database and return results but for now I'm just trying to build the HTML/CSS/JS and I've got stuck. I have attributed a JS function to a button in the <body> like so:
<input type="button" id="reportButton" value="Generate Report" onclick="showCriteria()">
I included a script in the <head> as follows:
<script>var showCriteria = function(){ My JS code...}</script>.
This function simply does some date manipulation and displays the result in a div on the same page like so:
document.getElementById("endDate").innerHTML = "to "+endDay+" "+endMonthName+" "+endYear;
But I get Uncaught TypeError: Cannot set property 'innerHTML' of null. So I searched the forum and discovered that this can sometimes be caused by not waiting for the window to load. So I wrapped the script as follows:
<script>
window.onload = function()
var showCriteria = function(){ My JS code...}
That solved the initial error but I then get Uncaught ReferenceError: showCriteria is not defined
It seems like I'm in a Catch22. I get the first error because the script is running before the window has loaded. I fix that by waiting for the window to load only to find that the HTML is waiting for my script to define my JS function.
Any advice gratefully received.
Report Generator screenshot
Window.load script
You've almost got the solution. At least you've got all the right elements.
window.onload = function() {
document.getElementById('reportButton').addEventListener('click', showCriteria);
};
This will make it so the button does not function until the page is ready.
You also need to remove the onclick from the button.
When you put the showCriteria function inside window.onload, please make sure it is accessible by the DOM, i.e. window.showCriteria.
<script>
window.onload = function()
window.showCriteria = function(){ My JS code...}
...
Beside using onclick on html, you can use add listener to listen the click event on that element.
window.onload = function() {
document.getElementById('reportButton').addEventListener('click', showCriteria);
};

Javascript replace content innerhtml on click with integrated PHP tag

I am trying to replace the content of a DIV once the button inside that DIV is clicked, (basically replacing the button, which retreives a PHP variable:
<div id="buttonholder">
Publish
</div>
I am trying to replace it with an unpublish button after a post is published (when the button above is clicked):
function publish(status){
document.getElementById("buttonholder").innerHTML = 'Unpublish';
}
It does not work however ... What am I doing wrong ?
Your code syntax is wrong. Use like below.
function publish(status){
document.getElementById("buttonholder").innerHTML = 'Unpublish';
}
Add a button id and then do:
$(function() {
$("#buttonId").click(function() {
$("#buttonHolder").html(" html to replace with ");
});
});
Also you can use the $("#buttonHolder").html(" html to replace with "); instruction in your onClick function as well.

Drop down value to Textbox (Not HTML Event Handlers)

Basically, I'm working with static HTML that is written in stone. I cannot add an onclick to the dropdown menu, which is usually what I would do.
The following is what I have:
<script type="text/javascript">
function replicate() {
var tb1 = document.getElementById("ctl00_ContentPlaceHolder1_DropDownList_Country_17");
var tb2 = document.getElementById("ctl00_ContentPlaceHolder1_TextBox_State_19");
tb2.value = tb1.value;
}
</script>
Of course, this works fine for the actual "transfer" of data from the drop down to textbox, but it never gets executed. Usually I would execute the function "onclick" in the HTML, but I cannot do that. Is there another way to "listen" for a click on that dropdown?
Just register the handler:
document.getElementById("yourdropdownID").onchange = replicate;
can you use JQuery? Link to JQuery (like all javascrip files) and do the following in a script tag somewhere (or add to your current script tag.
<script>
$(document).ready(function(){
//Use the ID of the control here:
$("#ct100_ContentPlaceHolder1_DropDownList_Country_17").change(function(){
replicate();
});
});
<script>

JavaScript: changing the value of onclick with or without jQuery

I'd like to change the value of the onclick attribute on an anchor. I want to set it to a new string that contains JavaScript. (That string is provided to the client-side JavaScript code by the server, and it can contains whatever you can put in the onclick attribute in HTML.) Here are a few things I tried:
Using jQuery attr("onclick", js) doesn't work with both Firefox and IE6/7.
Using setAttribute("onclick", js) works with Firefox and IE8, but not IE6/7.
Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return is code passed to eval().
Anyone has a suggestion on to set the onclick attribute to to make this work for Firefox and IE 6/7/8? Also see below the code I used to test this.
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var js = "alert('B'); return false;";
// Set with JQuery: doesn't work
$("a").attr("onclick", js);
// Set with setAttribute(): at least works with Firefox
//document.getElementById("anchor").setAttribute("onclick", js);
});
</script>
</head>
<body>
Click
</body>
</html>
You shouldn't be using onClick any more if you are using jQuery. jQuery provides its own methods of attaching and binding events. See .click()
$(document).ready(function(){
var js = "alert('B:' + this.id); return false;";
// create a function from the "js" string
var newclick = new Function(js);
// clears onclick then sets click using jQuery
$("#anchor").attr('onclick', '').click(newclick);
});
That should cancel the onClick function - and keep your "javascript from a string" as well.
The best thing to do would be to remove the onclick="" from the <a> element in the HTML code and switch to using the Unobtrusive method of binding an event to click.
You also said:
Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return in code passed to eval().
No - it won't, but onclick = eval("(function(){"+js+"})"); will wrap the 'js' variable in a function enclosure. onclick = new Function(js); works as well and is a little cleaner to read. (note the capital F) -- see documentation on Function() constructors
BTW, without JQuery this could also be done, but obviously it's pretty ugly as it only considers IE/non-IE:
if(isie)
tmpobject.setAttribute('onclick',(new Function(tmp.nextSibling.getAttributeNode('onclick').value)));
else
$(tmpobject).attr('onclick',tmp.nextSibling.attributes[0].value); //this even supposes index
Anyway, just so that people have an overall idea of what can be done, as I'm sure many have stumbled upon this annoyance.
One gotcha with Jquery is that the click function do not acknowledge the hand coded onclick from the html.
So, you pretty much have to choose. Set up all your handlers in the init function or all of them in html.
The click event in JQuery is the click function $("myelt").click (function ....).
just use jQuery bind method !jquery-selector!.bind('event', !fn!);
See here for more about events in jQuery
If you don't want to actually navigate to a new page you can also have your anchor somewhere on the page like this.
<a id="the_anchor" href="">
And then to assign your string of JavaScript to the the onclick of the anchor, put this somewhere else (i.e. the header, later in the body, whatever):
<script>
var js = "alert('I am your string of JavaScript');"; // js is your string of script
document.getElementById('the_anchor').href = 'javascript:' + js;
</script>
If you have all of this info on the server before sending out the page, then you could also simply place the JavaScript directly in the href attribute of the anchor like so:
Click me
Note that following gnarf's idea you can also do:
var js = "alert('B:' + this.id); return false;";<br/>
var newclick = eval("(function(){"+js+"});");<br/>
$("a").get(0).onclick = newclick;
That will set the onclick without triggering the event (had the same problem here and it took me some time to find out).
Came up with a quick and dirty fix to this. Just used <select onchange='this.options[this.selectedIndex].onclick();> <option onclick='alert("hello world")' ></option> </select>
Hope this helps

Categories

Resources