How to write the keypress event in Jquery/ Javascript? - javascript

I am new to Jquery and Javascript. Need a help regarding this problem:
There is a div named Profile , If I click that then a new popup window will open. Now this is only possible by a mouse click. I need it to be done by key press (enter) also.
JSP CODE FOR THE DIV
<div tabindex="0" style="text-decoration:underline" onmouseover="this.style.cursor='pointer';" id="<%=namespace%>_pmProfileName_<%=i%>_" onclick="perfChartConfig_<%=namespace%>.doShowProfilesForElement(this);">Profile</div>
JQUERY/JAVASCRIPT CODE
doShowProfilesForElement : function(source){
var callback = {
success : function(r) {
MO.globals.popups.hideWorkingMsg();
this.argument[0].pe = eval("("+r.responseText+")");
var pe = this.argument[0].pe;
var pStr = '';
if(this.argument[1].indexOf("pmProfileName") > 0){
if(pe == null || pe._mosol_AllPerfProfileNames.length==0){
pStr = pStr + "<li>There are no profiles available for the element you selected.</li>";
} else {
for(var i=0; i<pe._mosol_AllPerfProfileNames.length;i++){
var profile = pe._mosol_AllPerfProfileNames[i];
var onClick = "onClick=\"perfChartConfig_<%=namespace%>.doProfileSelection(this,'"+this.argument[1]+"');\"";
pStr = pStr + "<div style=\"text-decoration:underline\" onmouseover=\"this.style.cursor='pointer';\" "+onClick+" >"+profile+"</div>";
//alert('For profile ['+profile+'] there are '+pe[profile].length+' expressions.');
}
}
}
if(this.argument[1].indexOf("slaProfileName") > 0){
if(pe == null || pe.offers.length==0){
pStr = pStr + "<li>There are no SLAs available for the element you selected.</li>";
} else {
for(var i=0; i<pe.offers.length;i++){
var profile = pe.offers[i];
var onClick = "onClick=\"perfChartConfig_<%=namespace%>.doProfileSelection(this,'"+this.argument[1]+"');\"";
pStr = pStr + "<div style=\"text-decoration:underline\" onmouseover=\"this.style.cursor='pointer';\" "+onClick+" >"+profile+"</div>";
}
}
}
var rp = perfChartConfig_<%=namespace%>.rp;
rp.setHeader("Select a Profile you want to chart:");
rp.setBody(pStr);
rp.render();
rp.show();
},
failure : function(r) {
MO.globals.popups.hideWorkingMsg();
MO.globals.popups.showMsg("Error", "<h2><span class=\"portlet-msg-error\">Your submission failed</span>"+"<br />Status: " + r.status + "</h2>");
},
argument: [this, source.id]
};
Would you tell me how to write the function for keypress(enter) ?

bind the keypress or keyup event with you div
<div tabindex="0" class="someClass" style="text-decoration:underline" onmouseover="this.style.cursor='pointer';" id="<%=namespace%>_pmProfileName_<%=i%>_" onclick="perfChartConfig_<%=namespace%>.doShowProfilesForElement(this);">Profile</div>
add some class
$("div.someClass").bind("keyup",function(e){
if(e.keyCode == 13)
{
$(this).click();
}
});

$("#Profile").keyup(function(e){
var code = e.which;
if(code==13){
e.preventDefault();
//Do Stuff
}
});

Related

add javascript variable to click to call link

What I am trying to do is add a javascript variable to a click to call href so that whenever the phone number changes from the javascript the click to call href will change as well. The javascript that defines the variable has a default value (ex: 1-800-555-1212), but can change whenever the page loads where the tfid defines a different phone number (ex: http://www.domain.com?tfid=8663337777)
Here's an example of what's there currently:
<a href="tel:<this phone number needs to be dynamic as well>">Call this number: <script language="javascript" >
key = getVar("keyword");
tn = getVar("tfid");
source = getVar("source");
content = getVar("content");
campaign = getVar("campaign");
if(tn!="")
{
setcookie(key,tn);
}
getcookie();
</script></a>
EDIT:
In order to show all elements to how the phone number is shown or switched out, I've included the javascript below that is called whenever a page loads:
// JavaScript Document start
//function to set cookie from the URL
function pixelfire(debug)
{
var phone_number=getVar("phone_number");
var keyword=getVar("keyword");
var source=getVar("source");
if(keyword)
{
//document.write("set phone number "+phone_number);
//document.write("set keyword "+keyword);
setcookie(keyword,phone_number);
//document.write("back from set cookie");
}
else
{
var keyword=get_named_cookie("MM_Keyword");
var phone_number=get_named_cookie("MM_TrackableNumber");
//document.write("retrieved keyword "+keyword);
//document.write("retrieved phone number "+phone_number);
if(keyword)
{
}
else
{
return null;
}
}
if(debug)
{
document.write("here are cookies<BR><P>"+document.cookie);
}
var campaign=getVar("campaign");
var content=getVar("content");
//document.write("location is "+location);
var url="http://www.mongoosemetrics.com/pixelfire.php?phone_number="+phone_number;
var url = url + "&keyword="+keyword;
var url = url + "&source="+source;
var url = url + "&campaign="+campaign;
var url = url + "&content="+content;
//document.write("url is "+ url);
myImage= new Image();
myImage.src=url;
}
function setcookie(key,tn,path){
index = -1;
var today = new Date();
today.setTime( today.getTime() );
var cookie_expire_date = new Date(today.getTime() + (365* 86400000));
document.cookie="MM_TrackableNumber="+tn+";path=/;expires="+cookie_expire_date.toGMTString();
document.cookie="MM_Keyword="+key+";path=/;expires="+cookie_expire_date.toGMTString();
}
//function to retrive the cookie
function getcookie(){
//plcae your default phone number to show in case cookie is not set
defaultphone="8005551212";
if(document.cookie){ //check if there is a cookie set
index = document.cookie.indexOf("MM_TrackableNumber");
if (index != -1){
namestart = (document.cookie.indexOf("=", index) + 1);
nameend = document.cookie.indexOf(";", index);
if (nameend == -1) {nameend = document.cookie.length;}
document.write(formatnumber(document.cookie.substring(namestart, nameend)));
}
else
{
document.write(formatnumber(defaultphone));
}
}
else
{
document.write(formatnumber(defaultphone));
}
}
function get_named_cookie(name)
{
if(document.cookie)
{
index=document.cookie.indexOf(name);
if (index != -1)
{
namestart = (document.cookie.indexOf("=", index) + 1);
nameend = document.cookie.indexOf(";", index);
if (nameend == -1) {nameend = document.cookie.length;}
var ret_one = document.cookie.substring(namestart, nameend);
return ret_one;
}
}
}
//function to format the phonenumber to (123) 456-7890
function formatnumber(num)
{
_return="1-";
var ini = num.substring(0,3);
_return+=ini+"-";
var st = num.substring(3,6);
_return+=st+"-";
var end = num.substring(6,10);
_return+=end;
return _return;
}
function getVar(name)
{
get_string = document.location.search;
return_value = '';
do { //This loop is made to catch all instances of any get variable.
name_index = get_string.indexOf(name + '=');
if(name_index != -1)
{
get_string = get_string.substr(name_index + name.length + 1, get_string.length - name_index);
end_of_value = get_string.indexOf('&');
if(end_of_value != -1)
value = get_string.substr(0, end_of_value);
else
value = get_string;
if(return_value == '' || value == '')
return_value += value;
else
return_value += ', ' + value;
}
} while(name_index != -1)
//Restores all the blank spaces.
space = return_value.indexOf('+');
while(space != -1)
{
return_value = return_value.substr(0, space) + ' ' +
return_value.substr(space + 1, return_value.length);
space = return_value.indexOf('+');
}
return(return_value);
}
/*end*/
As simple as this may sound (which I know it's not), I need the <a> tag to do this: <a href="tel:FILL THIS WITH EITHER THE DEFAULT NUMBER OR THE NEW NUMBER DEFINED BY THE TFID URL">
You maybe want to wrap it in a function?
<a onclick="doSomething('123456789')" href="tel:<this phone number needs to be dynamic as well>">Call this number: </a>
<script language="javascript" >
function doSomething(telNumber){
var tel = telNumber;
key = getVar("keyword");
tn = getVar("tfid");
source = getVar("source");
content = getVar("content");
campaign = getVar("campaign");
if(tn!="")
{
setcookie(key,tn);
}
getcookie();
}
</script>
You can try to store the phonenumber into the ID of the then use this script
<script>
$(document).ready(function () {
$(".clickable").onClick(function() {
var phone = $(this).attr('id')
});
});
</script>
<a class="clickable" id="{variable_phone_number}" href="...."> ... </a>
EDIT: Try this
<a class="clickable" id="+298384858849" href="...."> ... </a>
<script type="text/javascript">
$(document).ready(function () {
var number = $(".clickable").attr('id')
});
</script>
Remember to add the id and the class attributes

Custom JQuery dynamic link creation

I'm pretty new to js and having a hard time figuring out the best way to generate a custom url depending on what links are selected. You can view what I have done here. http://jsfiddle.net/1fz50z1y/26/ I will also paste my info here.
var products = [];
var quantity = [];
qstring = '';
$('input.product-radio, select.products-howmany').change(function() {
var $this = $(this)
var $product = $(this).closest('.product-options-left');
var $radio = $product.find('input.product-radio');
var $select = $product.find('select.products-howmany')
var qid = $select.val();
var pid = $radio.val();
currentStatus = $radio.prop('checked'),
theString = '';
qString = '';
pString = '';
if (currentStatus) {
products.push(pid);
quantity.push(qid);
if ($product.find('div.quantity').removeClass('q-hidden')) {
//code
}
} else {
products.splice(products.indexOf(pid), 1);
quantity.splice(quantity.indexOf(qid), 1);
$product.find('div.quantity').addClass('q-hidden');
}
if ((products.length > -1) || (quantity.length > -1)) {
if ((products.length === 0) || (quantity.length === 0)) {
console.log("Q Length: " + quantity.length);
pString += products[0];
qString += quantity[0];
console.log("qString = " + quantity);
} else {
pString = products.join('-p');
qString = quantity.join('_q');
if (quantity.length > 1) {
qString = quantity.splice(quantity.indexOf(qid), 1);
pString = products.splice(products.indexOf(pid), 1);
}
console.log("+ Q Length: " + quantity.length);
console.log("ADDING " + "p" + pString + "_q" + qString);
}
if ((qString == 'undefined') || (pString == 'undefined')) {
$('a.options-cart').prop("href", "#");
} else {
//$('a.options-cart').prop("href", "/cart/add/p" + theString + "_q" + qstring + "?destination=/cart");
//$('a.options-cart').prop("href", "/cart/add/p" + theString + "?destination=/cart");
$('a.options-cart').prop("href", "/cart/add/p" + pString + "_q" + qString + "?destination=/cart");
}
}
});
$('a.options-cart').click(function() {
alert(qstring);
var $this = $(this);
href = $this.attr('href');
if (href == '#') {
alert("You must select a product.");
return false;
}
});
When you click on the add link icon it displays a drop down where you can select the quantity. So changing the quantity should also update the link and how it is created. I am trying to figure out how to create the link so the end result looks like so.
cart/add/p123_q1?destination=/cart this is how it would look with a single item. Where p = the product ID and q = the quantity. Unclicking the add to cart should remove those items and changing the drop down should update the quantity. If there is more than one item it should append to the link like so. cart/add/p123_q1-p234_q2-p232_q4?destination=/cart and then unclicking or changing quantity on any of those items should reflect the change in the link. I am not sure if I am going about this all wrong but I have been trying forever and many different routes to go about trying to achieve this effect. If anyone could please help me figure this out I would be greatly appreciated!
I was able to get this to work properly using this piece of code. Hope this maybe helps someone.
$('input.product-radio, select.products-howmany').change(function () {
var $product = $(this).closest('.product-options-left');
var $radio = $product.find('input.product-radio');
var $select = $product.find('select.products-howmany')
$product.find('div.quantity').toggleClass('q-hidden', !$radio.prop('checked'));
$product.find('label.quantity').toggleClass('q-hidden', !$radio.prop('checked'));
var string = $('.product-radio')
.filter(':checked')
.map(function(){
return $(this)
.closest('.product-options-left')
.find('.products-howmany')
.val();
})
.get()
.join('-');
$('a.options-cart').prop("href", "/cart/add/" + string + "?destination=/cart");
});
$('a.options-cart').click(function() {
alert(qstring);
var $this = $(this);
href = $this.attr('href');
if (href == '#') {
alert("You must select a product.");
return false;
}
});

Uncaught TypeError: Cannot read property 'style' of null.VB.NET

This errors occurs when I try to click on the the drop down button. I am using Response.Write to write the HTML. I have to use response.write because the buttons are generated inside a function() which exists under a <script runat="server"> tag and I cannot add Html directly.
If blnIsAssm = True Then
Response.Write("<img onclick=""changeNavPic('toggle" & lngCurrentLineNum & "'); toggleDisplay('tblparts" & lngCurrentLineNum & " ');"" id=""toggle" & lngCurrentLineNum & """src=""/Img/common/icons/Plus.gif"" width=""13"" height=""13"" border=""0"">")
Else
'print only blank gif
Response.Write("<img src=""/img/inv/template1/spacer.gif"" width=""10"" height=""10"" align=""left"" vspace=""0"" hspace=""0"" border=""0"">")
End If
<script language="JavaScript1.2" type="text/JavaScript1.2">
var getID= document.getElementById ? true : false;
function OpenPopup(varPage, varHeight) {
winstyle='height=' + varHeight + ',width=495,status=no,toolbar=no,location=no,menubar=yes,resizable=yes';
window.open(varPage,null,winstyle);
}
function AddLetter(varletter) {
// add a letter to the part number text box at the top of the page
if (document.topsearch.start.value.length >= 25) {
alert('To Many Letters For Part Number');
}
else {
document.topsearch.start.value = document.topsearch.start.value + varletter;
}
}
function BackSpacePartNum() {
//Makes the part number textbox lose one char in length
if (document.topsearch.start.value.length >= 1) {
var pnumStr = document.topsearch.start.value;
document.topsearch.start.value = pnumStr.substr(0,document.topsearch.start.value.length - 1);
}
}
function ClearPartNum() {
//Clears the part number search text at the top of the page
document.topsearch.start.value = '';
}
function ToggleMenu(objOn, objOff) {
if(!getID) return;
var objOn = getRef(objOn);
var objOff = getRef(objOff);
objOn.style.display = "block";
objOff.style.display = "none";
}
function MakeLeftBarNeutral() {
// return the left bar to everything DE-SELECTED
var obj = getRef('tblleft_partsupplier');
obj.style.display = "none";
}
function getRef(obj){
return (typeof obj == "string") ? document.getElementById(obj) : obj;
}
var getID= document.getElementById ? true : false;
// This toggles the actual display of the object, will completely remove it
// from the screen.
function toggleDisplay(obj){
if(!getID) return;
var obj = getRef(obj);
if(obj.style.display == "none"){
obj.style.display = "block";
}
else{
obj.style.display = "none";
}
}
// This will toggle the navigation pictures (plus, minus) for the given obj ref
// Used For Multi-Level Tables Such as Required Parts, Full Assembly List
function changeNavPic(obj){
if(!getID) return;
var obj = getRef(obj);
if(obj.src == '/Img/common/icons/plus.gif'){
obj.src = '/Img/common/icons/minus.gif';
}
else{
obj.src = '/Img/common/icons/plus.gif';
}
}
</script>

Why is this javascript object referring to a previous object's properties?

I am creating a class that can create any number of captchas on a page.I have a captcha class that I am using to instantiate new captcha objects c1 and c2. Here is my JS:
$(function(){
var captcha = {
parentForm : '',
container : '',
captcha_input : '',
number1 : 0,
number2 : 0,
createCaptcha : function(form_ID){
var newHtml;
this.parentForm = $('#' + form_ID);
this.container = this.parentForm.find('.captchaContainer');
this.number1 = this.randomNumber(10);
this.number2 = this.randomNumber(10);
newHtml = 'What does ' + this.number1 + ' plus ' + this.number2 + ' equal? <b class="required goldenrod" title="Required Field">*</b><br/><br/><input type="text" name="captcha">';
this.container.html(newHtml);
},
isValid : function(){
console.log(this.container);
this.captcha_input = this.container.find('input[name="captcha"]');
if (this.number1 + this.number2 == this.captcha_input.val()) {
this.captcha_input.css('background-color', '')
return true;
} else{
this.captcha_input.css('background-color', '#FFCCCC')
alert(this.number1 + ' plus ' + this.number2 + ' does not equal ' + this.captcha_input.val() + '. Please try again.');
this.captcha_input.focus();
return false;
}
},
randomNumber : function(max){ return Math.floor(Math.random()*(max+1)); }
}
var c1 = captcha,
c2 = captcha;
c1.createCaptcha("form1");
c2.createCaptcha("form2");
$('#form1 input[type="submit"]').click(function() {
if(c1.isValid()){
alert('Captcha is valid!');
}else{
return false;
}
});
$('#form2 input[type="submit"]').click(function() {
if(c2.isValid()){
alert('Captcha is valid!');
}else{
return false;
}
});
});
And my HTML:
<form id="form1">
<div class="captchaContainer"></div>
<input type="submit">
</form>
<form id="form2">
<div class="captchaContainer"></div>
<input type="submit">
</form>
When I click on form1's submit button, it seems like the isValid method is being ran for c2 and not c1 like I expect. Any idea why this is doing so?
A few things to note:
If I add more captcha instances and HTML, each submit button will run isValid on the last instance of captcha on click.
This needs to work for IE8+
Here is a fiddle of the code in action.
Any help would be greatly appreciated. Thanks!
c1 and c2 are both the same object. Use Object.create to create different instances. Object.create is not supported in old browsers, however there's a polyfill in the link I provided.
var c1 = Object.create(captcha),
c2 = Object.create(captcha);
You can also perform a deep copy of the object.
function deepCopy(obj) {
var res = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
res[key] = obj[key];
};
}
res.prototype = obj.prototype; // this would make it a deep copy.
return res;
};
var c1 = deepCopy(captcha);
While #plalx had a valid answer, it wasn't an ideal answer for my scenario. Since I cannot instantiate a class that was created from an object literal (without use of Object.create), I decided to refactor my class with a function instead:
$(function(){
var Captcha = function(){
var parentForm = '',
container = '',
captcha_input = '',
number1 = 0,
number2 = 0,
createCaptcha = function(form_ID){
var newHtml;
this.parentForm = $('#' + form_ID);
this.container = this.parentForm.find('.captchaContainer');
this.number1 = randomNumber(10);
this.number2 = randomNumber(10);
newHtml = 'What does ' + this.number1 + ' plus ' + this.number2 + ' equal? <b class="required goldenrod" title="Required Field">*</b><br/><br/><input type="text" name="captcha">';
this.container.html(newHtml);
},
isValid = function(){
this.captcha_input = this.container.find('input[name="captcha"]');
if (this.number1 + this.number2 == this.captcha_input.val()) {
this.captcha_input.css('background-color', '')
return true;
} else{
this.captcha_input.css('background-color', '#FFCCCC')
alert(this.number1 + ' plus ' + this.number2 + ' does not equal ' + this.captcha_input.val() + '. Please try again.');
this.captcha_input.focus();
return false;
}
},
randomNumber = function(max){ return Math.floor(Math.random()*(max+1)); }
return{
createCaptcha : createCaptcha,
isValid : isValid
}
}
// Instantiation of Captcha objects
var c1 = new Captcha,
c2 = new Captcha;
c1.createCaptcha("form1");
c2.createCaptcha("form2");
$('#form1 input[type="submit"]').click(function() { if(c1.isValid()){ alert('Captcha is valid!'); }else{ return false; } });
$('#form2 input[type="submit"]').click(function() { if(c2.isValid()){ alert('Captcha is valid!'); }else{ return false; } });
});
Here is the new working fiddle
TLDR: Since object literals cannot be instantiated without Object.create, I used a function to create the class instead, and then instantiated like so:
var c1 = new Captcha,
c2 = new Captcha;

Passing variable between javascript functions not working?

I tried using this method to pass a variable to the next function:
function a(form, ctr) {
var a = form;
var b = ctr;
b(ctr);
}
function b(ctr) {
var b = ctr;
}
The exact code is a lot more complicated as i'm using the POST method with ajax: function a begins upon a click and uses both the form and ctr parameters - it then goes to function b which only needs ctr - however this method of passing the variable hasn't worked. Any better solution?
function updateQuestion(form, ctr) {
console.log("Called updateQuestion");
var str1 = "toggleDiv";
var str2 = ctr;
var id = str1.concat(str2);
var divVar = document.getElementById(id);
console.log(divVar);
var getdate = new Date(); //Used to prevent caching during ajax call
if(XMLHttpRequestObject) {
console.log("XMLHttpRequestObject = TRUE");
var myVar = form.create_mcq_question.value;
console.log("MyVar = " + myVar);
var formQuestion = document.getElementById("formQuestion");
console.log("1");
XMLHttpRequestObject.open("POST","hiddent",true);
console.log("2");
XMLHttpRequestObject.onreadystatechange = handleServerResponse;
console.log("3");
XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
console.log("4" + document.getElementById("create_mcq_question").value);
var mcqid;
var mcqQuestion;
var mcqAnswerCorrect;
var mcqAnswerWrong1;
var mcqAnswerWrong2;
var mcqAnswerWrong3;
var mcqExplanation;
var error = 0;
if (form.create_mcq_question.value == "" || form.create_mcq_question.value == null ) {
error = 1;
}
else {
mcqQuestion = form.create_mcq_question.value
}
if (form.create_mcq_answer_correct.value == "" || form.create_mcq_answer_correct.value == null) {
mcqAnswerCorrect = "";
error = 1;
}
else {
mcqAnswerCorrect = form.create_mcq_answer_correct.value
}
if ((form.create_mcq_answer_wrong1.value == "" || form.create_mcq_answer_wrong1.value == null) && (form.create_mcq_answer_wrong2.value == "" || form.create_mcq_answer_wrong2.value == null) && (form.create_mcq_answer_wrong3.value == "" || form.create_mcq_answer_wrong3.value == null)) {
error = 1;
}
if (form.create_mcq_answer_wrong1.value == "" || form.create_mcq_answer_wrong1.value == null) {
mcqAnswerWrong1 = "";
}
else {
mcqAnswerWrong1 = form.create_mcq_answer_wrong1.value
}
if (form.create_mcq_answer_wrong2.value == "" || form.create_mcq_answer_wrong2.value == null) {
mcqAnswerWrong2 = "";
}
else {
mcqAnswerWrong2 = form.create_mcq_answer_wrong2.value
}
if (form.create_mcq_answer_wrong3.value == "" || form.create_mcq_answer_wrong3.value == null) {
mcqAnswerWrong3 = "";
}
else {
mcqAnswerWrong3 = form.create_mcq_answer_wrong3.value
}
if (form.create_mcq_explanation.value == "" || form.create_mcq_explanation.value == null) {
mcqExplanation = "";
}
else {
mcqExplanation = form.create_mcq_explanation.value
}
if (error == 0) {
XMLHttpRequestObject.send("create_mcq_question=" + mcqQuestion +
"&create_mcq_correct_answer=" + mcqAnswerCorrect +
"&create_mcq_wrong_answer1=" + mcqAnswerWrong1 +
"&create_mcq_answer_wrong2=" + mcqAnswerWrong2 +
"&create_mcq_answer_wrong3=" + mcqAnswerWrong3 +
"&create_mcq_explanation=" + mcqExplanation +
"&mcqid=" + mcqid );
console.log("5");
handleServerResponse(ctr);
}
else {
document.getElementById("divVar").innerHTML="Cannot update question - please ensure all required fields are filled!";
}
}
}
function handleServerResponse(ctr) {
var str1 = "toggleDiv";
var str2 = ctr;
var id = str1.concat(str2);
var divVar = document.getElementById(id);
console.log("Handle server response called");
if (XMLHttpRequestObject.readyState == 1) {
console.log("Loading");
document.getElementById(divVar).innerHTML="<img src=\"hidden">";
}
if (XMLHttpRequestObject.readyState == 4) {
console.log("4");
if(XMLHttpRequestObject.status == 200) {
document.getElementById(divVar).innerHTML=XMLHttpRequestObject.responseText; //Update the HTML Form element
console.log("divVar found");
console.log(divVar);
}
else {
document.getElementById(divVar).innerHTML="There was a problem updating your question - please try again!"; //Update the HTML Form element
console.log("divVar not found");
console.log(divVar);
}
}
}
And the button which starts the whole thing off:
<input type="button" value="Update My Question!" onclick="updateQuestion(this.form,<?php echo" $ctr"; ?>)">
Firebug showing the first function working, and calling the second one, which doesn't get the variable:
[02:21:42.106] Called updateQuestion
[02:21:42.106] [object HTMLDivElement]
[02:21:42.106] XMLHttpRequestObject = TRUE
[02:21:42.106] MyVar = Gram- bacteria are stained purple with gram staining, while gram+ bacteria are stained pink.
[02:21:42.106] 1
[02:21:42.107] 2
[02:21:42.107] 3
[02:21:42.107] 4Gram- bacteria are stained purple with gram staining, while gram+ bacteria are stained pink.
[02:21:42.108] Handle server response called
[02:21:42.108] Loading
[02:21:42.108] 5
[02:21:42.108] Handle server response called
[02:21:42.109] Loading
[02:21:42.649] Empty string passed to getElementById(). # hidden
[02:21:42.649] TypeError: document.getElementById(...) is null # hidden
[02:21:42.647] Handle server response called
[02:21:42.648] 4
There is already a variable called 'b' inside your function scope. That's why you get the error. If they are global functions, you can use:
function a(form, ctr) {
var a = form;
var b = ctr;
window.b(ctr);
}
function b(ctr) {
var b = ctr;
}
The following makes no sense really:
var b = ctr;
b(ctr);
Here the variable b is treated and invoked as function, and you pass a reference to itself as the parameter. Is that really our intention?
Edit: Now with the additional info, the problem is easy to explain. If you look at your log, you'll notice that the handleServerResponse is invoked several times. The first time "ctr" is passed as expected.
The problem is here:
XMLHttpRequestObject.onreadystatechange = handleServerResponse;
This sets a callback, and the callback will invoke your function without the "ctr" of course, which is why your code runs as it does. You could use an anonymous function so that a closure is used:
XMLHttpRequestObject.onreadystatechange = function() { handleServerResponse(ctr); };
You may want to read JavaScript: The Good Parts by Crockford, I think it would help to improve your JS coding significantly.

Categories

Resources