Cant get the session value using javascript in C# - javascript

I am trying to get 4 values from the session,while i get two of them,other two are missing.i am still learning so please bear with me if my question is too naive.I have this checkbox and two radio buttons in a tree view.
ASP.NET Code
<div class="control-label col-sm-1">
<asp:TreeView runat="server" ID="tvAi" Font-Bold="true" ShowLines="true" EnableClientScript="true"
ShowExpandCollapse="true" ShowCheckBoxes="All" >
</asp:TreeView>
<asp:HiddenField ID="hdMobile" runat="server" />
</div>
Now when i go to the chrome developer tool and check the values of the radio button the session values are binding well and shows like this.
<input type="radio" checked="checked" id="rad_01-02-00000622" name="rdoC1" value="01-02-00000622_Deposit_1_109861">
Those four values separated by '_' are accountNumber_accountType_officeId_customerId respectively.
The Javascript Code which sets session
$(function() {
$("[id*=tvAi] input[type=checkbox]").bind("click",
function() {
var table = $(this).closest("table");
if (table.next().length > 0 && table.next()[0].tagName == "DIV") {
//Is Parent CheckBox
var childDiv = table.next();
var isChecked = $(this).is(":checked");
if (isChecked) {
if ($('#CellNumberTextBox').val() == null || $('#CellNumberTextBox').val() === '') {
bootbox.alert(
"Please enter the Cell Number because you have asked for the MobileBankingService.");
this.checked = false;
$('#CellNumberTextBox').focus();
return false;
}
}
$("input[type=radio]", childDiv).each(function() {
if (isChecked) {
$(this).attr("checked", "checked");
return false;
} else {
$(this).removeAttr("checked");
}
});
}
});
$("[id*=tvAi] input[type=radio]").bind("click",
function() {
//hdMobile
var parentDIV = $(this).closest("DIV");
if ($(this).is(":checked")) {
if ($('#CellNumberTextBox').val() == null || $('#CellNumberTextBox').val() === '') {
bootbox.alert(
"Please enter the Cell Number because you have asked for the MobileBankingService.");
this.checked = false;
$('#CellNumberTextBox').focus();
return false;
}
$("input[type=checkbox]", parentDIV.prev()).attr("checked", "checked");
} else {
$("input[type=checkbox]", parentDIV.prev()).removeAttr("checked");
}
});
$("#SaveButton").bind("click",
function(e) {
$("#hdMobile").val("");
var tv = document.getElementById("<%= tvAi.ClientID %>");
var chkArray = tv.getElementsByTagName("input");
for (i = 0; i <= chkArray.length - 1; i++) {
if (i == 0) {
$.ajax({
type: "POST",
url: "AddNewCustomer.aspx/SetSession",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {
}
});
}
if (chkArray[i].type == 'radio') {
if (chkArray[i].checked == true) {
if ($('#CellNumberTextBox').val() == null || $('#CellNumberTextBox').val() === '') {
bootbox.alert(
"Please enter the Cell Number because you have asked for the MobileBankingService.");
$('#CellNumberTextBox').focus();
$.hideprogress();
return false;
if ($("#hdMobile").val() == "" || $("#hdMobile").val() == null) {
$("#hdMobile").val(chkArray[i].value);
} else {
$("#hdMobile").val($("#hdMobile").val() + "," + chkArray[i].value);
}
}
}
}
});
});
My Code behind setting the session
[WebMethod]
public static void SetSession()
{
System.Web.HttpContext.Current.Session["AccountMoney"] = "";
}
And binding treeview code
private void BindTreeViewForMobile()
{
_customerId = Convert.ToInt64(Session["CustomerId"]);
if (_customerId > 0)
{
DataTable dtAccount = new DataTable();
dtAccount = BusinessLayer.SMS.SmsSetup.GetActiveAccountListByCustomer(_customerId);
tvAi.Nodes.Clear();
int redindex = 1;
string accNumber = "";
var customerMobileBanking = BusinessLayer.SMS.MobileBankingSetup.GetMobileBankingCustomer(_customerId);
foreach (DataRow dr in dtAccount.Rows)
{
if (customerMobileBanking != null)
{
foreach (Common.SMS.MobileBankingSetup ss in customerMobileBanking)
{
if (ss.AccountNumber == dr["account_number"].ToString())
{
if (ss.FeeCharges)
{
accNumber = ss.AccountNumber;
break;
}
else
{
accNumber = "";
break;
}
}
}
}
TreeNode master = new TreeNode(dr["account_number"].ToString(), dr["account_number"].ToString());
master.ShowCheckBox = true;
tvAi.Nodes.Add(master);
master.SelectAction = TreeNodeSelectAction.None;
string sk = "";
if (accNumber != "")
{
if (accNumber == dr["account_number"].ToString())
{
master.Checked = true;
}
}
for (int i = 0; i <= 1; i++)
{
TreeNode child = new TreeNode(sk, sk);
child.SelectAction = TreeNodeSelectAction.None;
child.ShowCheckBox = false;
if (accNumber != "")
{
if (accNumber == dr["account_number"].ToString())
{
child.Text = "<input type='radio' checked='checked' id='rad_" + dr["account_number"].ToString() + "' name='rdoC" + redindex.ToString() + "' value ='" + sk + dr["account_number"].ToString() + "_" + dr["account"].ToString() + "_" + dr["office_id"].ToString() + "_" + _customerId.ToString() + "' />" + child.Text;
}
}
else
{
child.Text = "<input type='radio' id='rad_" + dr["account_number"].ToString() + "' name='rdoC" + redindex.ToString() + "' value ='" + sk + dr["account_number"].ToString() + "_" + dr["account"].ToString() + "_" + dr["office_id"].ToString() + "_" + _customerId.ToString() + "' />" + child.Text;
}
master.ChildNodes.Add(child);
}
redindex++;
}
}
}
The problem happens here when i am trying to get the session value in here
var sess = System.Web.HttpContext.Current.Session["AccountMoney"].ToString();
Here i only get the two session value not all 4.What am i doing wrong?Code must be too long for your time.any help appreciated.Thanks

I faced this before and search got me nowhere, went ahead and used cookies for the values I wanna read from JS. it works like a charm! Try it Get Cookies by name JS

Related

jQuery validate textbox 1 if there is same multiple value inside textbox 2

I have 2 textbox.
<input type="text" id="pcbaSerialNo"/>
and
<input type="text" id="pcbaSerialNoMask"/>
and the js
function handlePCBASerialNo(e)
{
var pcbaSerialNo = $(this).val();
var pcbaSerialNoMask = $('#pcbaSerialNoMask').val();
if(e.which ==13)
{
if(pcbaSerialNo == "")
{}
else
{
if(jQuery.inArray(pcbaSerialNo, pcbaSerialNoMask) != -1)
{
alert("Duplicate scan is not allowed!");
}
else
{
if(pcbaSerialNoMask == "")
{
$('#pcbaSerialNoMask').val(pcbaSerialNo);
$('#totalScan').val("1");
}
else
{
var totalScan = $('#totalScan').val();
$('#pcbaSerialNoMask').val(pcbaSerialNo + "," + pcbaSerialNoMask);
$('#totalScan').val(parseInt(totalScan) + 1);
}
}
$('#pcbaSerialNo').bind('keypress', handlePCBASerialNo);
$('#pcbaSerialNo').val("");
}
}
}
$('#pcbaSerialNo').keypress(handlePCBASerialNo);
The js function will run on enter key in textbox.
When scan on textbox #pcbaSerialNo, it will send the value to #pcbaSerialNoMask. (Example more than 1 value will be: test1, test2)
Now I need to validate #pcbaSerialNo to detect if there is same value.
My question, how to validate that textbox to prevent same value(duplicate)?
function handlePCBASerialNo(e)
{
var pcbaSerialNo = $(this).val();
var pcbaSerialNoMask = $('#pcbaSerialNoMask').val();
if(e.which ==13)
{
if(pcbaSerialNo == "")
{}
else
{
if(jQuery.inArray(pcbaSerialNo, pcbaSerialNoMask) != -1)
{
alert("Duplicate scan is not allowed!");
}
else
{
if(pcbaSerialNoMask == "")
{
$('#pcbaSerialNoMask').val(pcbaSerialNo);
$('#totalScan').val("1");
}
else
{
var totalScan = $('#totalScan').val();
$('#pcbaSerialNoMask').val(pcbaSerialNo + "," + pcbaSerialNoMask);
$('#totalScan').val(parseInt(totalScan) + 1);
}
}
$('#pcbaSerialNo').bind('keypress', handlePCBASerialNo);
$('#pcbaSerialNo').val("");
}
}
}
$('#pcbaSerialNo').keypress(handlePCBASerialNo);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input type="text" id="pcbaSerialNo"/>
<input type="text" id="pcbaSerialNoMask"/>
Just add below line before checking for existing value. You have to convert the string value to array while using inArray function.
pcbaSerialNoMask = pcbaSerialNoMask.split(",");
function handlePCBASerialNo(e)
{
var pcbaSerialNo = $(this).val();
var pcbaSerialNoMask = $('#pcbaSerialNoMask').val();
if(e.which ==13)
{
if(pcbaSerialNo == "")
{}
else
{
pcbaSerialNoMask = pcbaSerialNoMask.split(",");
if(jQuery.inArray(pcbaSerialNo, pcbaSerialNoMask) != -1)
{
alert("Duplicate scan is not allowed!");
}
else
{
if(pcbaSerialNoMask == "")
{
$('#pcbaSerialNoMask').val(pcbaSerialNo);
$('#totalScan').val("1");
}
else
{
var totalScan = $('#totalScan').val();
$('#pcbaSerialNoMask').val(pcbaSerialNo + "," + pcbaSerialNoMask);
$('#totalScan').val(parseInt(totalScan) + 1);
}
}
$('#pcbaSerialNo').bind('keypress', handlePCBASerialNo);
$('#pcbaSerialNo').val("");
}
}
}
$('#pcbaSerialNo').keypress(handlePCBASerialNo);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input type="text" id="pcbaSerialNo"/>
<input type="text" id="pcbaSerialNoMask"/>

Step identification bug in script using Material Steppers

I am working on a small AngularJS application with with Material Steppers.
I have to select items from two sections of the page and return true only if the items from both sections belong to the category with id (categoryID) 1.
Choosing items from section A already changes the variable this.isTriggerB, that should only be change after choosing from section A:
class Controller {
constructor($mdStepper) {
this.isTriggerA = false;
this.isTriggerB = false;
this.clickedStepNumber = 0;
getCurrentStep() {
this.steppers = this.$mdStepper('stepper');
const steps = this.steppers.steps;
steps.forEach((el, index) => {
let step = this.steppers.steps[index];
if (step.isClicked()) {
this.clickedStepNumber = step.stepNumber;
}
});
}
checkCategory() {
this.getCurrentStep();
if (this.filter.provider) {
let categoryID = parseInt(this.filter.category.id, 10);
console.log('Cid: ' + categoryID);
if (categoryID !== 1) {
this.isTestPassed = false;
} else {
if (parseInt(this.clickedStepNumber, 10 === 1)) {
this.isTriggerA = true;
console.log('Step: ' + this.clickedStepNumber);
console.log("A1: " + this.isTriggerA);
console.log("B1: " + this.isTriggerB);
}
if (parseInt(this.clickedStepNumber, 10 === 2)) {
this.isTriggerB = true;
console.log('Step: ' + this.clickedStepNumber);
console.log("A2: " + this.isTriggerA);
console.log("B2: " + this.isTriggerB);
}
if (this.isTriggerA === true && this.isTriggerB === true) {
this.isTestPassed = true;
} else {
this.isTestPassed = false;
}
}
}
}
}
The script should not even go inside if it is executing.
It should treat the 2 cases (steps) differently.
What am I doing wrong?
Move the banana:
if (categoryID !== 1) {
this.isTestPassed = false;
} else {
̶i̶f̶ ̶(̶p̶a̶r̶s̶e̶I̶n̶t̶(̶t̶h̶i̶s̶.̶c̶l̶i̶c̶k̶e̶d̶S̶t̶e̶p̶N̶u̶m̶b̶e̶r̶,̶ ̶1̶0̶ ̶=̶=̶=̶ ̶1̶)̶)̶ ̶{̶
if (parseInt(this.clickedStepNumber, 10) === 1) {
this.isTriggerA = true;
console.log('Step: ' + this.clickedStepNumber);
console.log("A1: " + this.isTriggerA);
console.log("B1: " + this.isTriggerB);
}
̶i̶f̶ ̶(̶p̶a̶r̶s̶e̶I̶n̶t̶(̶t̶h̶i̶s̶.̶c̶l̶i̶c̶k̶e̶d̶S̶t̶e̶p̶N̶u̶m̶b̶e̶r̶,̶ ̶1̶0̶ ̶=̶=̶=̶ ̶2̶)̶)̶ ̶{̶
if (parseInt(this.clickedStepNumber, 10) === 2) {
this.isTriggerB= true;
console.log('Step: ' + this.clickedStepNumber);
console.log("A2: " + this.isTriggerA);
console.log("B2: " + this.isTriggerB);
}

Javascript validation is not working in aspx page for allvalidate()

Here is my code:
<script type="text/javascript">
function Allvalidate() {
var ValidationSummary = "";
ValidationSummary += NameValidation;
ValidationSummary += EmailValidation;
ValidationSummary += MobilenumValidation;
if (ValidationSummary != "") {
alert("ValidationSummary");
return false;
}
else {
alert("Information Submitted Successfuly");
return true;
}
}
function NameValidation() {
var userid;
var controlid = document.getElementById("<%=Textusername.ClientID%>");
userid = controlid.value;
var val = /^[a-zA-Z]+$/;
if (userid == "") {
alert ("Enter your name" + "\n");
}
if (val.test(userid))
{
return "";
}
else{
alert("Name accepts only spaces and character" + "\n");
}
}
function EmailValidation() {
var userid;
var controlid = document.getElementById("<%=Textemail.ClientID%>");
userid = controlid;
var val = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (userid == "") {
alert("Enter your name" + "\n");
}
if (val.test(userid)) {
return "";
}
else {
alert("Email should be like this example xyz#abc.com");
}
}
function MobilenumValidation()
{
var userid;
var controlid = document.getElementById("<%=Textmobilenum.ClientID%>");
userid = controlid;
var val = /^[\d\.\-]+$/;
if (userid == "") {
alert("Enter your Mobile Number" + "\n");
}
if (val.test(userid)) {
return "";
}
else {
alert("PhoneNumber should be only in digits ");
}
}
</script>
aspx:
<asp:Button ID="btnsub" runat="server" Text="Submit"
OnClick="btnsub_Click" OnClientClick="javascript:Allvalidate()" />
The above code is not working, if i enter invalid mobile number,name and email it will accepted.
May i know, what is my mistake?
Thanks,

set focus to textbox form element following Validation

I have a number of fields on a form that I perform Validation on, which I then want to Focus on if the validation fails. The Validation works fine, i.e. rtnStr, but the focus() just won't land on any of the textbox fields, i.e. vCtrl. It remains on the Submit button.
<script language="javascript">
function ValidateForm() {
var rtnStr = "";
var vCtrl = "";
//Contact Details //
if (document.contactform.txtforename.value == "") {
rtnStr = rtnStr + " - Please enter your Forename.\n"
if (vCtrl == "") {
vCtrl = "txtforename";
}
}
if (document.contactform.txtSurname.value == "") {
rtnStr = rtnStr + " - Please enter your Surname.\n"
if (vCtrl == "") {
vCtrl = "txtSurname";
}
}
if (rtnStr != "") {
alert(rtnStr)
window.setTimeout(function () {
document.getElementById(vCtrl).focus();
}, 0);
return false;
}
else {
return true;
}
}
</script>
The problem is that vCtrl is a string which is the name of a form and not the id which document.getElementById(vCtrl).focus() is looking for. The way to fix this is to make vCtrl store the DOM element instead of a text string.
<script language="javascript">
function ValidateForm() {
var rtnStr = "";
var vCtrl = "";
//Contact Details //
if (document.contactform.txtforename.value == "") {
rtnStr = rtnStr + " - Please enter your Forename.\n"
if (vCtrl == "") {
vCtrl = document.contactform.txtforename;
}
}
if (document.contactform.txtSurname.value == "") {
rtnStr = rtnStr + " - Please enter your Surname.\n"
if (vCtrl == "") {
vCtrl = document.contactform.txtSurname;
}
}
if (rtnStr != "") {
alert(rtnStr)
vCtrl.focus();
return false;
}
else {
return true;
}
}
</script>
jsfiddle

Property of an array cannot be read

I have an extremely complex page that uses dynamic information to generate a layout with the correct and relevant information.
I am storing the data as an object. I have essentially 15 objects with multiple fields of user-submitted data.
Everything is stored and output correctly on the page, however now I am trying to validate and the information when the user tries to edit it from the edit page. The information is all being generated and laid out correctly, however I keep getting the same errors on the validation of the information.
The validation should go through and determine if a field was filled out correctly, and if it was not record a variable and add it to an alert variable. Then once it i done running the validation function it should pop up an alert with what fields still need to be filled in.
I keep receiving an error when it runs through the for loop toward the bottom. It says 'Uncaught TypeError' Cannot read property 'questionNumber' of undefined.
Above the code below I store the object and the properties, but this function is where everything is going awry. Note that there are also 15 arrays in the qtest object, but for the sake of simplification I removed all but a few.
I have gotten this to work on smaller, simpler forms, however because of the complexity and storage method I think this may be missing something or I might not be accessing something correctly. The code is very long and below, I've scaled back as much as possible. Please, if you have any insight or help you can provide I would be extremely grateful. Thank you!
var validateQ = function(qTextID, qAnswerType, TFID, MCID, MCText1, MCText2, MCText3, MCText4, VisRef, Youtube, Vimeo, ImgID) {
if (document.getElementById('ItemName').value == "") {
var quizName = true;
};
if (jQuery('select[name="CAT_Custom_14"]').val() == 'Quiz') {
if (jQuery(qTextID).val() == "") {
var qText = true;
};
if (jQuery('CAT_Custom_249').val() == " ") {
var quizscore1 = true;
};
if (jQuery(qAnswerType).val() == " ") {
var answertype = true;
} else if (jQuery(qAnswerType).val() == 'True/False') {
if (!jQuery(TFID).is(':checked')) {
var tfanswer = true;
var mcanswer = false;
};
} else if (jQuery(qAnswerType).val() == 'Multiple Choice') {
if (!jQuery(MCID).is(':checked')) {
var mcanswer = true;
var tfanswer = false;
};
if (jQuery(MCText1).val() == "" || jQuery(MCText2).val() == "" || jQuery(MCText3).val() == "" || jQuery(MCText4).val() == "") {
var mcTextfields = true;
} else {
mcTextfields = false;
};
};
} else if (jQuery('select[name="CAT_Custom_14"]').val() == 'Survey') {
if (jQuery(qTextID).val() == "") {
var qText = true;
};
if (!jQuery(sAnswers1).is(':checked')) {
var surveyAnswers1 = true;
} else {
surveyAnswers1 = false;
};
};
if (jQuery(VisRef).val() != " ") {
if (jQuery(VisRef).val() == "Youtube Video" && jQuery(Youtube).val() == "") {
var youtubeVal = true;
} else if (jQuery(VisRef).val() == "Vimeo Video" && jQuery(Vimeo).val() == "") {
var vimeoVal = true;
} else {
// validateImage(ImgID);
};
} else {
youtubeVal = false;
vimeoVal = false;
var tempImgCheck = false;
};
if (numCheck == 15) {
numCheck = 16;
};
var qName = "- Quiz or Survey Name\n";
var shortDescription = "- A short description of the Quiz/Survey\n";
var scoreMessage = "- A required passing score\n";
var QTextMessage = "- Question text\n";
var answerTMessage = "- An answer type\n";
var mcFields = "- The Multiple Choice answer fields\n";
var mcMessage = "- The correct Multiple Choice Answer\n"
var tfMessage = "- The correct True/False answer\n";
var vimMessage = "- A Vimeo Video code\n";
var ytMessage = "- A Youtube Video code\n";
var imgMessage = "- A reference image\n";
var surveyMessage = "- An answer type\n";
if (quizName == true || quizscore1 == true || qText == true || answertype == true || tfanswer == true || mcanswer == true || mcTextfields == true || youtubeVal == true || vimeoVal == true || tempImgCheck == true || surveyAnswers1 == true) {
var alertText = "It appears that you have not finished completing question" + question[i].questionNumber + ". Please ensure that you have completed the following question fields.\n";
if (quizName == true) {
alertText = alertText + qName;
};
if (quizscore1 == true) {
alertText = alertText + scoreMessage;
};
if (qText == true) {
alertText = alertText + QTextMessage;
};
if (answertype == true) {
alertText = alertText + answerTMessage;
};
if (tfanswer == true) {
alertText = alertText + tfMessage;
};
if (mcanswer == true) {
alertText = alertText + mcMessage;
};
if (mcTextfields == true) {
alertText = alertText + mcFields;
};
if (youtubeVal == true) {
alertText = alertText + ytMessage;
};
if (vimeoVal == true) {
alertText = alertText + vimMessage;
};
if (tempImgCheck == true) {
alertText = alertText + imgMessage;
};
if (surveyAnswers1 == true) {
alertText = alertText + surveyMessage;
};
if (quizscore1 == true) {
alertText = alertText + scoreMessage;
};
confirm(alertText);
};
};
var numCheck = 1;
var checkQuizQ = function() {
for (j = 1; j<= qtest.length; j++) {
numCheck = numCheck + 1;
if (qtest[j].questionNumber == "1") {
validateQ("CAT_Custom_3", "CAT_Custom_8", "CAT_Custom_19", "CAT_Custom_18", "CAT_Custom_4", "CAT_Custom_5", "CAT_Custom_6", "CAT_Custom_7", "CAT_Custom_9", "CAT_Custom_10", "CAT_Custom_11", "CAT_Custom_12", "CAT_Custom_230");
} else if (qtest[j].questionNumber == "2") {
validateQ("CAT_Custom_20", "CAT_Custom_21", "CAT_Custom_29", "CAT_Custom_26", "CAT_Custom_22", "CAT_Custom_23", "CAT_Custom_24", "CAT_Custom_25", "CAT_Custom_30", "CAT_Custom_31", "CAT_Custom_32", "CAT_Custom_33", "CAT_Custom_231");
} else if (qtest[j].questionNumber == "3") {
validateQ("CAT_Custom_35", "CAT_Custom_36", "CAT_Custom_37", "CAT_Custom_40", "CAT_Custom_41", "CAT_Custom_42", "CAT_Custom_43", "CAT_Custom_44", "CAT_Custom_45", "CAT_Custom_46", "CAT_Custom_47", "CAT_Custom_48", "CAT_Custom_232");
} else if (qtest[j].questionNumber == "4") {
};
};
document.getElementById('catcustomcontentbutton').style.display = "block";
document.getElementById("qsValidate").style.display = "none";
};
Since qtest looks like an array, its index starts from 0 to length - 1 so when j is length the value of qtest[j] will be undefined.
So change the loop as
for (j = 0; j< qtest.length; j++) {
//
}

Categories