C# using textbox as "post it" / "sticky memo" client side event - javascript

I want a textbox to act like a "post it" or "Sticky memo" just like widget Igoogle or Windows 7 widget.
The idea:
<asp:TextBox ID="TextBox1" runat="server">
</asp:TextBox>
Every time that user types into the textbox it calls Javascript to save the text into cookies.
Could somebody give me a hint?

This is somewhat quick and dirty but will get you going.
There's plenty of setCookie/getCookie JS snippets around the web. I used these:
http://www.dotnetspark.com/kb/1480-use-cookies-javascript-getcookie-setcookie.aspx
Teh code now:
<input type="text" id="txtMemo" />
<script type="text/javascript">
function setCookie(CookieName, CookieVal, CookieExp, CookiePath, CookieDomain, CookieSecure)
{
var CookieText = escape(CookieName) + '=' + escape(CookieVal); //escape() : Encodes the String
CookieText += (CookieExp ? '; EXPIRES=' + CookieExp.toGMTString() : '');
CookieText += (CookiePath ? '; PATH=' + CookiePath : '');
CookieText += (CookieDomain ? '; DOMAIN=' + CookieDomain : '');
CookieText += (CookieSecure ? '; SECURE' : '');
document.cookie = CookieText;
}
// This functions reads & returns the cookie value of the specified cookie (by cookie name)
function getCookie(CookieName)
{
var CookieVal = null;
if(document.cookie) //only if exists
{
var arr = document.cookie.split((escape(CookieName) + '='));
if(arr.length >= 2)
{
var arr2 = arr[1].split(';');
CookieVal = unescape(arr2[0]); //unescape() : Decodes the String
}
}
return CookieVal;
}
var memoCookieName = "txtMemo_value";
var memoElementId = "txtMemo";
var memoElement = document.getElementById(memoElementId);
memoElement.value=getCookie(memoCookieName);
memoElement.onkeyup = function() {
setCookie(memoCookieName,this.value, new Date(new Date().getTime()+1000*60*60*24*30));
};
</script>
This will work with plain HTML. In your case with ASP.NET markup and controls the ID property has a different meaning, so you need to make your JS aware of the actual client ID. This way for example:
(...)
var memoCookieName = "txtMemo_value";
var memoElementId = "<%= TextBox1.ClientID %>";
var memoElement = document.getElementById(memoElementId);
(...)

Of course. Play with "change" event:
http://www.w3schools.com/jsref/event_onchange.asp
It's just about using this event and update some cookie that you previously created with JavaScript too.

Related

Store gclid and bing utm tag in cookie, pass values to form

So I'm currently able to capture the GCLID value from visitors and pass this through to our forms just fine. My question is, using the same scripts (attached below), is it possible to also capture a utm value as well?
For example, if a visitor comes to our website from a Bing ad, the url will be something like www.example.com/?utm_source=bing&utm_medium=cpc
I need to be able to store the value of utm_source (bing) in a cookie, and pass this value to our forms.
Code that's working for me currently with the GCLID:
Store GCLID in cookie (before </body> tag):
<script type="text/javascript">
function setCookie(name, value, days){
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = name + "=" + value + expires + ";path=/";
}
function getParam(p){
var match = RegExp('[?&]' + p + '= ([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));}
var gclid = getParam('gclid');
if(gclid){
var gclsrc = getParam('gclsrc');
if(!gclsrc || gclsrc.indexOf('aw') !== -1){
setCookie('gclid', gclid, 90);
}
}
</script>
Pass value to form (in header):
<script>
window.onload = function getGclid() {
document.getElementById("00N3100000H5IBe").value = (name = new
RegExp('(?:^|;\\s*)gclid=([^;]*)').exec(document.cookie)) ?
name.split(",")[1] : "";
}
// window.onload() may not be supported by all browsers.
// If you experience problems submitting the GCLID as a
// hidden field, consider using an alternate method to
// call this function on page load.
</script>
I am able to modify the current scripts to capture the utm value but then it won't capture the gclid value. So far I have been unable to do both.
Any help or direction would be much appreciated. Please let me know if I need to better explain things. Thanks!
The code below puts the GCLID code in the hidden field OR the UTM_Source.
I have this all in the body as you first need to set the cookie and then read it out.
Good luck!
NOTE: the 'Field7' is the ID of the hidden field on my form.You will have to change that to your form.
<script type="text/javascript">
function setCookie(name, value, days){
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = name + "=" + value + expires + ";path=/";
}
function getParam(p){
var match = RegExp('[?&]' + p + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
function readCookie(name) {
var n = name + "=";
var cookie = document.cookie.split(';');
for(var i=0;i < cookie.length;i++) {
var c = cookie[i];
while (c.charAt(0)==' '){c = c.substring(1,c.length);}
if (c.indexOf(n) == 0){return c.substring(n.length,c.length);}
}
return null;
}
// Define the variables
var gclid = getParam('gclid');
var utm_source = getParam('utm_source');
// Check if there is a GCLID first, then check if there is a utm_source
if(gclid){
alert(gclid);
setCookie('gclid', gclid, 90);
} else if(utm_source) {
alert(utm_source);
setCookie('utm_source', utm_source, 90);
}
</script>
<script type="text/javascript"> // Now set the hidden field on the form by looking for the correct cookie name
window.onload = function() {
if (gclid) {
document.getElementById('Field7').value = readCookie('gclid');
} else if (utm_source) {
document.getElementById('Field7').value = readCookie('utm_source');
}
}
</script>

Making use of a JSON attribute that doesn't always exist. Using jquery

I am writing a short script that connects to the LastFM api to get my last scrobbled song. The issue I am having is that the JSON version has an attribute for "now playing" which when you are currently listening to a song has the value of "true". However if there is no song playing the attribute doesn't exist at all.
This is the script I currently have and when I am listening to a song via spotify or iTunes etc... it works fine.
<p>
<p class="nowplaying"> <span class="track"></span> by <span class="artist"></span></p>
<p>
<script type="text/javascript">
$.getJSON('https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=JamesTaylor87&api_key=ADD-API-KEY-HERE&format=json', function(data) {
var artist = $(".artist"),
track = $(".track"),
np = $(".nowplaying"),
artistVal = data.recenttracks.track[0].artist["#text"],
trackVal = data.recenttracks.track[0].name,
nowplaying = data.recenttracks.track[0]["#attr"].nowplaying;
if(typeof nowplaying === "undefined"){
np.prepend("The last song I listened to was")
artist.append(artistVal);
track.append(trackVal);
} else {
np.prepend("I am currently listening to")
artist.append(artistVal);
track.append(trackVal);
}
});
</script>
However when I am not listening to anything I get the following error message (in safari) and nothing works:
undefined is not an object (evaluating 'data.recenttracks.track[0]["#attr"].nowplaying')
in chrome the error is displayed as follows:
Uncaught TypeError: Cannot read property 'nowplaying' of undefined
I have attempted to use an if statement for when it's undefined which hasn't worked and don't really know what else to try. Any help would be much appreciated.
Replace
data.recenttracks.track[0]["#attr"].nowplaying
with
data.recenttracks.track[0]["#attr"] && data.recenttracks.track[0 ["#attr"].nowplaying
That should stop the error occuring if data.recenttracks.track[0]["#attr"] is undefined
Try changing the line where you defined nowplaying to this:
nowplaying = (data.recenttracks.track[0]["#attr"]) ? data.recenttracks.track[0]["#attr"].nowplaying : undefined;
According to the chrome error, data.recenttracks.track[0]["#attr"] is undefined, which means you can't look for a property on it. You can use an if statement or a ternary to check whether this is defined before checking for its nowplaying property.
var attrs = data.recenttracks.track[0]["#attr"];
if (typeof attrs !== 'undefined') {
var nowPlaying = attrs.nowplaying;
}
Try this:
var track = data.recenttracks.track[0];
var nowplaying = track.hasOwnProperty('#attr') && track['#attr'].nowplaying;
I just built a very similar function for my site with Last.fm, and ran into this same problem. I was able to solve the problem by removing subsequent .nowplaying that you've included.
See below. Hope it's helpful!
// get the api
$.getJSON('http://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks&user=YOURUSERNAME&limit=1&api_key=YOURAPIKEY&format=json', function(data) {
var latesttrack = data.recenttracks.track[0]
var trackTitle = latesttrack.name
var trackArtist = latesttrack.artist["#text"]
// detect if the track has attributes associated with it
var nowplaying = latesttrack["#attr"]
// if nowplaying is underfined
if (typeof nowplaying === 'undefined') {
$('.nowplaying').html("Currently listening to nothing.")
} else {
$('.nowplaying p').html("Currently listening to" + trackTitle + " by " + trackArtist)
}
});
See it in action here: http://theadamparker.com/daily
<script type="text/javascript">
//<![CDATA[
var lastfm_api = 'http://ws.audioscrobbler.com/2.0/';
var lastfm_methods = 'user.getRecentTracks';
var lastfm_user = 'YOUR_USERNAME';
var lastfm_key = 'YOUR_APIKEY';
var lastfm_limit = '1';
var lastfm_json = lastfm_api + '?method=' + lastfm_methods + '&user=' + lastfm_user + '&api_key=' + lastfm_key + '&limit=' + lastfm_limit + '&format=json';
$.getJSON(lastfm_json, function(data) {
var html = '';
var song = data.recenttracks.track[0].name,
artist = data.recenttracks.track[0].artist["#text"],
url = data.recenttracks.track[0].url,
cover = data.recenttracks.track[0].image[0]['#text'];
html += '<p>' + song + ' by ' + artist + '<br /><br /><img src="' + cover + '" style="display: block; width: 96px; height: 96px;" /></p><p>Share on Twitter</p>';
$('#recent-tracks').append(html);
});
//]]>
</script>
<div id="recent-tracks"></div>

How do I write javascript cookies from a form and then print the info in an alert or hidden div?

How do I use JavaScript to write cookies from form fields, and then print the info in an alert or hidden div?
Here is an example of what I have tried thus far.....
<script type="text/javascript">
function cookieForm() {
document.cookie = "name_first" + encodeURIComponent(document.forms[0].name_first.value);
}
function printCustomerInfo() {
var queryData = decodeURIComponent(document.cookie);
var queryArray = queryData.split(";");
if (document.cookie) {
window.alert("Your info. is:" + queryArray[0]);
window.alert[0].name_last.value = QueryArray[1].substring(queryArray[1].lastIndexOf("=") + 1);
}
}
</script>
<input type="submit" value="Submit" onclick="cookieForm(), printCustomerInfo()"/>
First, you're missing the "=" in the cookie string:
document.cookie = "name_first=" + encodeURIComponent(document.forms[0].name_first.value);
Second, your queryData has no ";" to split by, and no last name value - at least from what you show here.
This I do not understand:
window.alert[0].name_last.value = ...
I would call a single function from your event, and let that parent both setting the cookie and parsing it. That way you can at least debug it better.
re: a div, you could do something like this:
document.getElementById("yourDiv").innerHTML = "Your info. is:" + queryArray[0];
document.getElementById("yourDiv").style.visibility = 'visible';
But in general it's better to use jquery for manipulating elements, because it mitigates browser differences, though it wouldn't matter in this case:
$("yourDiv").html("Your info. is:" + queryArray[0]);
$("yourDiv").css ( { 'visibility': 'visible' } );
Good luck.

popualte textbox from values on screen with javascript

how can I use the values from the code below:
<html:select property="state" >
<html:option value="0">Select State</html:option>
<html:optionsCollection name="InputForm" property="stateList" label="label" value="value" />
</html:select>
to populate a textbox with whatever the selected value is for the state with a javascript onchange event? for example if texas is the selected state I want Texas to be written in the textbox and if I change the value to Colorado I would like Colorado and Texas to both show in the textbox. I am currently getting an undefined value in the textbox. I am using the following javascript code:
function displayState(obj, state) {
var theId = obj.id.substring(obj.id.indexOf('_') + 1);
var text = document.getElementById('text' + '_' + theId);
var textVal = text.value;
var stateSelect = document.getElementById('stateCode' + '_' + theId);
var stateSelectStr = new String(stateSelect.value);
var stateSelectSplit = stateSelectStr.split(',');
var stateSelectValue = stateSelectSplit[0];
var stateSelectLabel = stateSelectSplit[1];
if (stateSelectValue == '51') {
stateSelectLabel = '';
}
if (stateSelectValue != '00') {
textVal = textVal != '' ? eval('text.value=\'' + textVal + ', '
+ stateSelectLabel + '\'')
: eval('text.value=\'' + stateSelectLabel + '\'');
}
}
First off, start using jQuery (or equivalent), it will make your life much easier. Second, why are you using eval? You already have the text element; just build the appropriate string and set the value. See here for an example.
But again, using something like jQuery makes this laughably easy--I can't recommend using a library for simple DOM manipulation like this.
See here for a comparison between raw JS and JQ.

Submit not working in Chrome and IE under Windows 7

I have a web form created using .net and in this form has a frame which has its source from another HTML page (created by courselab software). I call a JavaScript code whenever the user completes the page and click a submit button and exits normally or whenever the user navigates away from the page based on the JavaScript event onbeforeunload.
The code works just perfectly using:
Firefox in both cases
IE on Windows XP in both cases
Still it works in CHROME if the user clicked on the submit button (this submit button generated by courselab software which calls the JavaScript code),
but if the user navigates away from the web form, this code is being called using the onbeforeunload and the code renders correctly but the submit input is never fired.
Similarly this code does not fire using IE on Windows 7.
I have also called the code onunload of the form, but still nothing happens.
Update
IE 8
Firefox 3.6.1.3
Chrome 9.0.597.98
The main web form has the following:
<div id="FOContent">
<iframe runat=server id="mainiframe" name="mainiframe" scrolling="no" frameborder="no"
width="1000" height="920"></iframe>
</div>
The frame content comes from this HTML page:
<body style="margin-left:0px;margin-top:0px;margin-right:0px;margin-bottom:0px;" onload="Run(true)" onunload="Shutdown()" onbeforeunload="Shutdown()" oncontextmenu="return false">
<div id="boardFrame" style="position:absolute;left:0px;top:0px;width:1000;height:700">
</div>
<div id="divEmail"></div>
</body>
And the JavaScript code being called for onunload or onbeforeunload is:
function LMSShutdown() {
if (submit_Var == false) {
var sAiccData = AICC_PrepareData(); // prepare data from the CourseLab
var strQuizResults
strQuizResults = "";
var nPos1 = sAiccData.indexOf("Score=");
nPos1 = nPos1 + 6;
var ePos1 = nPos1 + 2
var score = sAiccData.substring(nPos1, ePos1);
var sHTML = "";
var qTxt;
qTxt = ""
var qrStr = window.location.search;
var spQrStr = qrStr.substring(1);
var arrQrStr = new Array();
// splits each of pair
var arr = spQrStr.split("&");
for (var i = 0; i < arr.length; i++) {
// splits each of field-value pair
var index = arr[i].indexOf("=");
var key = arr[i].substring(0, index);
var val = arr[i].substring(index + 1);
var id1
var id2
if (key == "")
{key = "Q"+i}
qTxt = qTxt + "&" + key + "=" + val;
if (i == 0)
{ id1 = val; }
else
{ id2 = val; }
}
// saves each of field-value pair in an array variable
sHTML += '<FORM id="formQuiz" method="POST" action="../../../StudentView/QuizProcess.aspx?submit_Var=' + 'false' + '&score=' + score + qTxt + '">';
var spQrStr = g_arVars["writing"];
var arrQrStr = new Array();
// splits each of pair
var arr = spQrStr.split("###");
for (var i = 0; i < arr.length; i++) {
// splits each of field-value pair
var index = arr[i].lastIndexOf(":");
var key = arr[i].substring(0, index);
var val = arr[i].substring(index + 1);
if (key != "")
{qTxt = qTxt + "&" + key + "=" + val;
sHTML += '<INPUT TYPE="hidden" NAME="' + key + '" VALUE=\'' + val + '\'>';
}
}
sHTML += '<br><input name="btnSubmit" id="btnSubmit" type="button"><br>';
sHTML += '</FORM>';
document.getElementById("divEmail").innerHTML = sHTML;
document.getElementById("formQuiz").submit();
submit_Var = true;
}
}
The QuizProcess.aspx page has not much in HTML, but it has vb .net code to store data to database
The issue is that the function LMSShutdown is being called in all browsers on different platforms, but the form QuizProcess is not being submitted only in (Chrome on Windows XP or 7 ) and in (IE 8 when using Windows 7) strangely works fine in IE 8 on Windows XP.
Sounds like a security restriction here. Try generating that form straight from ASP.NET instead of Javascript. This will help Chrome see it, as the will be in the raw html rather than virtual. Of course, all the 's to the form can be hidden, so it wont affect the presentation.

Categories

Resources