Javascript double click text transform into textbox - javascript

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>

Related

How can I save data from dynamically added inputs into database table using SQL?

I need some help in explaining to me how I can save data from dynamically added inputs to my SQL database table.
What I am doing is creating an online quote / invoice web site whereby one can create the quote and then save the data or print to pdf. (I am currently working on the "save the data" bit :-) )
So by adding the input fields (text boxes) I use a java script as per below:
(function (document) {
var
head = document.head = document.getElementsByTagName('head')[0] || document.documentElement,
elements = 'article aside audio bdi canvas data datalist details figcaption figure footer header
hgroup mark meter nav output picture progress section summary time video x'.split(' '),
elementsLength = elements.length,
elementsIndex = 0,
element;
while (elementsIndex < elementsLength) {
element = document.createElement(elements[++elementsIndex]);
}
element.innerHTML = 'x<style>' +
'article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}' +
'audio[controls],canvas,video{display:inline-block}' +
'[hidden],audio{display:none}' +
'mark{background:#FF0;color:#000}' +
'</style>';
return head.insertBefore(element.lastChild, head.firstChild);
})(document);
(function (window, ElementPrototype, ArrayPrototype, polyfill) {
function NodeList() { [polyfill] }
NodeList.prototype.length = ArrayPrototype.length;
ElementPrototype.matchesSelector = ElementPrototype.matchesSelector ||
ElementPrototype.mozMatchesSelector ||
ElementPrototype.msMatchesSelector ||
ElementPrototype.oMatchesSelector ||
ElementPrototype.webkitMatchesSelector ||
function matchesSelector(selector) {
return ArrayPrototype.indexOf.call(this.parentNode.querySelectorAll(selector), this) > -1;
};
ElementPrototype.ancestorQuerySelectorAll = ElementPrototype.ancestorQuerySelectorAll ||
ElementPrototype.mozAncestorQuerySelectorAll ||
ElementPrototype.msAncestorQuerySelectorAll ||
ElementPrototype.oAncestorQuerySelectorAll ||
ElementPrototype.webkitAncestorQuerySelectorAll ||
function ancestorQuerySelectorAll(selector) {
for (var cite = this, newNodeList = new NodeList; cite = cite.parentElement;) {
if (cite.matchesSelector(selector)) ArrayPrototype.push.call(newNodeList, cite);
}
return newNodeList;
};
ElementPrototype.ancestorQuerySelector = ElementPrototype.ancestorQuerySelector ||
ElementPrototype.mozAncestorQuerySelector ||
ElementPrototype.msAncestorQuerySelector ||
ElementPrototype.oAncestorQuerySelector ||
ElementPrototype.webkitAncestorQuerySelector ||
function ancestorQuerySelector(selector) {
return this.ancestorQuerySelectorAll(selector)[0] || null;
};
})(this, Element.prototype, Array.prototype);
function generateTableRow() {
var emptyColumn = document.createElement('tr');
emptyColumn.innerHTML = '<td><a class="cut" title="Remove Item">-</a><span contenteditable></span>
</td>' +
'<td><span contenteditable></span></td>' +
'<td><span data-prefix>₹</span><span contenteditable>0.00</span></td>' +
'<td><span contenteditable>1</span></td>' +
'<td><span data-prefix>₹</span><span>0.00</span></td>';
return emptyColumn;
}
function parseFloatHTML(element) {
return parseFloat(element.innerHTML.replace(/[^\d\.\-]+/g, '')) || 0;
}
function parsePrice(number) {
return number.toFixed(2).replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1,');
}
function updateNumber(e) {
var
activeElement = document.activeElement,
value = parseFloat(activeElement.innerHTML),
wasPrice = activeElement.innerHTML == parsePrice(parseFloatHTML(activeElement));
if (!isNaN(value) && (e.keyCode == 38 || e.keyCode == 40 || e.wheelDeltaY)) {
e.preventDefault();
value += e.keyCode == 38 ? 1 : e.keyCode == 40 ? -1 : Math.round(e.wheelDelta * 0.025);
value = Math.max(value, 0);
activeElement.innerHTML = wasPrice ? parsePrice(value) : value;
}
updateInvoice();
}
function updateInvoice() {
var total = 0;
var cells, price, total, a, i;
for (var a = document.querySelectorAll('table.inventory tbody tr'), i = 0; a[i]; ++i) {
// get inventory row cells
cells = a[i].querySelectorAll('span:last-child');
// set price as cell[2] * cell[3]
price = parseFloatHTML(cells[2]) * parseFloatHTML(cells[3]);
// add price to total
total += price;
// set row total
cells[4].innerHTML = price;
}
// get label cells
label_cells = document.querySelectorAll('table.balance th span:last-child');
tax_rate = label_cells[1].innerHTML / 100;
// get balance cells
cells = document.querySelectorAll('table.balance td:last-child span:last-child');
// set total
cells[0].innerHTML = total;
// set tax
cells[1].innerHTML = parsePrice(total * tax_rate);
// set balance and meta balance
cells[2].innerHTML = document.querySelector('table.meta tr:last-child td:last-child span:last-
child').innerHTML = parsePrice(total + parseFloatHTML(cells[1]));
var prefix = document.querySelector('#prefix').innerHTML;
for (a = document.querySelectorAll('[data-prefix]'), i = 0; a[i]; ++i) a[i].innerHTML = prefix;
for (a = document.querySelectorAll('span[data-prefix] + span'), i = 0; a[i]; ++i) if
(document.activeElement != a[i]) a[i].innerHTML = parsePrice(parseFloatHTML(a[i]));
}
function onContentLoad() {
updateInvoice();
var
input = document.querySelector('input'),
image = document.querySelector('img');
function onClick(e) {
var element = e.target.querySelector('[contenteditable]'), row;
element && e.target != document.documentElement && e.target != document.body && element.focus();
if (e.target.matchesSelector('.add')) {
document.querySelector('table.inventory tbody').appendChild(generateTableRow());
}
else if (e.target.className == 'cut') {
row = e.target.ancestorQuerySelector('tr');
row.parentNode.removeChild(row);
}
updateInvoice();
}
function onEnterCancel(e) {
e.preventDefault();
image.classList.add('hover');
}
function onLeaveCancel(e) {
e.preventDefault();
image.classList.remove('hover');
}
function onFileInput(e) {
image.classList.remove('hover');
var
reader = new FileReader(),
files = e.dataTransfer ? e.dataTransfer.files : e.target.files,
i = 0;
reader.onload = onFileLoad;
while (files[i]) reader.readAsDataURL(files[i++]);
}
function onFileLoad(e) {
var data = e.target.result;
image.src = data;
}
if (window.addEventListener) {
document.addEventListener('click', onClick);
document.addEventListener('mousewheel', updateNumber);
document.addEventListener('keydown', updateNumber);
document.addEventListener('keydown', updateInvoice);
document.addEventListener('keyup', updateInvoice);
input.addEventListener('focus', onEnterCancel);
input.addEventListener('mouseover', onEnterCancel);
input.addEventListener('dragover', onEnterCancel);
input.addEventListener('dragenter', onEnterCancel);
input.addEventListener('blur', onLeaveCancel);
input.addEventListener('dragleave', onLeaveCancel);
input.addEventListener('mouseout', onLeaveCancel);
input.addEventListener('drop', onFileInput);
input.addEventListener('change', onFileInput);
}
}
window.addEventListener && document.addEventListener('DOMContentLoaded', onContentLoad);
function serial_file() {
document.getElementById("serial").value = Date.now();
}
function un_serial_file() {
document.getElementById("serial").value = "";
}
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
today = dd + '/' + mm + '/' + yyyy;
today_form = yyyy + '-' + dd + '-' + mm + ' ';
var serial = Date.now();
function myprint() {
window.print();
}
And on my "NewQuote.aspx" Page I have this:
<div class="container-fluid">
<div style="display: inline-block; float: left;">
<asp:DropDownList runat="server" ID="drpClientSelect" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"></asp:DropDownList><br />
<br />
<asp:Label runat="server" Text="First Name" ID="lblFirstName"></asp:Label><br />
<asp:Label runat="server" Text="Last Name" ID="lblLastName"></asp:Label><br />
<asp:Label runat="server" Text="Company Name" ID="lblCompanyName"></asp:Label><br />
<asp:Label runat="server" Text="Address" ID="lblAddress"></asp:Label><br />
<asp:Label runat="server" Text="Email" ID="lblEmail"></asp:Label><br />
<asp:Label runat="server" Text="Contact Number" ID="lblContactNumber"></asp:Label><br />
<asp:Label runat="server" Text="Web Site Address" ID="lblWebsite"></asp:Label><br />
</div>
<br />
<div>
<table class="meta" id="top_data_table">
<tbody>
<tr class="" id="invoice_number_row">
<th class="bold"><span class="invoice" id="invoice">Invoice #</span></th>
<td>
<input type="text" name="fname" /></td>
</tr>
<tr id="daterow">
<th class="bold"><span class="date" id="date">Date</span></th>
<td><span>
<input type="date" id="theDate" /></span></td>
</tr>
<tr class="" id="total_block">
<th class="bold"><span class="amount" id="amount">Ammout</span></th>
<td><span id="prefix">R</span><span></span></td>
</tr>
</tbody>
</table>
</div>
</div>
<hr />
<br />
<div class="min_height">
<table class="inventory">
<thead>
<tr>
<th class="bold">
<span class="item" id="item">Item</span>
</th>
<th class="bold">
<span class="description" id="description">Description</span>
</th>
<th class="bold">
<span class="rate" id="rate">Rate</span>
</th>
<th class="bold">
<span class="quantity" id="quantity">Quantity</span>
</th>
<th class="bold">
<span class="price" id="price">Price</span>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a class="cut" title="Remove Item">-</a>
<span contenteditable="true"></span>
</td>
<td>
<span contenteditable="true"></span>
</td>
<td>
<span data-prefix="">R</span>
<span contenteditable="true">0.00</span>
</td>
<td>
<span contenteditable="true">1</span>
</td>
<td>
<span data-prefix="">R</span><span>0.00</span>
</td>
</tr>
</tbody>
</table>
<a class="add noprint" title="Add Item">+</a>
<div class="left_btn">
<button class="mah_btn" onclick="myprint()">Print</button>
<button class="mah_btn" onclick="window.location.reload()">Reset</button>
</div>
<div class="right_tax">
<table class="balance" id="balance">
<tbody>
<tr>
<th class="bold">
<span class="subtotal" id="subtotal">Subtotal</span>
</th>
<td>
<span>R</span><span>0.00</span>
</td>
</tr>
<tr>
<th class="bold">
<span class="tax" id="tax" contenteditable="true">Include VAT </span>
<span contenteditable="true">0</span>%
</th>
<td>
<span>R</span><span>0.00</span>
</td>
</tr>
<tr>
<th class="bold">
<span class="total" id="total">Total</span>
</th>
<td>
<span>R</span><span>0.00</span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
So the end results looks like this (with the CSS ofcourse :-) )
enter image description here
As you can see you can add a new row and insert some data. If you hover over the input line a "minues" sign will popup where you can delete that row. It will also automatically multiply and add the necassary fields to display total amount. All of this works great, but I now want to save it to my SQL database table. For this I have created the table and looks like this:
CREATE TABLE [dbo].[tbl_newQuotes] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Item] NVARCHAR (MAX) NULL,
[Description] NVARCHAR (MAX) NULL,
[Rate] NVARCHAR (MAX) NULL,
[Quantity] NVARCHAR (MAX) NULL,
[Price] NVARCHAR(MAX) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
And as you can guess this is where I am stuck :-( No I have saved form data before which is realtively simple by supllying the TextBox ID and values and save that to the database. But this is a complete different ball game and am not sure on how to achieve that.
I have covered most things in the question, but if you require more info please let me know.
EDIT
If there is a simpler way maybe to achieve this I am all ears :-) Maybe a tutorial on creating an invoice / quotation web forms app?
I have tried now again and can't seem to figure it out :-(
Thanks
I want you to approach it in a different way by using a GridView control.
When you click the "+" button, you save a row you have added into the table; bind the gridview taking records from the table; and display the rows including the necessary fields calculated like total amount.
There is another way by using a DataTable. Create a DataTable and save those rows to the DataTable. Then put another button called "Save" which makes those records in the DataTable saved into the Table. After saving and refreshing the screen, bring the records saved to the DataTable to display the rows on the screen.
Provided you are using jquery, it is possible to do by creating the JSON object of the inputs you added.
Create JSON object for multiple rows
Make an ajax call to pass the JSON object to web method.
Populate datatable with parsing the JSON object
Create user defined table Type in SQL for the datatable we wish to pass.
Pass datatable to Stored procedure and in SP process the data as you want.

Clickable html table cells

I'm making a tic-tac-toe game. I've made my table cells clickable and once they are clicked they run a function called playPVPGame. To start, O and X are chosen randomly to go first. I have text in the corner of the page to indicate whose turn it is. Initially the text will be either "O goes first" or "X goes first". Afterwards it will change to "X is next" or "O is next" depending on the turn. The problem is after the initial text, the turn doesn't go back and forth like i want it to.
var $ = function(id) {
return document.getElementById(id);
};
var newGameAction = function()
{
//clear table
$("c1").innerHTML = "";
$("c2").innerHTML = "";
$("c3").innerHTML = "";
$("c4").innerHTML = "";
$("c5").innerHTML = "";
$("c6").innerHTML = "";
$("c7").innerHTML = "";
$("c8").innerHTML = "";
$("c9").innerHTML = "";
};
var pVpAction = function(elem)
{
var outputTect;
var turnCounter = 0;
var first_Turn = Math.floor(Math.random() * 2);
$("firstTurn").innerHTML = first_Turn;
first_turn = $("firstTurn").innerHTML;
if(first_turn == 0)
{
message = "O goes first";
}
if(first_turn == 1)
{
message = "X goes first";
}
$("goNext").innerHTML = message;
};
var playPVPGame = function(elem)
{
var turn = $("goNext").innerHTML;
var message;
if(turn == "O goes first")
{
elem.style.backgroundColor = "red";
elem.innerHTML = "O";
turn = "X is next";
$("goNext").innerHTML = turn;
}
if(turn == "X goes first")
{
elem.style.backgroundColor = "blue";
elem.innerHTML = "X";
turn = "O is next";
$("goNext").innerHTML = turn;
}
//does not work
/*if($("goNext").innerHTML = "X is next")
{
$("newGame").disabled = true;
}*/
message = $("goNext").innerHTML;
if(message == "X is next")
{
elem.style.backgroundColor = "blue";
elem.innerHTML = "X";
message = "O is next";
$("goNext").innerHTML = message;
}
if(message == "O is next")
{
elem.style.backgroundColor = "red";
elem.innerHTML = "O";
message = "X is next";
$("goNext").innerHTML = message;
}
};
window.onload = function() {
$("newGame").onclick = newGameAction;
$("playerVplayer").onclick = pVpAction;
};
table {width:100%}
table tr td{border:1px solid #000;height:50px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="firstTurn"> </span>
<span id= "goNext"> </span>
<table class = "board">
<tr>
<td id = "c1" onclick="playPVPGame(this)" > . </td>
<td id = "c2" onclick="playPVPGame(this)"> . </td>
<td id = "c3" onclick="playPVPGame(this)"> . </td>
</tr>
<tr>
<td id = "c4" onclick="playPVPGame(this)"> . </td>
<td id = "c5" onclick="playPVPGame(this)"> . </td>
<td id = "c6" onclick="playPVPGame(this)"> . </td>
</tr>
<tr>
<td id = "c7" onclick="playPVPGame(this)"> . </td>
<td id = "c8" onclick="playPVPGame(this)">. </td>
<td id = "c9" onclick="playPVPGame(this)"> .</td>
</tr>
</table>
<input type="button"
id= "newGame"
value="New Game"/>
<input type="radio"
id= "playerVplayer"
value="Player vs Player"/>
<input type="radio"
id= "playerVcpu"
value="Player vs CPU"/>
Store the current player ('X' or 'O') in a variable instead of reading it from your GUI.
Reading from the GUI is bad practice and you having to ask this question shows why that's the case.
Here you have simplified minimal working example: https://jsfiddle.net/smajl/nr21zd9e/1/
I highly suggest you store the game state in some handy object like:
{
nextTurn: 'X',
isFirstTurn: true,
...
}
You are also ending </body> too soon in your HTML and have many other small or big issues in your code.

Need help on JavaScript function I have

I have a JavaScript function which changes the border radius and the opacity of an image based on user's input.
Here is the JavaScript:
<script>
var input = document.getElementById('opc');
var text = document.getElementById('main');
function changeOpacity(event) {
if ( event.keyCode === 13 ) {
var value = input.value;
var parts = value.split(' ');
text.style.opacity = '0.' + value;
}
}
input.addEventListener('keyup', changeOpacity);
</script>
<script>
var input = document.getElementById('modell');
var text = document.getElementById('image');
function changeBorderRadius(event) {
//works with spacebar
if ( event.keyCode === 32 ) {
var value = input.value;
var parts = value.split(' ');
text.style.borderRadius = '5' + value;
}
}
input.addEventListener('keyup', changeBorderRadius);
</script>
And here is the HTML:
<div id = "main"><img id="image" src = "flag.gif" alt = "Flag" style = "left:0; top: 0;" /></div>
<br/>
<table border="1" style="background-color: #CCFFCC">
<tr>
<td>
Opacity Value (1 - 9)
</td>
<td>
<input type="text" id="opc" />
</td></tr>
<tr>
<td>
Border Radius (px / %)
</td>
<td>
<input type="text" id="modell" />
</td></tr>
</table>
</body>
I got the opacity thing working with the help of this Stack Overflow. :D
I tried to add another function (border function) which worked fine for me, but the opacity thing stopped working after adding this border function.
Can someone tell me what am I missing here or what is the issue?
You have to modify your javascript a bit.
Here is a jsfiddle of it working
<script>
function changeBorderRadius(e) {
var key = e.which || e.keyCode || 0;
//works with space
if ( key == 32 ) {
var value = inputBoarder.value;
var parts = value.split(' ');
textBoarder.style.borderRadius = parts[0] + "px";
}
}
function changeOpacity(e) {
var key = e.which || e.keyCode || 0;
if ( key == 32 ) {
var value = inputOPC.value;
textOPC.style.opacity = '0.' + value;
}
}
var inputOPC = document.getElementById('opc');
var textOPC = document.getElementById('main');
inputOPC.addEventListener('keyup', changeOpacity);
var inputBoarder = document.getElementById('modell');
var textBoarder = document.getElementById('image');
inputBoarder.addEventListener('keyup', changeBorderRadius);
</script>
Rename variable in either script tag.
Something like input to input1
Values of variable are getting overridden

Dynamic Validation of ASP.NET controls using Javascript/Jquery

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;
}
});
});

Javascript Search Exact Results Not Part Of

I am trying to use the Javascript search from the below website however was wondering if there is a way to return only the exact term searched for, as if I type part of a word it returns the table row also.
ie. Seach for "Heath" returns the same result as searching Heathesh", is there a simple workaround?
Script: http://heathesh.com/post/2010/05/06/Filtering-or-searching-an-HTML-table-using-JavaScript.aspx
Example: http://heathesh.com/code/javascript/tablesearch/
<table border="1" cellpadding="0" cellspacing="0">
<tr>
<th>ID</th>
<th>First Name</th>
<th>Surname</th>
<th>Website</th>
</tr>
<tbody id="data">
<tr>
<td>1</td>
<td>Heathesh</td>
<td>Bhandari</td>
<td>http://heathesh.com</td>
</tr>
<tr>
<td>2</td>
<td>Candice</td>
<td>David</td>
<td>http://candicedavid.com</td>
</tr>
</tbody>
</table>
//define the table search object, which can implement both functions and properties
window.tableSearch = {};
//initialize the search, setup the current object
tableSearch.init = function() {
//define the properties I want on the tableSearch object
this.Rows = document.getElementById('data').getElementsByTagName('TR');
this.RowsLength = tableSearch.Rows.length;
this.RowsText = [];
//loop through the table and add the data to the table search object
for (var i = 0; i < tableSearch.RowsLength; i++) {
this.RowsText[i] = (tableSearch.Rows[i].innerText) ? tableSearch.Rows[i].innerText.toUpperCase() : tableSearch.Rows[i].textContent.toUpperCase();
}
}
Next create the actual JavaScript function to run the search like so:
//onlys shows the relevant rows as determined by the search string
tableSearch.runSearch = function() {
//get the search term
this.Term = document.getElementById('textBoxSearch').value.toUpperCase();
//loop through the rows and hide rows that do not match the search query
for (var i = 0, row; row = this.Rows[i], rowText = this.RowsText[i]; i++) {
row.style.display = ((rowText.indexOf(this.Term) != -1) || this.Term === '') ? '' : 'none';
}
}
//handles the enter key being pressed
tableSearch.search = function(e) {
//checks if the user pressed the enter key, and if they did then run the search
var keycode;
if (window.event) { keycode = window.event.keyCode; }
else if (e) { keycode = e.which; }
else { return false; }
if (keycode == 13) {
tableSearch.runSearch();
}
else { return false; }
}
<table border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td>
<input type="text" size="30" maxlength="1000" value="" id="textBoxSearch" onkeyup="tableSearch.search(event);" />
<input type="button" value="Search" onclick="tableSearch.runSearch();" />
</td>
</tr>
</tbody>
</table>
You are matching this with rowText.indexOf() in the code below, that will return the row if the term is found anywhere in the string.
for (var i = 0, row; row = this.Rows[i], rowText = this.RowsText[i]; i++) {
row.style.display = ((rowText.indexOf(this.Term) != -1) || this.Term === '') ? '' : 'none';
}
To get exact matches, change rowText.indexOf(this.Term) != -1 to rowText.toUpperCase() === this.Term.toUpperCase(). The .toUpperCase() converts both strings to uppercase before comparing to make the search case insensitive.
for (var i = 0, row; row = this.Rows[i], rowText = this.RowsText[i]; i++) {
row.style.display = ((rowText.toUpperCase() === this.Term.toUpperCase()) || this.Term === '') ? '' : 'none';
}
The following code will do a partial search if an exact word match did not give any results:
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Search table</title>
</head>
<body style=" background-color:white;">
<input type="text" size="30"
value=""
id="textBoxSearch"
onkeyup="tableSearch.search(this.value);" />
<div id="table"></div>
<script type="text/javascript">
// create a 4 column table with random text
function getRandomText(len){
ret=[];
for(var i =0;i<len;i++){
ret.push(String.fromCharCode(
Math.floor((Math.random()*(85-65))+65)
));
}
return ret.join("");
}
function createRandomTable(){
var ret=["<table>"],i=0,
j=0;
while(i<50){
j=0
ret.push("<tr>");
while(j<5){
ret.push("<td>");
ret.push(getRandomText(5));
ret.push("</td>");
j++;
}
ret.push("</tr>");
i++;
}
document.getElementById("table")
.innerHTML=ret.join("");
}
createRandomTable();
// Code that does the search
tableSearchF=function(){
//private variables
var table=document.getElementById("table")
.getElementsByTagName("table")[0];
var rows=table.getElementsByTagName("tr");
var rowVals=[];
for(var i=0;i<rows.length;i++){
var tmp=[];
var c=rows[i].getElementsByTagName("td");
for(var j=0;j<c.length;j++){
tmp.push(
(c[j].textContent)?c[j].textContent:c[j].innerText
)
}
rowVals.push(tmp);
}
var searchTable=function(r){
var match=false;
var doPartial=true;
// for each row
for(var i=0;i<rowVals.length;i++){
match=false;
//for each cell
cellmatch:
for(var j=0;j<rowVals[i].length;j++){
if(r.test(rowVals[i][j])===true){
console.log("positive match");
match=true;
doPartial=false;
break cellmatch;
}
}
rows[i].style.display=(match)?"":"none";
}
return doPartial;
}
// publicly available methods
return {
search:function(searchText){
var txt = searchText.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g
,'\\$1')
.replace(/\x08/g, '\\x08'),
r = new RegExp("\\b"+txt+"\\b","igm");
if(searchTable(r)){
// no exact match, do a partial
r=new RegExp(txt,"igm");
searchTable(r);
}
}
}
}
//initialise tableSearch
var tableSearch=tableSearchF();
</script>
</body>
</html>

Categories