Adding paramaters for an onclick function inside an element - javascript

Hey guys I'm having an issue with the syntax of providing a parameter for a function that I call on an onclick event inside a div.
I can get the function open_email() to call but not when I add a parameter since the parameter I am looking to add is obtained from another form element and I'm not sure how to type it properly.
Below is my code. Please let me know if you know how it should be written. I'm currently getting nothing to happen unless I keep the parameters (arguments) blank.
To clarify, I need to know how to add emails[index].id as an argument for the function below that is called open_email(). What is the proper syntax? I tried : open_email(emails[index].id) and open_email("emails[index].id")
for (index = 0; index < emails.length; index++) {
if (emails[index].read == false) {
element.innerHTML += '<div class="emails unread" onclick="open_email();">' + "From:" + JSON.stringify(emails[index].sender) +
"<p class='subject'>" + "Subject: " + JSON.stringify(emails[index].subject) + "</p>" + JSON.stringify(emails[index].timestamp) + '</div>';
} else {
element.innerHTML += '<div class="emails">' + "From:" + JSON.stringify(emails[index].sender) +
"<p>" + "Subject: " + JSON.stringify(emails[index].subject) + "</p>" + JSON.stringify(emails[index].timestamp) + '</div>';
}

Yes, you can. You need to send an arrow function there. Try to click on the text "Initial Content".
I do not have your open_email function, so I made up one as an example.
Basically, onclick will execute () => open_email(emailIndexId):
<div id="text">Initial Content</div>
<script>
textDiv = document.getElementById('text');
const open_email = id => {
textDiv.innerText = "Sent email to " + id;
}
const emailIndexId = 33;
textDiv.onclick = () => open_email(emailIndexId) // IMPORTANT
</script>

Related

Declaring an empty element before insertAdjacentHTML

Hi I have a simple question, do I need to specify lblWelcomeUserMessage.innerHTML = ""; ( see below in code ) in the following function before insertAdjacentHTML on it ? It actually works as it is without declaring it, but I want to know what is the optimal approach ?
// Dynamic HTML / user interface for ALL users
function showWelcomeMessage() {
//lblWelcomeUserMessage.innerHTML = "";
var sWelcomeUserMessage = '<h3>' + 'Welcome:' + ' ' + sessionStorage.getItem( 'name' ) +
' ' + sessionStorage.getItem( 'lastname' ) + ' ' + sessionStorage.getItem( 'role' ) + ' </h3>';
var iUserImage = '<img src=" ' + sessionStorage.getItem( 'image' ) + ' " width="50px">';
lblWelcomeUserMessage.insertAdjacentHTML( 'beforeend', sWelcomeUserMessage + iUserImage );
}
It depends on what you want to do.
If you are calling showWelcomeMessage function more than once then
you need to set it to empty lblWelcomeUserMessage.innerHTML = ""
function showWelcomeMessage() {
lblWelcomeUserMessage.innerHTML = "";
var sWelcomeUserMessage = '<h3>' + 'Welcome:' + ' ' + sessionStorage.getItem( 'name' ) +
' ' + sessionStorage.getItem( 'lastname' ) + ' ' + sessionStorage.getItem( 'role' ) + ' </h3>';
var iUserImage = '<img src=" ' + sessionStorage.getItem( 'image' ) + ' " width="50px">';
lblWelcomeUserMessage.insertAdjacentHTML( 'beforeend', sWelcomeUserMessage + iUserImage );
}
setInterval(showWelcomeMessage,4000);
OR
Otherwise you can remove lblWelcomeUserMessage.innerHTML = ""; from
above code
insertAdjacentHTML inserts some HTML around a node (lblWelcomeUserMessage, which you should have get before with something like lblWelcomeUserMessage = document.getElementById('welcome_tag')).
Setting it's inner content to an empty string is not really necessary, unless you want to clear it. It's rather a design issue than a programmatic one.
Optimal approach for what?
By the way based on MDN:
https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
insertAdjacentHTML() parses the specified text as HTML or XML and
inserts the resulting nodes into the DOM tree at a specified position.
It does not reparse the element it is being used on and thus it does
not corrupt the existing elements inside that element. This avoids the
extra step of serialization, making it much faster than direct
innerHTML manipulation.
So it's basically depends on your needs. If you want to replace previous message you just add the lblWelcomeUserMessage.innerHTML = ""; , if you want to show all previous message just comment that code.

WinJS forward custom object to print function

I use WinJS in my application and try to print some content. Made my printer class according to this tutorial https://dzone.com/articles/windows-8-print-contract-%E2%80%93.
function registerForPrintContract(participiantData) {
var printManager = Windows.Graphics.Printing.PrintManager.getForCurrentView();
printManager.addEventListener("printtaskrequested", onPrintTaskRequested, false);
}
function onPrintTaskRequested(printEvent) {
var printTask = printEvent.request.createPrintTask("Print Example", function (args) {
printCurrentPage(args);
printTask.oncompleted = onPrintTaskCompleted;
});
}
function printCurrentPage(args) {
var docHtml = document.createDocumentFragment();
docHtml.appendChild(createDocumentContent());
args.setSource(MSApp.getHtmlPrintDocumentSource(docHtml));
}
function createDocumentContent() {
var container = document.createElement("div");
container.innerHTML = "<h2>" + firstname + " " + lastname + "</h2>" +
"<h4>" + emailaddress1 + "<h4>";
return container;
}
function showPrintUI() {
Windows.Graphics.Printing.PrintManager.showPrintUIAsync();
}
My problem is that I do not know how to forward some object data to createDocumentContent() function. In this example I put firstname, lastname and email. Those data I cannot get from html page I need to send them on print button click.
All examples I saw are about printing current page or making new content from data which we can get from HTML page by querying DOM, no example where I can send custom object.
What is the best way to do this ?
My problem is that I do not know how to forward some object data to createDocumentContent() function. In this example I put firstname, lastname and email. Those data I cannot get from html page I need to send them on print button click.
Do you mean you want to put the html output of "<h2>"+firstname + " " +lastname+"</h2>"+"<h4>" + emailaddress1 + "<h4>" to your print page?
The behavior of innerHTML has changed in Windows Store App Development.
see HTML and DOM API changes list innerHTML section:
Content is filtered as through it was processed by the toStaticHTML method
But WinJS offers a method that you can utilize to inject HTML.
Here is the link to documentation of this method: WinJS.Utilities.insertAdjacentHTML
Here is a code snippet that shows a simple use this method:
function createDocumentContent() {
var obj = {
firstname: "winffee",
lastname: "xia",
emailaddress1:"test#126.com"
}
var htmlString = "<h2>" + obj.firstname + " " + obj.lastname + "</h2>" +
"<h4>" + obj.emailaddress1 + "<h4>";
var container = document.createElement("div");
WinJS.Utilities.insertAdjacentHTML(container, "beforeend", htmlString);
return container;
}

Why is this JavaScript parameter getting lost?

In this function, the value parameter is being passed down to fill in my URL. This works perfectly.
function showResults(results) {
var html = '';
$.each(results, function(index,value) {
html += '<li><img src="' + value.snippet.thumbnails.medium.url + '">' + value.snippet.title + '(More from ' + value.snippet.channelTitle + ')</li>';
});
$('#results').html(html);
}
In this nearly identical function, the value param loses its value. I can't see how. It's difficult to debug why this is happening because console.log() just returns "ReferenceError: $ is not defined" no matter what I check (it returns this in the first section too, which works well).
function showResults(results) {
var html = '';
$.each(results, function(index,value) {
html += '<li><img src="' + value.snippet.thumbnails.medium.url + '">' + value.snippet.title + ') </li>';
});
$('#results').html(html);
$('#results li a').click(function(){
playVid($(this).attr(value.id.videoId));
});
}
function playVid(vidID) {
var embedVid = 'https://www.youtube.com/embed/'+vidID+'?autoplay=1';
document.getElementById('player').src = embedVid;
}
Here I'm trying to push the value param (in the url again) to an iframe with id="player". The iframe receives an invalid param and the video won't play. Meanwhile the video plays in the first example. Where does value get lost?
value only exists within the scope of the each loop. So, first fix your reference error, and then I suggest the following changes in that second example:
1) Update the href with the videoId value in the each loop like in the first example:
<a href="https://www.youtube.com/watch?v=' + value.id.videoId + '">
2) And then launch the player with that value:
$('#results li a').click(function(e) {
e.preventDefault();
playVid($(this).attr('href'));
});

Limit number of Dynamic list Items in a Function

I would like to achieve 2 things with this Code I have been working on so not sure if to separate the Questions:
JS:
function listPosts(data) {
postlimit =
var output='<ul data-role="listview" data-filter="true">';
$.each(data.posts,function(key,val) {
output += '<li>';
output += '<a href="#devotionpost" onclick="showPost(' + val.id + ')">';
output += '<h3>' + val.title + '</h3>';
output += '<p>' + excerpt + '</p>';
output += '</a>';
output += '</li>';
}); // go through each post
output+='</ul>';
$('#postlist').html(output);
} // lists all the posts
Questions:
1: I would like to limit the number of Dynamic List Posts returned to 8
2: While I limit the displayed items, I want to add a 'More...' text at the bottom so another set of 8 items is appended to already displayed list.
I am already trying out some codes but was hoping to get some guidance
function listPosts(data, postlimit) {
var $output = $('<ul class="posts" data-role="listview" data-filter="true">');
$.each(data.posts,function(key, val) {
$("<li>", {id: "post_" + val.id})
.append([
$("<h3>", {text: val.title}),
$("<p>", {text: val.excerpt})
])
.appendTo($output);
return (postlimit-- > 1);
});
$('#postlist').empty().append($output);
}
// exemplary delegated event handler
$(document).on("click", "ul.posts h3", function () {
$(this).show();
});
later ...
listPosts(data, 8);
Notes:
from $.each() you can return true or false. If you return false, the loop stops.
Try not to build HTML from concatenated strings. This is prone to XSS vulnerabilities that are easy to avoid. jQuery gives you the tools to build HTML safely.
Generally, for the same reason, try to avoid working with .html(), especially if you already have DOM elements to work with.
Don't use inline event handlers like onclick. At all. Ever.
I am answering you on basis of pure logic and implementation of logic. there could be API stuff for it , but I don't really know. Secondly; It would be a good solution to find some jQuery plugin if you don't have any problems with using jQuery.
call the function onMoreClick() upon clicking the More... html item
var end = 8;
var start = 1;
function onMoreClick()
{
start = end
end = end+8;
listPosts(data)
}
function listPosts(data) {
postlimit =
var output='<ul data-role="listview" data-filter="true">';
var i = start;
$.each(data.posts,function(key,val) {
if(i<end && i >=start){
output += '<li>';
output += '<a href="#devotionpost" onclick="showPost(' + val.id + ')">';
output += '<h3>' + val.title + '</h3>';
output += '<p>' + excerpt + '</p>';
output += '</a>';
output += '</li>';
i++;
}
}); // go through each post
output+='</ul>';
$('#postlist').html(output);
} // lists all the posts

Put javascript on page from code behind

I have some other javascript functions that are being set on the onfocus and onblur events of the textbox that I am using. In these functions it calls a generic javascript function that is not related to any controls. I want to know how to just simply spit this function out to the html of the page from the code behind. Something like this...
Page.ClientScript.RegisterStartupScript(this.GetType(), "?????", getCounter);
EDIT: Here is what I mean
public class MVADTextBox : TextBox
{
protected override void OnLoad(EventArgs e)
{
var getCounter = "<script language=\"javascript\">" +
"function GetCounter(input) {" +
//this function gets the number of special characters taht are in a row.
//it is only the grouping of characters that are right after your current position
"var textbox = document.getElementById(input.id);" +
"var mask = textbox.getAttribute('Mask');" +
"var inputCharacters = textbox.getAttribute('InputCharacters');" +
"var tbid = \"#\" + input.id;" +
"var position = $(tbid).caret().start;" +
"var counter = 0;" +
"for (var i = position; i < mask.length; i++) {" +
" if (mask[i] != '#') {" +
" counter++;" +
" if (mask[i + 1] == '#') {" +
" break;" +
" }" +
" }" +
"}" +
"return counter;" +
" }" +
"</script>";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OnFocus", onFocus);
Page.ClientScript.RegisterStartupScript(this.GetType(), "GetCounter(input)", getCounter);
var onBlur = "<script language=\"javascript\"> function PopulateField(input) {if (input.value == \"\") {input.value = input.defaultValue; input.className = 'sampleText'; } } </script>";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OnFocus", onFocus);
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OnBlur", onBlur);
}
}
The on blur method is getting sent to the page.
Answer:
I believe that Page.ClientScript has been deprecated. You should be using ClientScriptManager.
Replace your "?????" with the name of the script. Honestly, the name of the script is almost useless (unless you need to check for its existence later on).
ClientScriptManager.RegisterStartupScript(this.GetType(), "myCount", getCounter);
Usage Clarification:
//You must surround your code with script tags when not passing the bool param
ClientScriptManager.RegisterStartupScript(this.GetType(),
"myCount",
"<script>alert('Hey')</script>");
// The last param tells .Net to surround your
// code with script tags (true) or not (false)
ClientScriptManager.RegisterStartupScript(this.GetType(),
"myCount",
"alert('Hey')", true);
Additional Information:
Signatures from MSDN:
public void RegisterStartupScript(
Type type,
string key,
string script
)
public void RegisterStartupScript(
Type type,
string key,
string script,
bool addScriptTags
)
See: http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx
I think you need to use the ClientScriptManager.RegisterClientScriptBlock method
Try this
EDITED:
var getCounter = "<script language=\"javascript\">" +
"function GetCounter(input) {" +
//this function gets the number of special characters taht are in a row.
//it is only the grouping of characters that are right after your current position
"var textbox = document.getElementById(input.id);" +
"var mask = textbox.getAttribute('Mask');" +
"var inputCharacters = textbox.getAttribute('InputCharacters');" +
"var tbid = \"#\" + input.id;" +
"var position = $(tbid).caret().start;" +
"var counter = 0;" +
"for (var i = position; i < mask.length; i++) {" +
" if (mask[i] != '#') {" +
" counter++;" +
" if (mask[i + 1] == '#') {" +
" break;" +
" }" +
" }" +
"}" +
"return counter;" +
" }" +
"</script>";
this.TextBox1.Attributes.Add("OnFocus", "GetCounter(this);");
if (!ClientScript.IsClientScriptBlockRegistered("getCounter")) {
ClientScript.RegisterClientScriptBlock(this.GetType(), "getCounter", getCounter, false);
}
You would put the actual function definition, which you already have in getCounter. Note that the second parameter which you currently have as "????", as James pointed out, is for the script's key, which must be unique from all other scripts registered for this type. The third parameter is the script itself, and the fourth determines whether script tags are to be added, which needs to be false, since you already added them.
Page.ClientScript.RegisterStartupScript(this.GetType(),
"someKeyForThisType", getCounter, false);

Categories

Resources