Put javascript on page from code behind - javascript

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);

Related

Adding paramaters for an onclick function inside an element

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>

How can i call two javascript function from c# page both on button click

btnSubmit.OnClientClick = "return Getprodsize('" + hdnprdsize.ClientID + "')";
btnSubmit.OnClientClick = "return formatSpecifications('" + hdnSpecifications.ClientID + "')";
Only one function is called it ignores the other i need both the functions to be called on button click.
please help me
btnSubmit.OnClientClick = "Getprodsize('" + hdnprdsize.ClientID + "');return formatSpecifications('" + hdnSpecifications.ClientID + "')";
To ensure that both functions are called .. discard first function return checking
How about add a middle function to wrap both functions up?
function MiddleWare(hdnprdsizeClientID, hdnSpecificationsClientID){
Getprodsize(hdnprdsizeClientID);
formatSpecifications(hdnSpecificationsClientID);
}
btnSubmit.OnClientClick = "return MiddleWare('" + hdnprdsize.ClientID +",'" + hdnSpecifications.ClientID + "')";
If you don’t do anything this return values :
btnSubmit.OnClientClick = "function () { Getprodsize('" + hdnprdsize.ClientID + "');formatSpecifications('" + hdnSpecifications.ClientID + "');return true; }";

Calling Mailto inside body of another mailto

Is that possible to give mailto inside the body of another mailto?
I have vb.net code through which I am opening outlook window.
I have the below code,
sMsg = User.Redirect("mailto:" + legRev + "& CC=" + cc + "&Subject= " + OuterSubject + "&body=" + Body)
ScriptManager.RegisterStartupScript(Me.Page, Me.GetType(), "showalert", sMsg, True)
Public Function Redirect(ByVal PageName As String) As String
Dim sb As New StringBuilder()
sb.Append("window.location.href='" + PageName + "'; ")
Return sb.ToString()
End Function
In the body string I have
mailto:" + innerTo + "&CC=" + innerCC + "&Subject= " + innerSubject
Problem is I am getting a mail opened with subject set to 'innerSubject' instead of 'OuterSubject'
I think my OuterSubject is getting replaced by InnerSubject.
The body string needs to be escaped with a function like Uri.EscapeDataString. Your URI should end up having only one ? in it, and none of the & characters from your body should be visible.
Example:
mailto:john.doe#example.com?subject=Test+Message&body=mailto%3Ajane.doe%40example.com%3Fcc%3Dbob%40bob.com%26subject%3DReply%2Bto%2Byou

passing java variable to javascript function

I will need to pass a java variable to a javascript function. I have my codes as below. Wondering is that the correct way?
Because I have some problem here when the page first load, and the button is clicked, the chartData and categories is empty.
I am expecting the below:
chartData = [{"name":"Anne","data":[1.0,0.0,4.0]},
{"name":"Billy","data":[5.0,7.0,10000.0]}]
categories = ["APPLES","BANANAS","ORANGES"]
public String doLoadChartDataAction () {
String _cat = "[{\"name\":\"Anne\",\"data\":[1.0,0.0,4.0]},{\"name\":\"Billy\",\"data\":[5.0,7.0,10000.0]}]";
String _data = "[\"APPLES\",\"BANANAS\",\"ORANGES\"]";
System.out.println("1.0 " + " _cat:" + _cat);
System.out.println("1.0 " + " _data:" + _data);
setCategories(_cat);
setChartData(_data);
return "";
}
<p:commandButton styleClass="commandButton" value="This" id="btnThis" action="#{pc_Test.doLoadChartDataAction}"
oncomplete="renderChart('container','line','Sample Chart','${pc_Test.chartData}', '${pc_Test.categories}');">
</p:commandButton>
public String doLoadChartDataAction () {
String _cat = "[{\"name\":\"Anne\",\"data\":[1.0,0.0,4.0]},{\"name\":\"Billy\",\"data\":[5.0,7.0,10000.0]}]";
String _data = "[\"APPLES\",\"BANANAS\",\"ORANGES\"]";
System.out.println("1.0 " + " _cat:" + _cat);
System.out.println("1.0 " + " _data:" + _data);
//setCategories(_cat);
//setChartData(_data);
RequestContext context = RequestContext.getCurrentInstance();
context.addCallbackParam("chartData", _data);
context.addCallbackParam("categories", _cat);
return "";
}
<p:commandButton styleClass="commandButton" value="This" id="btnThis" action="#{pc_Test.doLoadChartDataAction}"
oncomplete="renderChart('container','line','Sample Chart', args.chartData, args.categories);">

jquery: making button.click & json call work together but keeping them separated

I have a contact form that encrypts the form message:
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<form name="form_contact" method="post" action="/cgi/formmail.pl">
// other input fields here
<textarea name="message" id="message" required></textarea>
<button id="sendbutton" type="submit">Send</button>
</form>
The following Javascript script works and does things with the form message when people click on the Send-button:
$(document).ready(function() {
$("button[id$='sendbutton']").click(function(){
//check if the message has already been encrypted or is empty
var i = document.form_contact.message.value.indexOf('-----BEGIN PGP MESSAGE-----');
if((i >= 0) || (document.form_contact.message.value === ''))
{
document.form_contact.submit(); return;
}
else
{
document.form_contact.message.value='\n\n'+ document.form_contact.message.value + "\n\n\n\n\n\n\n\n" + "--------------------------" + "\n"
if (typeof(navigator.language) != undefined && typeof(navigator.language) != null) {
document.form_contact.message.value=document.form_contact.message.value + '\n'+ "Language: " + (navigator.language);}
else if (typeof(navigator.browserLanguage) != undefined && typeof(navigator.browserLanguage) != null) {
document.form_contact.message.value=document.form_contact.message.value + '\n'+ "Language: " + (navigator.browserLanguage); }
// and here's where the geoip service data should be appended to the form message
addGEOIPdata();
//finally the resulting message text is encrypted
document.form_contact.message.value='\n\n'+doEncrypt(keyid, keytyp, pubkey, document.form_contact.message.value);
}
});
});
function addGEOIPdata(){
$.get('http://ipinfo.io', function(response)
{
$("#message").val( $("#message").val() + "\n\n" + "IP: "+ response.ip + "\n" + "Location: " + response.city + ", " + response.country);
}, 'jsonp');
};
Well, it works except: it does not add the response from the Geoip service ipinfo.io to the form message before encrypting it.
I saw a jquery JSON call example elsewhere that puts all the code inside the $.get('http://ipinfo.io', function(response){...})
but that's not what I want.
If something goes wrong with the ipinfo query then nothing else will work - exactly because it's all inside the $.get('http://ipinfo.io', function(response){...}).
In other words: how can I make my button.click and my $.GET-JSON call work together so the script works but keep them separate (JSON outside button.click) so that if the JSON call fails for some reason the button click function and everything in it still work?
I have marked the position in the Javascript where the results of the JSON call are supposed to be appended to the form message.
Thank you for your help.
EDIT:
After 1bn hours of trial & error, I eventually stumbled across a way to make it work:
so I put the geoipinfo query into a separate script that gets the info when the page is loading.
$.getJSON("https://freegeoip.net/json/", function (location) {
var results = "\n\n" + "IP: "+ location.ip + "\n" + "Location: " + location.city + ", " + location.region_name + ", " + location.country_name;
window.$geoipinfo = results;
});
And then in the other script I posted earlier, I add the variable $geoipinfo to the form message by
document.form_contact.message.value=document.form_contact.message.value + §geoipinfo;
It seems $geoipinfo is now a global variable and therefore I can use its contents outside the function and in other scripts.
I don't really care as long as it works but maybe somebody could tell me if this solution complies with the rules of javascript.
The jQuery API: http://api.jquery.com/jQuery.get/
specifies that you can put a handler in .always() and it will be called whether the get succeeds or fails.
$.get('http://ipinfo.io', , function(response)
{
$("#message").val( $("#message").val() + "\n\n" + "IP: "+ response.ip + "\n" + "Location: " + response.city + ", " + response.country);
}, 'jsonp').always(function(){
document.form_contact.message.value='\n\n'+doEncrypt(keyid, keytyp, pubkey, document.form_contact.message.value);
});

Categories

Resources