Dynamic Validation of ASP.NET controls using Javascript/Jquery - javascript

I have multiple controls that need validation based on one condition: if one of the three controls have values, the fourth one must also contain a value. I have 4 sets of 4 controls, each numbered from one to four. I've written a quick and dirty function for validation, but it the code itself is unholy and defies most of the principal of good code design, its really ugly.
JavaScript Validation
$(document).ready(function () {
$("#<%= submitBtn.ClientID%>").click(function () {
var errorMessage = "";
var error = false;
var firstname1 = document.getElementById("<%=child1FN.ClientID%>").value;
var surname1 = document.getElementById("<%=child1LN.ClientID%>").value;
var relation1 = document.getElementById("<%=ddlRelationship1.ClientID%>").value;
var dob1 = document.getElementById("<%=DoB1.ClientID%>");
if ((firstname1 != "" || surname1 != "" || relation1 != "") && dob1.value == "") {
errorMessage += "First DoB needs to be filled. \n";
error=true;
}
var firstname2 = document.getElementById("<%=child2FN.ClientID%>").value;
var surname2 = document.getElementById("<%=child2LN.ClientID%>").value;
var relation2 = document.getElementById("<%=ddlRelationship2.ClientID%>").value;
var dob2 = document.getElementById("<%=DoB2.ClientID%>");
if ((firstname2 != "" || surname2 != "" || relation2 != "") && dob2.value == "") {
errorMessage += "Second DoB needs to be filled. \n";
error=true;
}
var firstname3 = document.getElementById("<%=child3FN.ClientID%>").value;
var surname3 = document.getElementById("<%=child3LN.ClientID%>").value;
var relation3 = document.getElementById("<%=ddlRelationship3.ClientID%>").value;
var dob3 = document.getElementById("<%=Dob3.ClientID%>");
if ((firstname3 != "" || surname3 != "" || relation3 != "") && dob3.value == "") {
errorMessage += "Third DoB needs to be filled. \n";
error=true;
}
var firstname4 = document.getElementById("<%=child4FN.ClientID%>").value;
var surname4 = document.getElementById("<%=child4LN.ClientID%>").value;
var relation4 = document.getElementById("<%=ddlRelationship4.ClientID%>").value;
var dob4 = document.getElementById("<%=DoB4.ClientID%>");
if ((firstname4 != "" || surname4 != "" || relation4 != "") && dob4.value == "") {
errorMessage += "Fourth DoB needs to be filled. \n";
error=true;
}
if (error) {
alert(errorMessage);
return false;
}
});
});
The problem is, that I cannot use a for loop as asp doesn't accept a javascript value for the following source
<tr>
<th>
Child one:
</th>
</tr>
<tr>
<td>
<asp:TextBox ID="child1FN" runat="server" />
</td>
<td>
<asp:TextBox ID="child1LN" runat="server" />
</td>
<td>
<asp:DropDownList ID="ddlRelationship1" runat="server" ></asp:DropDownList>
</td>
<td>
<telerik:RadDatePicker ID="DoB1" runat="server" Culture="English (Australia)" MinDate="1 Jan 1920" class="datePickerDOB">
</telerik:RadDatePicker>
</td>
</tr>
<tr>
<th>
Child two:
</th>
</tr>
<tr>
<td>
<asp:TextBox ID="child2FN" runat="server" />
</td>
<td>
<asp:TextBox ID="child2LN" runat="server" />
<td>
<asp:DropDownList ID="ddlRelationship2" runat="server"></asp:DropDownList>
</td>
<td>
<telerik:RadDatePicker ID="DoB2" runat="server" Culture="English (Australia)" MinDate="1 Jan 1920" class="datePickerDOB">
</telerik:RadDatePicker>
</td>
</tr> . . .
I've only shown the first two rows of the source which has been simplified and removed styling tags for legibility. Like I wrote; there's 4 rows and they're similar to the above code but with just a different ID.
I was wondering if anybody had any suggestions to improve this code?
Rendered Telerick Code
<span class="riSingle RadInput RadInput_MetroTouch" id="ctl00_cphBody_DoB1_dateInput_wrapper" style="width: 100%; display: block;">
<input name="ctl00$cphBody$DoB1$dateInput" class="riTextBox riEnabled" id="ctl00_cphBody_DoB1_dateInput" style="padding-left: 2px; font-size: 12px;" type="text">
<input name="ctl00_cphBody_DoB1_dateInput_ClientState" id="ctl00_cphBody_DoB1_dateInput_ClientState" type="hidden" value='{"enabled":true,"emptyMessage":"","validationText":"","valueAsString":"","minDateStr":"20202020-JanJan-0101-0000-0101-0000","maxDateStr":"99999999-DecDec-3131-0000-1212-0000","lastSetTextBoxValue":""}' autocomplete="off">
</span>

Giv the container an ID, this will make your life easier with jQuery (and is a little more efficient than using classes etc as selectors). Also, add a class to your "data" rows
<table id="formElements">
<tr><th>Child 1</th></tr>
<tr class="data"><!-- Form Elelemt Cells --></tr>
<!-- etc -->
</table>
Javascript
$(document).ready(function () {
var formTable = $("#formElements");
/*console.log(formTable); */
$("#submitBtn").click(function (index) {
var errorMessage = "";
var error = false;
//Use the fact we have the elements in a row to our advantage
$(formTable).find("tr.data").each(function (index) {
var firstName = $(this).find("td:nth-child(1) input").val();
var lastName = $(this).find("td:nth-child(2) input").val();
var relationship = $(this).find("td:nth-child(3) select").val();
//Taking a punt the value is in the hidden form field for DOB;
var dob = $(this).find("td:nth-child(4) input[type='hidden']").val();
//Use console to try and work out what telrik uses to hold the data
console.log($(this).find("td:nth-child(4) input[type='hidden']"));
console.log($(this).find("td:nth-child(4) input[type='text']"));
if ((firstName != "" || lastName != "" || relationship != "") && dob == "") {
errorMessage += "DoB " + (index + 1) + " needs to be filled. \n";
error = true;
}
});
if (error) {
alert(errorMessage);
return false;
}
});
});
This is a little quick and dirty and handling the telrick control could be tricky.
Demo
If you can use ASP.net inbuild validators to validate the telrik control you may be better off using them. Even stil, using a custom ASP.net validator should work in a similar fasion.
Update
I've added a couple of debug lines using console.log to try and help with the telrik controls.
Slighly hacky version
Keep the HTML as per above.
Javascript
$(document).ready(function () {
var formTable = $("#formElements");
/*console.log(formTable); */
//Create an array of the DatePicker controls
//You could replace the jQuery selectro with:
//document.getElementById("<%=DoB1.ClientID%>")
var arrDoB = new Array(
$("#<%=DoB1.ClientID%>"),
$("#<%=DoB2.ClientID%>"),
$("#<%=DoB3.ClientID%>"),
$("#<%=DoB4.ClientID%>")
);
$("#submitBtn").click(function (index) {
var errorMessage = "";
var error = false;
//Use the fact we have the elements in a row to our advantage
$(formTable).find("tr.data").each(function (index) {
var firstName = $(this).find("td:nth-child(1) input").val();
var lastName = $(this).find("td:nth-child(2) input").val();
var relationship = $(this).find("td:nth-child(3) select").val();
//Get the value of the datepicker control from the array
var dob = arrDoB[index].value;
if ((firstName != "" || lastName != "" || relationship != "") && dob == "") {
errorMessage += "DoB " + (index + 1) + " needs to be filled. \n";
error = true;
}
});
if (error) {
alert(errorMessage);
return false;
}
});
});

Related

How to pass a text box value from one html page to another

I would like to pass a textbox value from one html page to another html page and print on the second page. I have page1.html and page2.html. I dont want to use asp or php any server side scripting language simply i want to do using javascript or jquery anyone which is easy.
<script>
function checkPassword() {
if (document.getElementById("name").value == "") {
document.getElementById("studname").innerHTML = "Enter your name. Field cannot be left blank.";
alert('Enter your name.');
return false;
}
else if (document.getElementById("class").value == "select") {
document.getElementById("classname").innerHTML = "Select your class.";
alert('Select your class.');
return false;
}
else if (document.getElementById("section").value == "select") {
document.getElementById("secname").innerHTML = "Select your section.";
alert('Select your section.');
return false;
}
else if (document.getElementById("password").value == "") {
document.getElementById("passwordname").innerHTML = "Enter your password.";
alert('Enter your password.');
return false;
}
else if (document.getElementById('password').value == '12345' && document.getElementById("class").value == 'V' && document.getElementById("section").value == 'a') {
location.href = 'Start.html?name=' + document.getElementById('name').value + '?class=' + document.getElementById('class').value;
}
else {
alert('Your Class, Section and Password doesn\'t match. Please re-enter correctly.');
return false;
}
}
</script>
Run this code, u ll get the output what u needed.
html1.html
<html>
<form type=get action="html2.html">
<table>
<tr>
<td>First Name:</td>
<td><input type=text name=firstname size=10></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type=text name=lastname size=10></td>
</tr>
<tr>
<td>Age:</td>
<td><input type=text name=age size=10></td>
</tr>
<tr>
<td colspan=2><input type=submit value="Submit">
</td>
</tr>
</table>
</form>
</html>
html2.html
<html>
<script LANGUAGE="JavaScript">
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}
params = getParams();
firstname = unescape(params["firstname"]);
lastname = unescape(params["lastname"]);
age = unescape(params["age"]);
document.write("firstname = " + firstname + "<br>");
document.write("lastname = " + lastname + "<br>");
document.write("age = " + age + "<br>");
</script>
</html>

Filter for certain values in a JSON

I have a JSON Object like this:
var test = {"employees": [
{"name":"John","klasse":12,"fach":"BW"},
{"name":"max", "klasse":13,"fach":"E"},
{"name":"Stef","klasse":14,"fach":"D"},
{"name":"abc", "klasse":15,"fach":"AM"},
{"name":"def", "klasse":17,"fach":"AM"},
{"name":"John","klasse":12,"fach":"D"}
]};
In my HTML file I have 3 input fields, which should give me the values to search in the JSON object.
<form ng-controller="Suche">
<span>Suchbegriff: </span><input type="text" ng-model="suchbegriff"> <br>
<span>Klasse: </span><input type="text" ng-model="klasse"> <br>
<span>Fach: </span><input type="text" ng-model="fach"> <br>
<input type="submit" ng-click="submit()">
<input type="submit" ng-click="sort()" value="Sort">
<table>
<tr>
<td>Name</td>
<td>Klasse</td>
<td>Fach</td>
</tr>
<tr ng-repeat="result in results">
<td>{{result.name}}</td>
<td>{{result.klasse}}</td>
<td>{{result.fach}}</td>
</tr>
<tr ng-hide="filter" ng-repeat="erg in json.employees">
<td>{{erg.name}}</td>
<td>{{erg.id}}</td>
<td>{{erg.fach}}</td>
</tr>
</table>
Now my Problem. For instance I want search for the name "John" and fach "D".
My current output would be the following:
As you can see I donĀ“t get the output I want. It should only list the third row with name "John" klasse "12" and fach "D".
How can I fix this problem?
This is my function so far:
$scope.submit = function () {
$scope.results = [];
var searchField = "name",
searchField2 = "klasse",
searchField3 = "fach";
var search = $scope.suchbegriff,
search_class = $scope.klasse,
search_subject = $scope.fach;
if(
search_subject == null || search_subject == ''
&& search == null || search == ''
&& search_class == null || search_class == ''
) {
$scope.filter = false;
}
for (var i=0 ; i < test.employees.length ; i++) {
if (
test.employees[i][searchField] == search ||
test.employees[i][searchField2] == search_class ||
test.employees[i][searchField3] == search_subject
) {
$scope.filter = true;
$scope.results.push(test.employees[i]);
}
}
};
I appreciate any help!
The problem is that in the for... loop, you are pushing employees that match either of the search criteria instead of pushing those that match all the search criteria provided. Try the following:
$scope.submit = function () {
$scope.results = [];
var searchField = "name",
searchField2 = "klasse",
searchField3 = "fach";
var search = $scope.suchbegriff,
search_class = $scope.klasse,
search_subject = $scope.fach;
var hasSearch = !(search == null || search == ''),
hasSearch_class = !(search_class == null || search_class == ''),
hasSearch_subject = !(search_subject == null || search_subject == '');
$scope.filter = hasSearch || hasSearch_class || search_subject;
for (var i=0 ; i < test.employees.length ; i++) {
if (
(!hasSearch || test.employees[i][searchField] == search) &&
(!hasSearch_class || test.employees[i][searchField2] == search_class) &&
(!hasSearch_subject || test.employees[i][searchField3] == search_subject)
) {
$scope.results.push(test.employees[i]);
}
}
};
Take a look at this pen I've created.
CodePen
app.filter('employeeFilter', function() {
return function(input, name, k, f) {
name = name.toLowerCase();
k = k.toLowerCase();
f = f.toLowerCase();`
return input.filter(function(item) {
return item.name.toLowerCase().includes(name) && item.klasse.toString().includes(k) && item.fach.toLowerCase().includes(f);
});
}
})
These kind of things are easier if left to filters. You're using three parameters, so, I don't think that angular's default filter would be of any use. You can make your own simply. See the filter in the pen.
Hope it helps.

Add 2 numbers and show result on label with comma's

I am writing some code for some functionality
My first text box
<asp:TextBox ID="txtLeasePaymentFixed" type="text" runat="server" class="number" CssClass="form-control" Style="text-align: right" TabIndex="101" placeholder="e.g 123,456,789" onKeyUp="fncCalculateSum()" onBlur="fncCalculateSum()"></asp:TextBox>
My second text Box is
<asp:TextBox ID="txtLeasePaymentVairable" type="text" runat="server" CssClass="form-control" Style="text-align: right" TabIndex="102" placeholder="e.g 123,456,789" onKeyUp="fncCalculateSum()" onBlur="fncCalculateSum()"></asp:TextBox>
Label On which Toltal shows is like this
<asp:Label ID="lbltotal" runat="server" Text=""></asp:Label>
Function calling onblur and onkeyUp is like this:
function fncCalculateSum() {
var LeasePaymentFixed = $('#MainContent_txtLeasePaymentFixed');
var LeasePaymentVariable = $('#MainContent_txtLeasePaymentVairable');
if (LeasePaymentFixed.val() == '' || LeasePaymentFixed.val() == null) {
PaymentFixed = 0;
}
else {
PaymentFixed = parseFloat(LeasePaymentFixed.val());
}
if (LeasePaymentVariable.val() == '' || LeasePaymentVariable.val() == null) {
PaymentVariable = 0;
}
else {
PaymentVariable = parseFloat(LeasePaymentVariable.val());
}
(Sum) = PaymentFixed + PaymentVariable
if ((LeasePaymentFixed.val().trim() == '' && LeasePaymentVariable.val().trim() == '') || (LeasePaymentFixed.val() == null && LeasePaymentVariable.val() == null)) {
$("#MainContent_lbltotal").text('');
}
else {
$("#MainContent_lbltotal").html(parseFloat(Sum));
}
}
Now I am using jQuery code to apply comma in international format after every 3 digits like this
$('#MainContent_txtLeasePaymentFixed,#MainContent_txtLeasePaymentVairable,#MainContent_lbltotal').keyup(function(event){
// skip for arrow keys
if(event.which >= 37 && event.which <= 40){
event.preventDefault();
}
var $this = $(this);
var num = $this.val().replace(/,/gi, "").split("").reverse().join("");
var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));
console.log(num2);
// the following line has been simplified. Revision history contains original.
$this.val(num2);
});
function RemoveRougeChar(convertString){
if(convertString.substring(0,1) == ","){
return convertString.substring(1, convertString.length)
}
return convertString;
}
When I write digits in the first text box it comes with commas, that's fine.
Same when I write in the second text box, but it don't show sum of all the digits on label.
Watch out! You're losing data with your comma to parseFloat conversion:
let foo = 21231323.246;
let bar = foo.toLocaleString("en-US"); // "21,231,323.246"
console.log(parseFloat(bar)); // 21
You should check your conversions and make sure you're working on the right numbers.

JavaScript Error: Unable to get property 'style' of undefined or null reference?

I created DropDownList with checkboxes
There was an error in js:
document.onclick = check;
function check(e) {
var target = (e && e.target) || (event && event.srcElement);
var obj = document.getElementById('divChkList');
var obj1 = document.getElementById('ddlChkList');
if (target.id != "alst" && !target.id.match("chkLstItem")) {
if (!(target == obj || target == obj1)) {
obj.style.display = 'none'
}
html :
<table>
<tr>
<td valign="top" style="width: 165px">
<asp:PlaceHolder ID="phDDLCHK" runat="server"></asp:PlaceHolder>
</td>
<td valign="top">
<asp:Button ID="btn" runat="server" Text="Get Checked" OnClick="btn_Click" />
</td>
<td valign="top">
<asp:Label ID="lblSelectedItem" runat="server"></asp:Label>
</td>
</tr>
</table>
<asp:HiddenField ID="hidList" runat="server" />
Here is the code cs in Page_load
Here I've defined dropdownlist:
DropDownList ddl = new DropDownList();
ddl.ID = "ddlChkList";
ListItem lstItem = new ListItem();
ddl.Items.Insert(0, lstItem);
ddl.Width = new Unit(155);
ddl.Attributes.Add("onmousedown", "showdivonClick()");
CheckBoxList chkBxLst = new CheckBoxList();
chkBxLst.ID = "chkLstItem";
chkBxLst.Attributes.Add("onmouseover", "showdiv()");
DataTable dtListItem = GetListItem();
int rowNo = dtListItem.Rows.Count;
string lstValue = string.Empty;
string lstID = string.Empty;
for (int i = 0; i < rowNo - 1; i++)
{
lstValue = dtListItem.Rows[i]["Value"].ToString();
lstID = dtListItem.Rows[i]["ID"].ToString();
lstItem = new ListItem("" + lstValue + "", dtListItem.Rows[i]["ID"].ToString());
lstItem.Attributes.Add("onclick", "getSelectedItem('" + lstValue + "','" + i + "','" + lstID + "','listItem');");
chkBxLst.Items.Add(lstItem);
}
System.Web.UI.HtmlControls.HtmlGenericControl div = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
div.ID = "divChkList";
div.Controls.Add(chkBxLst);
div.Style.Add("border", "black 1px solid");
div.Style.Add("width", "160px");
div.Style.Add("height", "180px");
div.Style.Add("overflow", "AUTO");
div.Style.Add("display", "none");
phDDLCHK.Controls.Add(ddl);
phDDLCHK.Controls.Add(div);
The error here obj.style.display = 'none'
I have been looking online for a fix and nothing is working?
What am I doing wrong?
HMTL provided in the question does not have an element with ID divChkList
Even if it existed, The correct way of calling an ASP.net control would be like this
var obj = document.getElementById('<%=divChkList.ClientID%>');
This is because asp.net does not render the same id you specify in the markup of a server control , unless to specify to keep it static.

Javascript double click text transform into textbox

What is the javascipt code that will edit a text on double click. The process is I have a text and if I double click it, a text box will appear, and if I press enter the word will change depends on what you've type.
Sample
This is sample text. $nbsp;$nbsp; --> if I double click it a textbox will appear.
<input type="text" value="This is sample text." name="" />
Sorry for asking this. I am a newbie in javascript
Here is a great example.
I'm going to paste in the script from that example so that it's preserved in case that link goes away, but you should follow the link -- the article does a great job of breaking the script down line by line and explaining what it does. A great learning opportunity for javascript.
var editing = false;
if (document.getElementById && document.createElement) {
var butt = document.createElement('BUTTON');
var buttext = document.createTextNode('Ready!');
butt.appendChild(buttext);
butt.onclick = saveEdit;
}
function catchIt(e) {
if (editing) return;
if (!document.getElementById || !document.createElement) return;
if (!e) var obj = window.event.srcElement;
else var obj = e.target;
while (obj.nodeType != 1) {
obj = obj.parentNode;
}
if (obj.tagName == 'TEXTAREA' || obj.tagName == 'A') return;
while (obj.nodeName != 'P' && obj.nodeName != 'HTML') {
obj = obj.parentNode;
}
if (obj.nodeName == 'HTML') return;
var x = obj.innerHTML;
var y = document.createElement('TEXTAREA');
var z = obj.parentNode;
z.insertBefore(y,obj);
z.insertBefore(butt,obj);
z.removeChild(obj);
y.value = x;
y.focus();
editing = true;
}
function saveEdit() {
var area = document.getElementsByTagName('TEXTAREA')[0];
var y = document.createElement('P');
var z = area.parentNode;
y.innerHTML = area.value;
z.insertBefore(y,area);
z.removeChild(area);
z.removeChild(document.getElementsByTagName('button')[0]);
editing = false;
}
document.onclick = catchIt;
I wanted to know how it works as I have seen it on many websites. And I build it using jQuery
$(document).dblclick(function(event) {
var id = event.target.id; //id
// var id = $(this).attr('id');
if (id == "") {
console.log("nope");
} else {
id = "#" + id + "";
console.log(typeof(id)); //concatenated with #
text = $(id).text().trim();
console.log(text); //asscociated text
$(id).html('<textarea name="" id="tex" cols="10" rows="1" onkeypress="myFunction(event)">' + text + '</textarea>');
// alert(id);
}
})
function myFunction(event) {
var x = event.code;
var id = $(this).attr('id');
parentId = event.path[1].id;
parentId = "#" + parentId + "";
if (x == 'Enter') {
name = $('#tex').val();
$(parentId).text(name);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container mt-3">
<h2>Striped Rows</h2>
<p>The .table-striped class adds zebra-stripes to a table:</p>
<table class="table table-striped">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td id="name1" class="name">
john
</td>
<td id="sirname1">Doe</td>
<td id="email1">john#example.chdm som</td>
</tr>
<tr>
<td id="name2" class="name">Mary</td>
<td id="sirname2">Moe</td>
<td id="email2">mary#example.com</td>
</tr>
<tr>
<td id="name3" class="name">July</td>
<td id="sirname3">Dooley</td>
<td id="email3">july#example.com</td>
</tr>
</tbody>
</table>
</div>

Categories