To set focus on textbox if the condition is failure using javascript - 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...");
}
}

Related

How do I input a number / time of 01:10 from my code?

I have this working code below to input a number/tme in textbox. This code below is functioning well but I want to set my textbox value into 00:00 and edit my function code like the second jsfiddle however my edited code is not going well as my idea. In my second jsfiddle I want to input a time of 05:30 but the code is replacing any number that input by a user from the textbox 0
function MaskedTextboxDPSDeparture() {
var myMask = "__:__";
var myCorrectionOut2 = document.getElementById("Departure");
var myText = "";
var myNumbers = [];
var myOutPut = ""
var theLastPos = 1;
myText = myCorrectionOut2.value;
//get numbers
for (var i = 0; i < myText.length; i++) {
if (!isNaN(myText.charAt(i)) && myText.charAt(i) != " ") {
myNumbers.push(myText.charAt(i));
}
}
//write over mask
for (var j = 0; j < myMask.length; j++) {
if (myMask.charAt(j) == "_") { //replace "_" by a number
if (myNumbers.length == 0)
myOutPut = myOutPut + myMask.charAt(j);
else {
myOutPut = myOutPut + myNumbers.shift();
theLastPos = j + 1; //set current position
}
} else {
myOutPut = myOutPut + myMask.charAt(j);
}
}
document.getElementById("Departure").value = myOutPut;
document.getElementById("Departure").setSelectionRange(theLastPos, theLastPos);
}
document.getElementById("Departure").onkeyup = MaskedTextboxDPSDeparture;
HTML
< input id="Departure" type="text" style="width: 35px; text-align: center" value="__:__" />
JSFIDDLE
JSFIDDLE 2
Any suggestion will accepted. Thanks.

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

Returning cell value based on Radio selection

The goal I am trying to achieve is to retrieve a cell value based on a form radio selection and update a text area.
Process: User opens dialog box. They select a field office. Onclick runs the function check. After check runs google.script.run.withSuccessHandler(addSignatureLine).getSignatureLine(cellElement); is supposed to run and update the textarea with the Id 'AdditionalMessage' with the signature line retrieved from .getSignatureLine.
Here are two functions of the html code:
<script>
function addSignatureLine(signatureLine){
document.getElementById('AdditionalMessage').value = '\n\n'signatureLine;
};
function updateSignatureLine() {
var cellElement = document.getElementById('ET');
console.log('cellElement: ' + cellElement);
google.script.run.withSuccessHandler(addSignatureLine)
.getSignatureLine(cellElement);
};
function check() {
var ele = document.getElementsByName('fieldOfficeET');
var flag = 0;
for (var i = 0; i < ele.length; i++) {
if (ele[i].checked)
flag = 1;
}
if (flag == 1)
document.getElementById('Submit').disabled = false;
};
</script>
Here is the getSignatureLine.gs script
function getSignatureLine(cellObject) {
var ss = SpreadsheetApp.openById('googleSheetId');
var sheet = ss.getSheetByName('AMS Contact Information');
var firstRow = 2;
var lastRow = 10;
var dataRange = sheet.getRange(firstRow, 1, lastRow, 11);
var dataValues = dataRange.getValues();
for (var key in cellObject) { //Loop through all the data in the form
Logger.log('key: ' + key);
Logger.log('value: ' + cellObject[key]);
}
//Determines the row the Field Office is in
for (var rr = 0; rr < dataValues.length; rr++) {
if (dataValues[rr][0] == cellObject.fieldOfficeET) {
var r = rr + 2
break;
}
}
var signatureLine = sheet.getRange(r, 11).getValue();
Logger.log("signatureLine: " + signatureLine)
return signatureLine;
}
There is a problem with this line:
document.getElementById('AdditionalMessage').value = '\n\n'signatureLine;
I would try:
document.getElementById('AdditionalMessage').value = '\n\n' + signatureLine;
Add a plus sign to concatenate the text.

How to write Javascript coding in C# code behind?

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

Javascript function not recognizing id in getElementById

I am adding a row to a table, and attached an ondblclick event to the cells. The function addrow is working fine, and the dblclick is taking me to seltogg, with the correct parameters. However, the var selbutton = document.getElementById in seltogg is returning a null. When I call seltogg with a dblclick on the original table in the document, it runs fine. All the parameters "selna" have alphabetic values, with no spaces, special characters, etc. Can someone tell me why seltogg is unable to correctly perform the document.getElementById when I pass the id from addrow; also how to fix the problem.
function addrow(jtop, sel4list, ron4list) {
var tablex = document.getElementById('thetable');
var initcount = document.getElementById('numrows').value;
var sel4arr = sel4list.split(",");
var idcount = parseInt(initcount) + 1;
var rowx = tablex.insertRow(1);
var jtop1 = jtop - 1;
for (j = 0; j <= jtop1; j++) {
var cellx = rowx.insertCell(j);
cellx.style.border = "1px solid blue";
var inputx = document.createElement("input");
inputx.type = "text";
inputx.ondblclick = (function() {
var curj = j;
var selna = sel4arr[curj + 2];
var cellj = parseInt(curj) + 3;
inputx.id = "cell_" + idcount + "_" + cellj;
var b = "cell_" + idcount + "_" + cellj;
return function() {
seltogg(selna, b);
}
})();
cellx.appendChild(inputx);
} //end j loop
var rowCount = tablex.rows.length;
document.getElementById('numrows').value = rowCount - 1; //dont count header
} //end function addrow
function seltogg(selna, cellid) {
if (selna == "none") {
return;
}
document.getElementById('x').value = cellid; //setting up for the next function
var selbutton = document.getElementById(selna); //*****this is returning null
if (selbutton.style.display != 'none') { //if it's on
selbutton.style.display = 'none';
} //turn it off
else { //if it's off
selbutton.style.display = '';
} //turn it on
} //end of function seltogg
You try, writing this sentence:
document.getElementById("numrows").value on document.getElementById('numrows').value
This is my part the my code:
contapara=(parseInt(contapara)+1);
document.getElementById("sorpara").innerHTML+="<li id=\"inputp"+contapara+"_id\" class=\"ui-state-default\"><span class=\"ui-icon ui-icon-arrowthick-2-n-s\"></span>"+$('#inputp'+contapara+'_id').val()+"</li>";
Look you have to use this " y not '.
TRY!!!!

Categories

Resources