How to write Javascript coding in C# code behind? - javascript

i am creating textboxes dynamically so how to call below javascript function for textbox 'onchange' event?
<script type="text/javascript">
debugger;
function myFunction() {
var btn = document.getElementById('<%= temp.ClientID%>').value;
var btntemp = document.getElementById('<%= txttemp2.ClientID%>').value;
var val = parseInt(btn) + parseInt(btntemp);
document.getElementById('<%= TextBox1.ClientID%>').value = val;
}
</script>
<asp:TextBox ID="temp" runat="server" onchange="myFunction()"></asp:TextBox>
<asp:TextBox ID="txttemp2" runat="server" onchange="myFunction()"></asp:TextBox>
Here iam creating textboxex dynamically.
Table table = (Table)this.Page.FindControl("PlaceHolder1").FindControl("Table1");
for (int i = 0; i < rowsCount; i++)
{
for (int j = 0; j < colsCount; j++)
{
TextBox tb = (TextBox)table.Rows[i + 1].Cells[j].FindControl("TextBoxRow_" + i + "Col_" + j);
tb.Text = Request.Form["TextBoxRow_" + i + "Col_" + j];
here iam getting first column's textbox value
else if (j == 2)
{
int quantityText;
TextBox quantity = (TextBox)table.Rows[i +1].Cells[j].FindControl("TextBoxRow_" + i + "Col_" + j);
here iam getting second column's textboxes value
else if (j == 3)
{
double rateText;
TextBox rate = (TextBox)table.Rows[i + 1].Cells[j].FindControl("TextBoxRow_" + i + "Col_" + j);
here iam generating textboxes dynamically.
private void GenerateTable(int rowsCount)
{
Table table = new Table();
table.ID = "Table1";
PlaceHolder1.Controls.Add(table);
for (int i = 0; i < rowsCount; i++)
{
TableRow row = new TableRow();
row.ID = "Row_" + i;
else if (j < colsCount - 1)
{
TableCell cell = new TableCell();
TextBox tb = new TextBox();
tb.ID = "TextBoxRow_" + i + "Col_" + j;
cell.Controls.Add(tb);
row.Cells.Add(cell);
}

use this for calling javascript function in code behind
ClientScript.RegisterClientScriptBlock(myFunction(), "AlertMsg", "<script>
alert('Inserted successfully');</script>", true)

You need your script to have the runat="server" attribute if your textbox does. I think your script needs to be c# in order to work this way. You could rewrite your original function as:
<script runat="server">
void textBox_Change(Object sender, EventArgs e) {
TextBox1.Text = Int32.parse(temp.Text) +
Int32.parse(txttemp2.Text)
}
</script>
<asp:TextBox ID="temp" runat="server" ontextchanged="textBox_Change" autopostback="true"></asp:TextBox>
<asp:TextBox ID="txttemp2" runat="server" ontextchanged="textBox_Change" autopostback="true"></asp:TextBox>
Your handler attribute is also wrong. The event for changing the text in a TextBox control is ontextchange="" as shown in the code box above, and also requires autopostback="true" to be set... but it will only take effect when the user changes focus away from the TextBox control.
You can also use jQuery for a pure javascript handler:
$(document).on("change","#temp,#txttemp2",myFunction);
This will detect changes to your textboxes in the client and fire your method. Because it's a delegated handler, it will catch the events even if the items weren't created when you registered it originally. You could even set a class for your items so that you don't need to know their IDs:
$(document).on("change",".waitingForChangeForMyFunction",myFunction);
And then when you generate your textboxes, just do:
TextBox tb = new TextBox();
tb.CssClass="waitingForChangeForMyFunction";

you can use RegisterClientScriptBlock:
String scripts = "function myFunction(clientID) {
var btn = document.getElementById('clientID').value;
var btntemp = document.getElementById('clientID').value;
var val = parseInt(btn) + parseInt(btntemp);
document.getElementById('clientID').value = val;
} ";
ClientScript.RegisterClientScriptBlock(this.GetType(),
"CounterScript", scripts, true);
for (int i = 0; i < rowsCount; i++)
{
for (int j = 0; j < colsCount; j++)
{
TextBox quantity = (TextBox)table.Rows[i +1].Cells[j].FindControl("TextBoxRow_" + i + "Col_" + j);
quantity .Attributes.Add("onchange", "jsFunc('TextBoxRow_'" + i + "Col_" + j + "')");
}
}

I got my answer successfully which is in below.
script side have to write like below
<script type="text/javascript">
function myFunction() {
var btn = document.getElementById('<%= TextBox1.ClientID%>').value;
var sum = [0, 1, 2]
for (var j = 0; j <= btn; j++) {
var elements = document.getElementsByClassName("sum"+j);
for (var i = 0, length = elements.length; i < length; i++) {
if (elements[i].value) {
sum[0] = parseInt(elements[0].value);
sum[1] = parseInt(elements[1].value);
sum[2] = parseInt(elements[2].value);
}
elements[2].value = sum[0] * sum[1];
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div style="display:none">
<asp:HiddenField ID="HiddenField2" runat="server" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div> </form>
</body>
</html>
and while creating dynamically textboxes have to add class to which we have to get values and calculate it and then show the result
private void GenerateTable(int rowsCount)
{
//ContentPlaceHolder content = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
TextBox1.Text = rowsCount.ToString();
Table table = new Table();
table.ID = "Table1";
PlaceHolder1.Controls.Add(table);
for (int i = 0; i < rowsCount; i++)
{
TableRow row = new TableRow();
row.ID = "Row_" + i;
for (int j = 0; j < colsCount; j++)
{
if (j < colsCount - 1)
{
TableCell cell = new TableCell();
TextBox tb = new TextBox();
if (j == 2)
{
tb.ID = "TextBoxRow_" + i + "Col_" + j;
tb.CssClass = "sum"+i;
tb.Attributes.Add("onchange", "myFunction();");
}
else if (j == 3)
{
tb.ID = "TextBoxRow_" + i + "Col_" + j;
tb.CssClass = "sum"+i;
tb.Attributes.Add("onchange", "myFunction();");
}
else if (j == 4)
{
tb.ID = "TextBoxRow_" + i + "Col_" + j;
tb.ReadOnly = true;
tb.CssClass = "sum"+i;
}
cell.Controls.Add(tb);
row.Cells.Add(cell);
}
table.Rows.Add(row);
}
SetPreviousData(rowsCount, colsCount);
rowsCount++;
ViewState["RowsCount"] = rowsCount;
}

Related

Multiplication Table in javascript and how about to align the row

I tried to a do Multiplication Table in JS and I want to print in <p> element out (Use DOM and not use document.write method).
I tried to use " " or "\t" to align column , but when number is double digit (from x3 column) , it got typographic issue.
Does it any ways could solve this problem?
var p1 = document.getElementById("printout");
var s = "";
for (var i = 1; i <= 9; i++) {
for (var j = 1; j <= 9; j++) {
s = s + j + "*" + i + " = " + (i * j) + " ";
}
s = s + "<br>";
}
p1.innerHTML = s;
<pre id="printout"></pre>
Instead of printing table column wise, print row wise.
And wrap your each table in a div, so that aligning them becomes easy.
var p1 = document.getElementById("printout");
var s = "";
for (var i = 1; i <= 9; i++) {
s = s + "<div>";
for (var j = 1; j <= 9; j++) {
s = s + i + "*" + j + " = " + (i*j) + "<Br/>" ;
}
s = s + "</div>";
}
p1.innerHTML = s;
Little bit CSS
#printout {
display:flex;
flex-wrap:wrap;
}
#printout div {
padding:10px;
min-width:100px
}
https://jsfiddle.net/wkg92rud/
Inspiring from #Andreas suggestion, Using <table>
var p1 = document.getElementById("printout");
var s = "";
for (var i = 1; i <= 9; i++) {
let row = document.createElement("tr");
for (var j = 1; j <= 9; j++) {
let col = document.createElement("td");
col.innerText = j + "*" + i + " = " + (i * j);
row.append(col);
}
p1.append(row);
}
td {
padding: 2px 2px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<table id="printout"></table>
</body>
</html>
#Dalvik method is the correct way, styling and alignment should be done through CSS.
However, in other environments like command line, or if you are doing this as an exercise to learn JS you can use string padding, here is an example:
const p1 = document.getElementById("printout");
const LONGEST_ENTRY = 9; // Longest string you will have is 9 characters long
const entries = []
for (let i = 1; i <= 9; i++) {
for (let j = 1; j <= 9; j++) {
const entry = `${j}*${i} = ${(i*j)}`.padEnd(LONGEST_ENTRY, " ") ; // use string interpolation, then pad the string with spaces until the length of LONGEST_ENTRY is reached
entries.push(entry); // store all the entries in an array
}
entries.push("<br/>"); // add a line break at the end of each row
}
p1.innerHTML = entries.join(''); // join all the elements
Here is a jsfiddle as an example

HTML/Javascript multiplication table that takes inputs and highlights the answer on table

As the title states, I need to make a multiplication table using JS and HTML that takes two user inputs and highlights the answer on the table. I have the table made, I'm just struggling with how to take the user inputs from the ids "leftOp" and "rightOp" and highlighting the answer on the table.
var color_td;
document.write("<table border='1px'>");
for(var i = 1; i < 11; i++) {
document.write("<tr style='height:30px;'>");
for(var j = 1; j < 11; j++) {
if(j == 1 || i == 1) {
color_td = "#ccc";
}
else {
color_td = "#fff";
}
document.write("<td style='width:30px;background-color:" + color_td + "'>" + i*j + "</td>");
}
document.write("</tr>");
}
document.write("</table>");
<input type='text' id='leftOp' value=''>
<input type='text' id='rightOp' value=''>
I tried a simple answer with your code style.
Just bind the event "onkeyup" of your inputs to a function that highlight the result cell.
To identify each cell, I add an id and a class to each one. The id is a concatenation of the two indexes and the class difference between border cells and other cells.
To hightlight the rersult cell, you use the inputs values and build the id of the result cell with them.
Don't forget to reset the cells colors on each invocation.
var color_td;
document.write("<table border='1px'>");
for (var i = 1; i < 11; i++) {
var id;
var cellClass;
document.write("<tr style='height:30px;'>");
for (var j = 1; j < 11; j++) {
id = 'cell-' + i + '-' + j;
if (j == 1 || i == 1) {
color_td = "#ccc";
cellClass = "border-cell";
}
else {
color_td = "#fff";
cellClass = "result-cell";
}
document.write("<td class='" + cellClass + "' id='" + id + "' style='width:30px;background-color:" + color_td + "'>" + i * j + "</td>");
}
document.write("</tr>");
}
document.write("</table>");
function inputChange() {
var left = document.getElementById('leftOp').value;
var right = document.getElementById('rightOp').value;
if (!left || !right || left > 10 || left < 1 || right > 10 || left < 1) {
return;
}
var cells = document.getElementsByClassName('result-cell');
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
cell.style.backgroundColor = '#fff';
}
var cells = document.getElementsByClassName('border-cell');
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
cell.style.backgroundColor = '#ccc';
}
var resultCell = document.getElementById('cell-' + left + '-' + right);
resultCell.style.backgroundColor = '#5fc047';
}
<input type='text' id='leftOp' value='' onkeyup="inputChange()">
<input type='text' id='rightOp' value='' onkeyup="inputChange()">
Important tip: Doesn't use document.write when creating elements and appending new things to DOM, use the correct API for that, such as document.createElement that you can manage the elements much better. In my code below I'm using it to show you as example.
After creating the table, you'll need a function to get the values and the do the verifications and Maths. Also, add the operands i and j (example: "i_j") as the id of each <td> (take care to not have any repeated id), that way you'll have an easy way to found the td you should highlight.
Also, you should have some way to clear the background color of the td which is already highlighted, for that I used an auxiliar function called cleanTds.
Take a look:
var color_td;
let table = document.createElement("table");
document.body.appendChild(table);
for(var i = 1; i < 11; i++) {
let tr = document.createElement("tr");
tr.style.height = "30px"
table.appendChild(tr);
var color_class;
for(var j = 1; j < 11; j++) {
if(j == 1 || i == 1) {
color_class = "grayBg";
}
else {
color_class = "whiteBg";
}
let td = document.createElement("td");
td.className = "tdClass " + color_class;
td.id = i +"_"+ j;
td.style.background = color_td;
td.textContent = i * j;
tr.appendChild(td);
}
}
document.getElementById("calc").onclick = (ev) => {
cleanTds()
let val1 = document.getElementById("leftOp").value;
let val2 = document.getElementById("rightOp").value;
if (val1 == null || val1 == ""){ val1 = 0}
if (val2 == null || val2 == ""){ val2 = 0}
let tdResult = document.getElementById(val1 + "_" + val2)
if (tdResult != null){
tdResult.style.background = "green";
}
}
function cleanTds(){
let tds = document.querySelectorAll("td");
for (var td of tds){
td.style.background = ""
}
}
.tdClass{
height: 30px;
width: 30px;
border: 1px solid;
}
.grayBg{
background: #ccc;
}
.whiteBg{
background: #fff;
}
<input type='text' id='leftOp' value=''>
<input type='text' id='rightOp' value=''>
<button id="calc">Calculate</button>
This should get you started. it's triggered when the enter key is pressed
var color_td;
document.write("<table border='1px'>");
for(var i = 1; i < 11; i++) {
document.write("<tr style='height:30px;'>");
for(var j = 1; j < 11; j++) {
var idName = 'R'+i + 'C' + j;
if(j == 1 || i == 1) {
color_td = "#ccc";
}
else {
color_td = "#fff";
}
document.write("<td id='"+idName + "'style='width:30px;background-color:" + color_td + "'>" + i*j + "</td>");
}
document.write("</tr>");
}
document.write("</table>");
left = document.getElementById("leftOp");
right = document.getElementById("rightOp");
document.getElementById("rightOp")
.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
left = document.getElementById("leftOp");
right = document.getElementById("rightOp");
var idName = 'R' + leftOp.value + 'C' + rightOp.value;
document.getElementById(idName).style.backgroundColor = "lightblue";
}
});
<input type='text' id='leftOp' value=''>
<input type='text' id='rightOp' value='' >

how to display information underneath a specific button using javascript

I have the following piece of code I am working on. My purpose is to be able to grab information about different users from a specific website, display the name and other info and then have a button that when clicked, prints more information. I am able to get the information and display the name and picture, but when I click the button the information is displayed at the top of the page, not under the specific button that was clicked. I want for the information to be display under each user... I am new to Javascript and learning on my own, any help is appreciated!
function getUsers(user) {
var out = "";
var i;
for (i = 0; i < user.length; i++) {
out += '' + user[i].login + '<br>'+'</br> <img src="'+user[i].avatar_url+
'" alt="Image" style="width:304px;height:228px"</br></br>'+
'<button onclick=printRepos("'+user[i].repos_url+'")>Repositories</button></br>'+'<div id="id"></div>';
}
document.getElementById("id01").innerHTML = out;
}
Printing Function
function printF(array) {
var out = "";
var i;
for (i = 0; i < array.length; i++) {
out += array[i].id+'</br>';
}
document.getElementById("id").innerHTML = out;
}
This works fine. I just made div with dynamic ids and passed it to the function
function getUsers(user) {
var out = "";
var i;
for (i = 0; i < user.length; i++) {
out += '' + user[i].login + ' <br>'+'</br> <img src="'+user[i].avatar_url+
'" alt="Image" style="width:304px;height:228px"</br></br>'+
'<button onclick=printRepos("'+user[i].repos_url+'","'+i+'")>Repositories</button></br>'+'<div id="'+ 'id' + i +'"></div>';
}
document.getElementById("id01").innerHTML = out;
}
function printRepos(array, id) {
var out = "";
var i;
for (i = 0; i < array.length; i++) {
out += array[i].id+'</br>';
}
console.log('id' + id);
document.getElementById('id' + id).innerHTML = out;
}
Add the "this" keyword as a parameter to your onclicks, to pass in the button that was clicked:
<button onclick=printRepos(this,"'+user[i].repos_url+'")>Repositories</button>
Then locate the next div after that button in your event handler:
function printF(btn, array) {
var out = "";
var i;
for (i = 0; i < array.length; i++) {
out += array[i].id+'</br>';
}
// find the div
var d = btn; // start with the button
while (d.tagName != "DIV") d = d.nextSibling; // look for the next div
d.innerHTML = out;
}

Add alphabets dynamically as html row increments

How to ensure i have a dynamic increment of Alphabets in a new cell on left side, next to each cell in a row which is dynamically created based on the option chosen in Select. This newly generated alphabet will be considered as bullet points/serial number for that particular row's text box.
jsfiddle
js code
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
html
<select id="Number_of_position">
</select> <table id="Positions_names">
</table>
This is essentially a base26 question, you can search for an implementation of this in javascript pretty easily - How to create a function that converts a Number to a Bijective Hexavigesimal?
alpha = "abcdefghijklmnopqrstuvwxyz";
function hex(a) {
// First figure out how many digits there are.
a += 1; // This line is funky
var c = 0;
var x = 1;
while (a >= x) {
c++;
a -= x;
x *= 26;
}
// Now you can do normal base conversion.
var s = "";
for (var i = 0; i < c; i++) {
s = alpha.charAt(a % 26) + s;
a = Math.floor(a/26);
}
return s;
}
So you can do
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td>" + hex(i) + "</td><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
Heres the example http://jsfiddle.net/v2ksyy7L/6/
And if you want it to be uppercase just do
hex(i).toUpperCase();
Also - this will work up to any number of rows that javascript can handle
if i have understood you correctly, that's maybe what you want:
http://jsfiddle.net/v2ksyy7L/3/
I have added an array for the alphabet:
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
and then added the output to your "render" loop:
rows += "<tr><td>" + alphabet[i] + " <input type='text'></td></tr>";

To set focus on textbox if the condition is failure using javascript

In the below code i have a textbox and a javascript function which has regular expression.I can validate regular expressions in textbox it will alert success or failure.My aim is if it is failure it should focus on textbox and should not able to move to another control until it is success.
js:
function ValidateRegExp(txtInput, REGEXP) {
var mySplitResult = new Array();
mySplitResult = REGEXP.split("~~");
var iReturn = 0;
for (i = 0; i < mySplitResult.length - 1; i++) {
var re = new RegExp(mySplitResult[i]);
if (!txtInput.match(re)) {
iReturn = iReturn + 1;
}
}
if (iReturn > 0) {
alert("Failed...");
}
else {
alert("Success...");
}
}
asp.net:
<asp:TextBox ID="txtField" runat="server" width="200Px" onfocus="But1()"></asp:TextBox>
codebehind
txtField.Attributes.Add("onblur", "javascript:ValidateRegExp(document.getElementById('" + txtField.ClientID + "').value, '" + hidRegExp.Value + "');");
Because you are already using onblur event so you just need to use javascript focus() to set focus on your text box. I have changed your code to pass this(your control) to javascript function.
Change you code behind code to
txtField.Attributes.Add("onblur", "javascript:ValidateRegExp(this, '" + hidRegExp.Value + "');");
and your javascript code to
function ValidateRegExp(txtInput, REGEXP) {
var mySplitResult = new Array();
mySplitResult = REGEXP.split("~~");
var iReturn = 0;
for (i = 0; i < mySplitResult.length - 1; i++) {
var re = new RegExp(mySplitResult[i]);
if (!txtInput.value.match(re)) {
iReturn = iReturn + 1;
}
}
if (iReturn > 0) {
alert("Failed...");
txtInput.focus(); //set focus back to control.
}
else {
alert("Success...");
}
}

Categories

Resources