Javascript to pre-select row 1 of html table on page load - javascript

I am using the following JavaScript code (found on Stackoverflow) to populate a div id ='article_title' from a cell value chosen from a table on the page.
The issue I am having is that the code does not run automatically on page load - unless I click on the table.
I would like to:
retain the existing functionality ie run the code on clicking a row on the table
But I also want to:
run the code on page load using row 1 (or any random row) from the table.
<script>
(function () {
if (window.addEventListener) {
window.addEventListener('load', run, false);
} else if (window.attachEvent) {
window.attachEvent('onload', run);
}
function run() {
var t = document.getElementById('table_id');
t.onclick = function (event) {
event = event || window.event; //IE8
var target = event.target || event.srcElement;
while (target && target.nodeName != 'TR') {
target = target.parentElement;
}
var cells = target.cells;
if (!cells.length || target.parentNode.nodeName == 'THEAD') {
return;
}
var article_title = cells[11].innerHTML;
//Assign Article Title to text box
let h4 = document.createElement('h4');
h4.textContent = article_title;
document.getElementById("article_title").innerHTML = "";
document.getElementById("article_title").appendChild(h4);
document.getElementById("article_title").style.color='black'
};
}
})();
</script>

Used the solution offered by #coderLMN to build the following code and add to the body section of the page. This works now:
<script>
window.onload = function() {
var table = document.getElementById('table_id');
var article_title = table.rows[1].cells[11].innerHTML;
//Assign Article Title to text box
let h4 = document.createElement('h4');
h4.textContent = article_title;
document.getElementById("article_title").innerHTML = "";
document.getElementById("article_title").appendChild(h4);
document.getElementById("article_title").style.color='black'
}
</script>

Related

how to show the sub elements text based on div>a like the select>option structure in a drop-down box using original javascript

everyone. I got some problems when I wanna accomplish a drop-down box in a HTML website without using select and option elements, instead of using and elements.
The main function is made up by two parts, the first function is when clicked the first elements in the drop-down box, the hidden parts of list shows up and hide clicked again. The second function is when choose the elements in the hidden list, the text of the elements on the list will replace the first element on the drop-down box.
I have accomplished first function using below codes:
// javascript codes
var searchListBtn = document.getElementById("btn_List");
var a_searchListBtn = document.getElementById("btn_List").getElementsByTagName("a");
function show(event) {
let oevent = event || window.event;
if (document.all) {
oevent.cancelBubble = true;
}
else {
oevent.stopPropagation();
}
// click it to show it, click again to hide it and loop
if (searchListBtn.style.display === "none" || searchListBtn.style.display === "") {
searchListBtn.style.display = "block";
}
else {
searchListBtn.style.display = "none";
}
}
document.onclick = function() {
searchListBtn.style.display = "none";
}
searchListBtn.onclick = function (event) {
let oevent = event || window.event;
oevent.stopPropagation();
}
<!-- html codes -->
<html>
<body>
<div>
<div class="ui-search-selected" onclick="show();">A</div>
<div class="ui-search-selected-list" id="btn_List">
B
C
D
</div>
</div>
</body>
</html>
But when I did the second part, my idea was not clear enough to implement that, I searched if I use select>option elements I could use selectedIndex method to find the index of list, but this is a custom drop-down box formed by div>a structure elements.
I tried to console.log(a_searchListBtn) and show an array from the console, and I could use a_searchListBtn[0~3].text to get the value of B/C/D.
I tried to write codes like below:
a_searchListBtn.onclick = function() {
console.log("Clicked.")
}
But nothing in the console, so, is there anyone could apply some help, thx in advance.
Well you're fetching all the a elements using getElementsByTagName("a"). Now you just need to loop through the results and add a click event listener that will take the innerHTML of that a element and put it into the innerHTML of the ui-search-selected div.
You don't need an index. You can access the clicked element's innerHTML using event.target. See it working in this snippet below:
// javascript codes
var searchListBtn = document.getElementById("btn_List");
var uiSearchSelected = document.getElementById("ui-search-selected");
var a_searchListBtn = document.getElementById("btn_List").getElementsByTagName("a");
for (button of a_searchListBtn) {
button.addEventListener("click", replace);
}
function show(event) {
let oevent = event || window.event;
if (document.all) {
oevent.cancelBubble = true;
}
else {
oevent.stopPropagation();
}
// click it to show it, click again to hide it and loop
if (searchListBtn.style.display === "none" || searchListBtn.style.display === "") {
searchListBtn.style.display = "block";
}
else {
searchListBtn.style.display = "none";
}
}
document.onclick = function() {
searchListBtn.style.display = "none";
}
searchListBtn.onclick = function (event) {
let oevent = event || window.event;
oevent.stopPropagation();
}
function replace(event) {
if (!event) return;
uiSearchSelected.innerHTML = event.target.innerHTML
}
<!-- html codes -->
<html>
<body>
<div>
<div id="ui-search-selected" onclick="show();">A</div>
<div class="ui-search-selected-list" id="btn_List">
B
C
D
</div>
</div>
</body>
</html>
I have tried to use this codes to implement this funtion, it works.
// javascript
var par_searchListBtn = document.getElementById("btn_list_parent");
var searchListBtn = document.getElementById("btn_List");
var a_searchListBtn = document.getElementById("btn_List").getElementsByTagName("a");
// console.log(a_searchListBtn.length);
// console.log(a_searchListBtn);
function show(event) {
let oevent = event || window.event;
if (document.all) {
oevent.cancelBubble = true;
}
else {
oevent.stopPropagation();
}
if (searchListBtn.style.display === "none" || searchListBtn.style.display === "") {
searchListBtn.style.display = "block";
}
else {
searchListBtn.style.display = "none";
}
}
document.onclick = function() {
searchListBtn.style.display = "none";
}
searchListBtn.onclick = function (event) {
let oevent = event || window.event;
oevent.stopPropagation();
}
for(var i = 0; i < a_searchListBtn.length; i++){
a_searchListBtn[i].onclick = function () {
par_searchListBtn.innerHTML = this.innerText;
//searchListBtn.style.display = "none";
}
}
<!-- html codes -->
<html>
<body>
<div>
<div class="ui-search-selected" id="btn_list_parent" onclick="show();">A</div>
<div class="ui-search-selected-list" id="btn_List">
B
C
D
</div>
</div>
</body>
</html>

Copy to clipboard buttons

I want to create "copy to clipboard" buttons to work on our sharepoint. They should be placed in a few different places, and what I need to copy is some text from from a specific field on the page (ex. a list of emails).
I know, I can just select the text and copy it, but we do it quite often, so having a button that automatically copies the text to the clipboard would be very useful.
I did manage to create one in a Script Editor, where I pasted the whole code below (which I found on the internet)
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
document.getElementById("copyButton").addEventListener("click", function() {
copyToClipboardMsg(document.getElementById("copyTarget"), "msg");
});
document.getElementById("copyButton2").addEventListener("click", function() {
copyToClipboardMsg(document.getElementById("copyTarget2"), "msg");
});
document.getElementById("pasteTarget").addEventListener("mousedown", function() {
this.value = "";
});
function copyToClipboardMsg(elem, msgElem) {
var succeed = copyToClipboard(elem);
var msg;
if (!succeed) {
msg = "Copy not supported or blocked. Press Ctrl+c to copy."
} else {
msg = "Text copied to the clipboard."
}
if (typeof msgElem === "string") {
msgElem = document.getElementById(msgElem);
}
msgElem.innerHTML = msg;
setTimeout(function() {
msgElem.innerHTML = "";
}, 2000);
}
function copyToClipboard(elem) {
// create hidden text element, if it doesn't already exist
var targetId = "_hiddenCopyText_";
var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
var origSelectionStart, origSelectionEnd;
if (isInput) {
// can just use the original source element for the selection and copy
target = elem;
origSelectionStart = elem.selectionStart;
origSelectionEnd = elem.selectionEnd;
} else {
// must use a temporary form element for the selection and copy
target = document.getElementById(targetId);
if (!target) {
var target = document.createElement("textarea");
target.style.position = "absolute";
target.style.left = "-9999px";
target.style.top = "0";
target.id = targetId;
document.body.appendChild(target);
}
target.textContent = elem.textContent;
}
// select the content
var currentFocus = document.activeElement;
target.focus();
target.setSelectionRange(0, target.value.length);
// copy the selection
var succeed;
try {
succeed = document.execCommand("copy");
} catch(e) {
succeed = false;
}
// restore original focus
if (currentFocus && typeof currentFocus.focus === "function") {
currentFocus.focus();
}
if (isInput) {
// restore prior selection
elem.setSelectionRange(origSelectionStart, origSelectionEnd);
} else {
// clear temporary content
target.textContent = "";
}
return succeed;
}
}//]]>
</script>
</head>
<body>
<input id="copyTarget" value="Some initial text"> <button id="copyButton">Copy</button><br><br>
<span id="copyTarget2">Some Other Text</span> <button id="copyButton2">Copy</button><br><br>
<input id="pasteTarget"> Click in this Field and hit Ctrl+V to see what is on clipboard<br><br>
<span id="msg"></span><br>
</body>
</html>
But we have main problems with it:
1) it reloads the page every time we click the "copy" button
2) it is not very elegant and friendly, when we think about updating our documents
I would be very grateful for any hints you may have for me, on how to make it work better.
This project may help: clipboardjs

Call script from another script

In HTML5 I have a dropdown menu . When choosing different options I hide or show different parts of my page. Here is that script:
document
.getElementById('target')
.addEventListener('change', function () {
'use strict';
var vis = document.querySelector('.vis'),
target = document.getElementById(this.value);
if (vis !== null) {
vis.className = 'inv';
}
if (target !== null ) {
target.className = 'vis';
}
});
However what I want to do now, in another script is to preload an option from the dropdown. I can do it easily with this script:
setSelectedIndex(document.getElementById('target'),'content_1');
function setSelectedIndex(s, valsearch)
{
// Loop through all the items in drop down list
for (i = 0; i< s.options.length; i++)
{
if (s.options[i].value == valsearch)
{
// Item is found. Set its property and exit
s.options[i].selected = true;
break;
}
}
return;
}
This is where my problem comes up, my dropdow will get the value I want, but the part that I want to be shown when choosing that option won't come up.
That is because change events need to happen from the browser.
When the user commits the change explicitly (e.g. by selecting a value
from a 's dropdown with a mouse click, by selecting a date
from a date picker for , by selecting a file in the
file picker for , etc.);
If your using Jquery you can:
$("#id").val("value").trigger('change');
or you can use javascript if your not worried about building the event object:
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
element.dispatchEvent(evt);
}
else
element.fireEvent("onchange");
I would recommend moving your anonymous onchange function into a named function that you can call once onload, and again onchange.
Here is the function I wrote:
function setContent(id) {
//get the current visible content
var vis = document.querySelector('.vis');
//get the target element by id
var target = document.getElementById(id);
//make current vis element inv
if (vis) vis.className = "inv";
//make target element vis
if (target) target.className = 'vis';
}
and a fiddle
edited: got rid of querySelectorAll to stick closer to OP original code and updated fiddle. clarified and commented code.
The problem you have is changing a vale or the selected value of an input with JavaScript does not trigger any change event. So you would need to manually trigger the event.
function setSelectedIndex(s, valsearch)
{
// Loop through all the items in drop down list
for (i = 0; i< s.options.length; i++)
{
if (s.options[i].value == valsearch)
{
// Item is found. Set its property and exit
s.options[i].selected = true;
break;
}
}
//Setting the selected value with JavaScript does not trigger the change event so you need to manually trigger the change event
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
s.dispatchEvent(evt);
} else {
s.fireEvent("onchange");
}
return;
}

How to send Gmail talk messages using Gmails built it method

I want to create a Google Chrome extension that, among other things, will modify the chat text based on what is inputed. I will add a button next to the video, call, and add people buttons below the name, and when clicked will activate the modifications. I don't want to have to put any more scripts on the page than I have to, so I would like to be able to send the messages the way Gmail would be pressing "return" in the chat box. Also I want to to be able to show that both of the people chatting are using my extension by displaying text in the chat box just like the "This chat is off the record" text is, and possibly if both are using it add extra stuff to the chat. What I tried to do was make an imitation textarea and when the user 'sends' it, grab it and modify it, then insert it into the real one and send the new text. I can change the text but can't seem to send it...
Heres what I have so far, I enclosed everything in a setInterval to check if chat box exists and add appropriate stuff to it:
var chatBtnClone = setInterval(function() {
if ($("body").find(".nH .NG").length > 0) { //if chat is active
var clone = $("body").find(".nH .NG .NJ").first();
if (clone.children()[0].className.indexOf("chat") < 0) { //if already added my class
var clonned = clone.clone();
var clonnedChd = clonned.children().first();
clonnedChd.attr("title", "Start encrypted chat");
clonnedChd.on('click', function() {
console.log("clicked chatBtn!"); //make sure it works
var self = $(this);
if (self[0].className.indexOf("chatEncX") >= 0) { //toggle button pic
self.removeClass('chatEncX').addClass('chatEnc');
self.attr("title", "Stop encrypted chat");
} else {
self.removeClass('chatEnc').addClass('chatEncX');
self.attr("title", "Start encrypted chat");
}
});
clone.parent().prepend(clonned);
clonned.find('.NK').removeClass("NK-Y8").addClass("chatEncX");
}
var chatBoxs = $('body').find(".nn .AD");
var chatArea = chatBoxs.first().find(".nH textarea"); //get chat textareas
if (chatArea.length === 1) {
var clonChatArea = chatArea.first().clone();
clonChatArea.removeAttr("id");
chatArea.first().parent().append(clonChatArea);
// chatArea.first().hide();
var chatTextDiv = chatBoxs.first().find(".jp .nH .nH").first();
clonChatArea.focusin(function() {
chatTextDiv.removeClass("gv").addClass("f7");
});
clonChatArea.focusout(function() {
chatTextDiv.removeClass("f7").addClass("gv");
});
clonChatArea.on('keyup', function(event) {
var self = this;
//console.log(this.style.height); //make sure height it working
if (self.scrollHeight === 38) {
self.style.overflowY = "hidden";
self.style.height = "36px";
} else if (self.scrollHeight === 47) {
self.style.height = "54px";
} else if (self.scrollHeight === 62) {
self.style.height = "72px";
} else if (self.scrollHeight >= 77) {
self.style.height = "80px";
self.style.overflowY = "scroll";
}
if( event.keyCode === 13 && event.shiftKey ){
//regular, just insert a newline
} else if (event.keyCode === 13) {
//grab text and modify then reinsert into real textarea
var chatTxt = $(this).val();
var chatHidden = chatBoxs.first().find(".nH textarea").first();
var chatEncTxt = Crypto.AES.encrypt(chatTxt, "pass"); //modify text
//console.log(chatEncTxt);
chatHidden.val(chatEncTxt);
chatHidden.focus();
chatHidden.trigger({ type : 'keypress', which : 13 }); //try to imitate the return key and send (NOT WORKING!!!)
// $(this).focus();
}
});
}
}
},150);
This might be a bit late, but if anyone else is interested then I managed this by doing the following:
var e = new Event("keypress");
e.keyCode = e.which = 13;
// :mc is an example textarea id, but the OP has the code for finding that already
document.getElementById(':mc').dispatchEvent(e);

jJavascript select box hanging on second select in IE7

I have a drop down select box inside a div. When the user clicks on change, a dropdown box appears next to the change/submit button and the user makes a selection which then updates the database and the selection appears instead of the dropdown. All works fine in IE8 and Firefox but in IE7 it allows one selection (there are several identical dropdowns) but the second time a selection is made it hangs on "please wait". This is the relevant code:
<td width=200>
<input type="button" onclick="startChanging(this)" value="Change" /></td>
<script type="text/javascript">
var selectBox, isEditing = false;
var recordvalue;
if( window.XMLHttpRequest ) {
recordvalue = new XMLHttpRequest();
} else if( window.ActiveXObject ) {
try {
recordvalue = new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) {}
}
window.onload = function () {
selectBox = document.getElementById('changer');
selectBox.id = '';
selectBox.parentNode.removeChild(selectBox);
};
function startChanging(whatButton) {
if( isEditing && isEditing != whatButton ) { return; } //no editing of other entries
if( isEditing == whatButton ) { changeSelect(whatButton); return; } //this time, act as "submit"
isEditing = whatButton;
whatButton.value = 'Submit';
var theRow = whatButton.parentNode.parentNode;
var stateCell = theRow.cells[3]; //the cell that says "present"
stateCell.className = 'editing'; //so you can use CSS to remove the background colour
stateCell.replaceChild(selectBox,stateCell.firstChild); //PRESENT is replaced with the select input
selectBox.selectedIndex = 0;
}
function changeSelect(whatButton) {
isEditing = true; //don't allow it to be clicked until submission is complete
whatButton.value = 'Change';
var stateCell = selectBox.parentNode;
var theRow = stateCell.parentNode;
var editid = theRow.cells[0].firstChild.firstChild.nodeValue; //text inside the first cell
var value = selectBox.firstChild.options[selectBox.firstChild.selectedIndex].value; //the option they chose
selectBox.parentNode.replaceChild(document.createTextNode('Please wait...'),selectBox);
if( !recordvalue ) {
//allow fallback to basic HTTP
location.href = 'getupdate.php?id='+editid+'&newvalue='+value;
} else {
recordvalue.onreadystatechange = function () {
if( recordvalue.readyState != 4 ) { return; }
if( recordvalue.status >= 300 ) { alert('An error occurred when trying to update'); }
isEditing = false;
newState = recordvalue.responseText.split("|");
stateCell.className = newState[0];
stateCell.firstChild.nodeValue = newState[1] || 'Server response was not correct';
};
recordvalue.open('GET', "getupdate.php?id="+editid+"&newvalue="+value, true);
recordvalue.send(null);
}
}
</script>
If anyone has any idea why this is happening I'd be very grateful
ok managed to solve it. I moved the recordvalue.open line near the bottom inside te last else loop and it works perfectly in all browsers just don't ask me why

Categories