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.
Related
When using the API, the parameter requested to the server does not work properly.
'occupation=01%02' works fine (change url directly in internet browser), but it throws an error when 'occupation=01%2C02'(,) or 'occupation=01&occupation=02'.
This error occurs when requesting to the server with multiple values from the checkbox.
What is the problem?
Is it an encoding problem?
If I'm wrong, where would I go wrong?
I used html5 client and receive 10 from the server and paging them
in java:
uri = new URIBuilder()
.setScheme("http")
.setHost("openapi.work.go.kr")
.setPath("/opi/opi/opia/wantedApi.do")
.setParameter("returnType", "xml")
.setParameter("startPage", requestVo.getStartPage())
.setParameter("callTp", "L")
.setParameter("region", "30200")
.setParameter("occupation", requestVo.getOccupation())
.setParameter("keyword", requestVo.getKeyword())
.setParameter("authKey", requestVo.getKey())
.build();
in jsp
:checkbox id is occupation_chbox and I put the value in
<input type="hidden" name="startPage" value="1">
using js
function jobsubmit(){
var form = document.getElementById("requestForm")
var occ = checkOcc();
$("#occupation").val(occ);
console.log($("#occupation").val());
form.submit();
}
function checkOcc(){
var chk_arr = [];
$("input[id='occupation_chbox']:checked").each(function(){
var chkBox = $(this).val();
chk_arr.push(chkBox);
})
console.log(chk_arr);
var occ="";
for(i = 0; i<chk_arr.length; i++){
occ += (i < chk_arr.length - 1) ? chk_arr[i] + "," : chk_arr[i]
}
console.log(occ);
return occ;
}
I solved this problem by changing the delimiter from ',' to '|'.
occ += (i < chk_arr.length - 1) ? chk_arr[i] + "|" : chk_arr[i]
I know some of the quirks of injecting HTML via JavaScript are subtle, but this one produces results which don't even make sense. I'm guessing some of the double quote characters are being misinterpreted, but the guides I've read don't seem to suggest doing anything different.
This is a function which injects a series of dynamically labelled buttons into a bootstrap panel and then injects that panel into a row on the page. So far I'm only producing 10 buttons, and I know I need to address the problem of having more than 12 and making a new panel. For now, the button creation is the issue.
function tableMaker(data, tableID) {
var panel = '<div class="col-md-12" style="height: 140px"> \n\t<div class="panel panel-default" style="height: 100%"> \n\t\t<div class="panel-heading">Apps Alive</div> \n\t\t <div class="panel-body">';
var mytable = '';
var colStart = '<div class="col-md-1"><center><b>';
var titleEnd = '</b></center>';
var buttonStart = '<center><button id="';
var buttonMiddle1 = '-appcheck" type="button" class="btn btn-default btn-circle btn-lg" title="';
var buttonMiddle2 = '" onclick="templateLoader("';
var buttonMiddle3 = '")"';
var buttonEnd = '-appcheck-icon" class="fa fa-exclamation-circle"></i></button></center>';
var colEnd = '</div>';
var panelEnd = '\n</div>';
var i = 0, j = 0, colLimit = 12;
for(; i < data.length;){
for (var j = 0; j < colLimit && i < data.length; ++j, ++i) {
/*
* Template
* <button id="OPS-appcheck" type="button" class="btn btn-default btn-circle" title="OPS" onclick="templateLoader("OPS")"><i id="OPS-appcheck-icon" class="fa fa-exclamation-circle"></i>
* </button>
*/
mytable += colStart + data[i][2] + titleEnd + '\n' + buttonStart + data[i][2] + buttonMiddle1 +
data[i][2] + buttonMiddle2 + data[i][2] + buttonMiddle3 + '><i id="' + data[i][2] +
buttonEnd + colEnd;
}
}
panel += mytable + panelEnd;
document.getElementById(tableID).innerHTML = panel;
}
To me, this looks right. Every quote and tag has a matching closer where it should be, but browsers turn the HTML generated into this odd thing:
The 'type' isn't in remotely the correct spot, and I don't know how it managed to get there based on the string format. There are also a few extra double quotes, but visual inspection doesn't tell me how they got there.
EDIT So, escaping the suggested double quotes has produced the following:
That seems like it should work, but the onclick isn't doing as I'd expect. It's probably a regex issue with my MVC mapping, but maybe it's still the JavaScript.
At the top of the HTML page, jquery.js and then dashboard.js are invoked. At the top of dashboard.js is the following:
function templateLoader(appTag) {
$.get('/app/' + appTag);
}
And in the controller for the project (the only one so far), I have this:
#RequestMapping(value = "/app/*", method = RequestMethod.GET)
public ModelAndView generic()
{
return new ModelAndView("template");
}
Yet, if I click any of the buttons, I get no reported request according to the Tomcat logs, and I'm not being redirected to my target page. Is it the mvc, or the script? There are no errors in the dev tools console either.
If you console.log(panel) at the end of your function, it becomes very clear
change these two vars
var buttonMiddle2 = '" onclick="templateLoader(\'';
var buttonMiddle3 = '\')"';
I am currently trying to create a dynamic printable-document generator for my training department at work. I would like the entire project to remain in Javascript/browser-side scripting, as I'm trying to gain knowledge in Javascript exclusively. The UI is linked below (can't post images until I have 10 rep):
Hosted on my personal website - cgiv.webs.com/Test Platform/Training Plan.png
The issue I'm having is with regular expressions. I am fairly new to Javascript, but VERY new to regular expressions within Jscript. I'm currently using the following function to generate and identify three input texts per execution:
/*Variable Declarations*/
var i1 = 0;
var i2 = 0;
/* ------------------- */
function generateInput()
{
if (i1<15)
{
i1++;
var appendSpan = document.getElementById('appendSpan');
var appendStr = "<div class='row'><input id='text_topic" + i2.toString() + i1.toString() + "' class='text_topic' type='text'/>|<input id='text_instructor" + i2.toString() + i1.toString() + "' class='text_instructor' type='text'/>|<input id='text_date" + i2.toString() + i1.toString() + "' class='text_date' type='text'/></div>";
appendSpan.innerHTML += appendStr;
}
else
{
alert("Action Cancelled. Maximum fields reached.");
}
}
The i2 variable indicates the header number that the input fields fall under, where the i1 variable indicates the row that each cell falls into. I would like to place a regex identifier script within the following function to pull the values from each cell and append them underneath their respective target spans within the "newPage" variable:
function createPage()
{
var newPage = "<html><head><title></title>";
newPage += "<link rel='stylesheet' lang='text/css' href='output.css'>";
newPage += "</head><body>";
newPage += "<div class='head'>" + promptVal[0] + "</div><br/>";
newPage += "<span id='hcontent1'></div></span>";
var inputs = document.getElementsByTagName("input");
/* Uhhh.. Yeah. This is where I'm lost */
newPage += "</span>";
newPage += "</body></html>";
var j = window.open('')
j.document.write(newPage);
j.document.close();
}
Once I can get, for example, text_(topic, instructor, date)(11-13) all within the "hcontent1" span, I can format it out. I just want the data to be pulled from the text fields and placed into div tags on a separate page.
Thanks for your time, ahead of time!
I figured it out! After like three days of searching, this worked:
var regex1 = /1/g;
for (var i=0; inputs[i]; i++)
{
if (inputs[i].id.search(regex1) == 10)
{
alert("It worked");
}
else if (inputs[i].id.search(regex1) == 15)
{
alert("It worked again");
}
else if (inputs[i].id.search(regex1) == 9)
{
alert("You did it, man");
}
else
{
alert("Skip this one");
}
}
I have asked a question about how to avoiding to write the html in the js,then some people tell me using the javascript template,for example,the jquery/template pugin and ect.
It is a good idea when generate static html,for example:
<ul id="productList"></ul>
<script id="productTemplate" type="text/x-jquery-tmpl">
<li><a>${Name}</a> (${Price})</li>
</script>
<script type="text/javascript">
var products = [
{ Name: "xxx", Price: "xxx" },
{ Name: "yyy", Price: "xxx" },
{ Name: "zzz", Price: "xxx" }
];
// Render the template with the products data and insert
// the rendered HTML under the "productList" element
$( "#productTemplate" ).tmpl( products )
.appendTo( "#productList" );
</script>
However when I try to bind some event to the generated html,I meet some problem.
For example,I have a page which user can search some products by the price/name/location.
So I have three function:
searchByPrice(lowPrice,highPrice,productType,currentPage)
searchByName(name,productType,currentPage);
searchByLocation(location,currentpage);
ALl the above function have a realated method in the server side and they will retrun the products usint the xml format.
Since they will retrun so many items,so I have to paging them,the "currengPage" is used to tell the server side which part of results should be returned.
When the client get the result from the server side,now it is the js for display them int he div and create a Paging Bar if possible.
Before I know the template,I use this manner(which I hate most,try my best to avoid):
function searchByPrice(lowPrice,highPrice,productType,currentPage){
var url="WebService.asmx/searchByPrice?low="+lowPrice="&high="+highPrice+"&curPage="+currentPage;
//code to create the xmlHttp object
xmlhttp.open("GET",url,true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
var i=0;
var Prohtml="";
var proList=parseProductList(xmlhttp.responseText);
for(i=0;i<prolist.length;i++){
Prohtml+="<li><a href='#'>"+prolist[i].name+"</a> ("+prolist[i].price"+)</li>";
}
//generate the paging bar:
var totleResult=getTotleResultNumber(xmlhttp.responseText);
if(totleResult>10){
var paghtml="<span>";
//need the paging
var pagNum=totleResult/10+1;
for(i=1;i<=pagenum;i++){
paghtml+="<a onclick='searchByPrice(lowPrice,highPrice,productType,currentPage+1)'>i</a>";
//here the synax is not right,since I am really not good at handle the single or doule '"' in this manner.
//also if in the searchByName function,the click function here should be replaced using the searchByName(...)
}
}
}
}
}
In the example,it is easy to use the template to generate the "Prohtml" since there is no event handling with them,but how about the "paghtml",the click function is different in differnt search type.
So,any good idea to hanld this?
Either:
Create DOM Elements instead of building HTML strings, using document.createElement or a small library if you're doing lots of this, which will allow you to attach events immediately in the usual fashion.
or
Give each element which needs to make use of event handlers a unique ID and build up a list of events to be attached once the HTML has been inserted into the document.
E.g.:
var eventHandlers = []
, eventCount = 0;
for (i = 1; i <= pagenum; i++) {
var id = "search" + eventCount++;
html += "<a id='" + id + "'>" + i + "</a>";
eventHandlers.push([id, 'click',
handler(searchByPrice, lowPrice, highPrice, productType, currentPage + i)])
}
// Later...
someElement.innerHTML = html;
registerEvents(eventHandlers);
Where registerEvents is:
function registerEvents(eventHandlers) {
for (var i = 0, l = eventHandlers.length; i < l; i++) {
var eventHandler = eventHandlers[i],
id = eventHandler[0],
eventName = eventHandler[1],
func = eventHandler[2];
// Where addEvent is your cross-browser event registration function
// of choice...
addEvent(document.getElementById(id), eventName, func);
}
}
And handler is just a quick way to close over all the arguments passed in:
/**
* Creates a fnction which calls the given function with any additional
* arguments passed in.
*/
function handler(func) {
var args = Array.prototype.slice.call(arguments, 1);
return function() {
func.apply(this, args);
}
}
I use something like this approach (but automatically adding unique ids when necessary) in the HTML generation portion of my DOMBuilder library, which offers a convenience method for generating HTML from content you've defined, inserting it into a given element with innerHTML and registering any event handlers which were present. Its syntax for defining content is independent of output mode, which allows you to switch between DOM and HTML output seamlessly in most cases.
First of all, you can simply use the $.get() or $.ajax() for your AJAX call.
Secondly, you can use .live() or .delegate() to bind events to elements that do not exist.
Thirdly, you can use the data attributes in the anchor elements as a way to pass in the arguments for the event handler, see .data().
So, to rewrite your function, you have may something like the following:
function searchByPrice(event) {
$this = $(this);
var lowPrice = $this.data('lowPrice'),
highPrice = $this.data('lowPrice'),
productType = $this.data('productType'),
currentPage = $this.data('currentPage');
var url = "WebService.asmx/searchByPrice?low=" + lowPrice = "&high=" + highPrice + "&curPage=" + currentPage;
$.get(url, function(data, textStatus, jqXHR) {
var i = 0;
var Prohtml = "";
var proList = parseProductList(data);
for (i = 0; i < prolist.length; i++) {
Prohtml += "<li><a href='#'>" + prolist[i].name + "</a> (" + prolist[i].price "+)</li>";
}
//generate the paging bar:
var totleResult = getTotleResultNumber(data);
if (totleResult > 10) {
var paghtml = "<span>";
//need the paging
var pagNum = totleResult / 10 + 1;
for (i = 1; i <= pagenum; i++) {
paghtml += '<a class="pagelink" ' +
'data-lowPrice="' + lowPrice + '" ' +
'data-highPrice="' + highPrice + '" ' +
'data-productType="' + productType + '" ' +
'data-currentPage="' + (currentpage + 1) + '">' + i + '</a>';
//here the synax is not right,since I am really not good at handle the single or doule '"' in this manner.
//also if in the searchByName function,the click function here should be replaced using the searchByName(...)
}
}
});
}
$(document).ready(function(){
$("a.pagelink").live('click', searchByPrice);
});
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.