Adding onClick function with Javascript doesn't go through - javascript

So I am trying to add an onClick attribute to a button created with Javascript. Obviously I am using Javascript to add it, however it won't go through because when I inspect the element on the web page it doesn't show an onClick attribute there. This is the code I have to create the button
var buttonExponent = document.createElement('button');
buttonExponent.innerHTML = '^';
buttonExponent.onclick = function(){appendExpr(this.className);}; <---This is my problem
buttonExponent.className = 'button operator ' + expression.id + ' top';
buttonExponent.style.marginTop = '0px';
buttonExponent.style.marginLeft = '-6px';
container.appendChild(buttonExponent);
The rest of the functions work fine and everything, however the onClick attribute simply won't get added on. I have tried doing it multiple ways, but none of them work
EDIT: Figured I should add what the output is on the webpage, the element has this HTML
<button class="button operator expr1 top" style="margin-top: 0px; margin-left: -6px;">^</button>
When it should be looking like this
<button onClick="appendExpr(this.className);" class="button operator expr1 top" style="margin-top: 0px; margin-left: -6px;">^</button>

Modifying the element.onclick DOM property doesn't modify the element's onclick attribute. They are two separate pieces of data, confusingly.
To set the attribute, use element.setAttribute('onclick','code here').

Nvm, the problem was that by setting the onClick through element.onClick I was setting the property without the attribute, and the properties don't show up when inspecting the element on the webpage, so I had to set the attribute for it to show up

Related

Is there a to change the value of an element using JavaScript

I'm trying to change the value of an element on a third-party web page using a JavaScript Add-on to display a hyperlink
I already have the link on the page i would like to be able to click it
I think I'm on the right track using document.getElementById although I'm not sure how to then change the id into a "a href" and then how to pass it back into the value.
Sorry, this is a bit of a tricky situation so I'll try my best to explain it. On a third-party web-page which we use for our HR related tasks, there is a section titled "File Link" although this isn't a link. When you copy and paste the address into a browser it displays the file. What i am trying to do is create a hyperlink on the "File Link" section to remove the need to copy and paste the link. Because this is a third party website. We have access to the JavaScript on the website and need to change the address into a hyperlink. I'm not entirely sure this is possible.The element id is "__C_cb_file_link" and i would like to insert the link address into the element using a variable then add the link parameters into the variable then reinsert it into the element/value.
function linkIt() {
var intoLink = document.getElementById("__C_cb_file_link");
var hLink = "<a href="+intoLink+"</a>;
intoLink.value = hLink;
}
window.onload = linkIt();
<td><div class="sui-disabled" title="">m-files://view/37FF751C-A23F-4233-BD8B-243834E67731/0-46524?object=C46A7624-D24B-45F3-A301-5117EFC1F674</div>
<input type="hidden" name="__C_cb_file_link" id="__C_cb_file_link" value="m-files://view/37FF751C-A23F-4233-BD8B-243834E67731/0-46524?object=C46A7624-D24B-45F3-A301-5117EFC1F674"/></td></tr>
In below code first we read input value with new link (however we can read this value from other html tags), then we remove this element (and button) and add to parent element (of removed input) the new link
function linkIt() {
let intoLink = __C_cb_file_link.value;
let parent = __C_cb_file_link.parentNode;
__C_cb_file_link.remove();
btn.remove();
parent.innerHTML += `${intoLink}`;
}
<input id="__C_cb_file_link" value="https://example.com">
<button id="btn" onclick="linkIt()">Link It</button>
There are a number of issues with your code:
1) The code snippet in your question doesn't run because of a missing " at the end of the second line of the linkIt() function.
2) intoLink is a hidden field so anything you add to it will not be visible in the page
3) Even if point 2 were not true, setting the value of a form field will not cause HTML to appear on the page (at best you might get some plain text in a textbox).
4) "<a href="+intoLink+"</a>" doesn't work because intoLink is a complex object which represents the entire hidden field element (not just its value property). You can't convert a whole object into a string directly. You need to extract the value of the field.
A better way to do this is by creating a new element for the hyperlink and appending it to the page in a suitable place. Also I recommend not adding your event via onload - when written using this syntax only one onload event can exist in a page at once. Since you're amending another page which isn't under your control you don't want to disable any other load events which might be defined. Use addEventListener instead, which allows multiple handlers to be specified for the same event.
Demo:
function linkIt() {
var intoLink = document.getElementById("__C_cb_file_link");
var hLink = document.createElement("a");
hLink.setAttribute("href", intoLink.value);
hLink.innerHTML = "Click here";
intoLink.insertAdjacentElement('beforebegin', hLink);
}
window.addEventListener('load', linkIt);
<td>
<div class="sui-disabled" title="">m-files://view/37FF751C-A23F-4233-BD8B-243834E67731/0-46524?object=C46A7624-D24B-45F3-A301-5117EFC1F674</div>
<input type="hidden" name="__C_cb_file_link" id="__C_cb_file_link" value="m-files://view/37FF751C-A23F-4233-BD8B-243834E67731/0-46524?object=C46A7624-D24B-45F3-A301-5117EFC1F674" /></td>
</tr>
P.S. m-files:// is not a standard protocol in most browsers, unless some kind of extension has been installed, so even when you turn it into a hyperlink it may not work for everyone.
[UPDATE] I supose that your "__C_cb_file_link" was a paragraph so I get the previous text http://mylink.com and create a link with, is it what you want, right?
function linkIt() {
let fileLink = document.getElementById("__C_cb_file_link");
let hLink = fileLink.textContent;
fileLink.innerHTML = ""+hLink+"";
}
linkIt();
<div>
<p id="__C_cb_file_link">http://myLink.com</p>
</div>

Changing inner HTML of a button with dynamic id

On a project I'm working on, a HTML file is defining a Javascript template used on selection buttons. All buttons have a "Change..." label that I want to localize (set dynamically). In other cases I'm searching for the element ID and setting the InnerHTML accordingly. But in this case, the ID of the buttons are defined dynamically. Is it possible to have a text element inside the button element, search for this element, and set its InnerHTML value?
<script id="optionSelectionTemplate" type="text/x-handlebars-template">
<div class="sub-section option-selection">
{{#if name}}<h4>{{name}}</h4>{{/if}}
<div class="current"></div><button class="button" id="{{id}}" data-action-id="{{id}}">Change...</button>
</div>
</script>
I've been searching this for a while now. But given that my forte is not web development, I'm not really sure what to search for...
You may be able to get the button element(s) by its class instead; for example:
var x = document.getElementsByClassName("button");
As you suggested, you can improve your selection's precision by first getting the 'optionSelectionTemplate' element(s) like so:
var x = document.getElementById("optionSelectionTemplate").getElementsByClassName("button");
Or if you prefer:
var x = document.getElementById("optionSelectionTemplate").getElementsByTagName("button");
Here are some links for more on these method:
https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
https://www.w3schools.com/jsref/met_document_getelementsbytagname.asp
Depending on how dynamic your localization should become, you could also specify the text inside a (locale-dependent) CSS as in https://jsfiddle.net/1gws5kat/ :
[HTML]
<button class="button btn_change" id="{{id}}" data-action-id="{{id}}"></button>
[CSS]
.btn_change:before { content: "Change..."; }
In particular when dealing with a large number of identically-named elements (i.e. many "Change" buttons), this might be pretty handy.
You find those btns by this command:
var btnlist= $(':button')
This Camano get you all button in your html file, then loop ton in and apply your changing.
Before call this command, jquery must be install.

Chrome Extension: Displaying & Hiding Elements?

I'm currently trying to hide a button that is visible on a page, while displaying another one that is automatically hidden (both are on the page, I'm not adding new ones, just changing visibility).
This is how it looks like right now:
<div class="myAwesomeButtons">
<button id="first_button" class="blue_button inset_button" style="">First</button>
<button id="second_button" class="green_button inset_button" style="display: none;">Second</button>
<button id="third_button" class="other_button">Third</button>
</div>
I'm attempting to remove the first button, and remove the style attribute on the second button. How can I achieve this using JavaScript within a Chrome extension?
I already have my manifest.json file in order, but I'm not sure how to go about the rest.
This is what I've tried, but I'm not sure what I'm doing wrong:
function fixButtons() {
document.getElementsByClassName("myAwesomeButtons")[0].style.visibility='hidden';
document.getElementsByClassName("myAwesomeButtons")[1].style.visibility='visible';
}
fixButtons();
function fixButtons() {
var buttonGroup = document.getElementsByClassName("myAwesomeButtons")[0].getElementsByTagName("button");
buttonGroup[0].style.visibility='hidden';
buttonGroup[1].style.visibility='visible';
}
You are mixing up the display and visibility properties.
I avoid using getElementsByClass when possible since it doesn't work with IE. I know this is a Chrome extension though, so it would work. However, since each button already has an ID, I would just use getElementById.
Try
function fixButtons() {
var button1 = document.getElementById("first_button");
button1.style.display= "none";
var button2 = document.getElementById("second_button");
button2.style.display= "inline";
}

Split up and modify an element with jQuery

Here's a confusing question. I need to replace an <input> with a different <input> but I need to preserve the onclick attribute. Here's an example:
<input type="image" class="previous_page_img graybutton mediumbutton" src="btn_prevpage.png" onclick="Add_Search_Param('page', 1); Refine();" alt="">
Since I cannot change the <input> type to a button, I want to replace it with a button, however, I need to preserve the "onclick" attribute. So first, I'd have to break up the element. Replace it with a button and append the original onclick attribute to the new button.
So in the end, I'd have this onclick="Add_Search_Param('page', 1); Refine();" added to the new button. Since the onclick changes, a simple .attr or .prop function would not be sufficient. It must clone the onclick attribute. Can anyone help me? Thanks.
Here's jsFiddle that does not preserve the onclick attribute but does everything else: http://jsfiddle.net/rAMcw/
You could do (i used a simple javascript function to test it)
<input type="image" class="previous_page_img graybutton mediumbutton" src="btn_prevpage.png" onclick="Add_Search_Param('page', 1); Refine();" alt="">
var onclick = $('.mediumbutton').attr('onclick');
var but = $('<input/>', { type: "button", value: "pressme", onclick: onclick});
$('.mediumbutton').replaceWith(but);
fiddle here http://jsfiddle.net/KjBm3/
Just create a new button right after the input, set the input to display: none; (or jQuery('#input').hide()) and have the button onclick trigger the input's onclick (jQuery('#button').click(function(){ jQuery('#input').trigger('click'); });
How about cloning?
var x = $('input').clone(true);
x.attr('type','button').addClass('previous_page_img graybutton mediumbutton').val('Previous Page');
$('input').replaceWith(x);
Updated jsFiddle
What is wrong with turning the existing input element into a button?
$("input.previous_page_img").prop("type", "button").val("Previous Page");
jQuery 1.4.2: (set the property in plain-old JavaScript);
$("input.previous_page_img").val("Previous Page")[0].type = "button";
Demo

Disable link using javascript

I have following HTML and would like to disable the link using javascript.
<a style="white-space: nowrap;" onclick="return InstallWebApp(true);" id="uc_ii_lnkInstall" href="javascript:__doPostBack('uc_ii$lnkInstall','')">
<img style="border-width: 0pt; margin-right: 3px;" id="uc_ii_lnkInstallImg" alt="Install" title="Install" src="/CortexDotNet/pics/buttons/install_g.gif">
Install
</a>
The JavaScript I am using are :
document.getElementById("uc_ii_lnkInstall").disabled = true;
However , it does not work , I could still click this this link after I have disabled the link using the above javascript.I look at the html , it does not seem to have the disable attribute in the a tag.Can anyone help me to explain this please?
document.getElementById("uc_ii_lnkInstall").onclick = function() { return false; };
The return value of false in the old-style event handler prevents the default action (i.e. loading the javascript: URL).
If you want to gray out the image link, you would also need to swap out the image's src URL with one pointing to a grayed-out version of the icon and change the text's color using .style.color = "gray";.
I don't think the 'disable' attribute will work on links, it work mostly on form elements such as inputs, textarea, button, etc.
But as #idealmachine said normal links <a> can be disabled by returning false 'return false' in javascript/jquery.
For example:
let link_example = document.querySelector("#top-content .view-content a");
link_example.removeAttribute("href");
Here is a short and easy way to disable a link.
<a href="javascript:void(0)" >My link is disabled</a>

Categories