Passing variable into JavaScript getElementById - javascript

I have a simple JavaScript problem. Here is an example:
function test()
{
for(int i=1; i<5; i++)
{
var value[i] = 100*i;
var x = accountname + value[i];
document.getElementById(x).value = value + '_'+"TestName";
}
}
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<telerik:RadTextBox RenderMode="Lightweight" ID="accountname100" AutoCompleteType="HomePhone" runat="server"
Label="account #1:" /><br />
<telerik:RadTextBox RenderMode="Lightweight" ID="accountname200" AutoCompleteType="HomePhone" runat="server"
Label="account #2:" /><br />
<telerik:RadTextBox RenderMode="Lightweight" ID="accountname300" AutoCompleteType="HomePhone" runat="server"
Label="account #3:" /><br />
<telerik:RadTextBox RenderMode="Lightweight" ID="accountname400" AutoCompleteType="HomePhone" runat="server"
Label="account #4:" /><br />
</asp:Content>
I am trying to find the correct syntax so that the value of parameter "x" can be in the radtextbox correctly.

I think there are a few issues here. One is using value to set the value of the input when it has never been set and another is using accountname, when it should be a string "accountname". I have created a fiddle which is roughly what I think you're trying to achieve. Hope that helps

here is some seems to you pretended
function test() {
value = [];
for(var i=1; i<5; i++) {
value.push(100*i);
var x = accountname + value[i];
document.getElementById('accountname'+x).value = value + '_' + "TestName";
}
}
Details:
in javascript vars don't have types their type is dinamic
so to declarate any type of variable you have to do this
var number = 10;
var name = "Jhon";
var money = 3.23;
var arrayNumbers = [1,2];
I suggest you to see some basic guide to javascript.

Related

Need to populate a textfield with email ids based on the checkbox checked for different towers

I have 4 towers and I need checkboxes for each of them. Based on checking any combnation of them the 'txtNotifTo' textbox should get populated with the respective group of email ids for each tower selected.
Please help me find out what is going wrong in this code.
When the checkbox is checked, I get this error:
0x800a138f - JavaScript runtime error: Unable to get property
'getElementsByTagName' of undefined or null reference*
function getChNotifValue() {
var listItems = document.getElementById("txtTowerValue").getElementsByTagName("input");
var cb1 = listItems[0];
var cb2 = listItems[1];
var cb3 = listItems[2];
var cb4 = listItems[3];
var cb5 = listItems[4];
var emailaddress = document.getElementById('<%=txtNotifTo.ClientID%>');
// var email = [];
var emailList = [];
if (cb1.checked) {
emailList.push("Admin#test.com");
} else {
emailList = removeEmail(emailList, "Admin#test.com");
}
if (cb2.checked) {
emailList.push("Admin1#test.com");
} else {
emailList = removeEmail(emailList, "Admin1#test.com");
}
if (cb3.checked) {
emailList.push("Admin2#test.com");
} else {
emailList = removeEmail(emailList, "Admin2#test.com");
}
if (cb4.checked) {
emailList.push("Admin3#test.com");
} else {
emailList = removeEmail(emailList, "Admin3#test.com");
}
if (cb5.checked) {
emailList.push("Admin4#test.com");
} else {
emailList = removeEmail(emailList, "Admin4#test.com");
}
emailaddress.value = emailList.join(', '); // Concatenate the email address to NotifTo variable
}
THE HTML CODE:
<tr>
<td class="toconditions" style="border-color: lightblue">
<asp:Label runat="server" ID="Label21" Font-Bold="true" Text="To" />
</td>
<td>
<asp:TextBox runat="server" Width="700px" SkinID="EmailTextbox" ID="txtNotifTo" />
</td>
</tr>
<asp:CheckBoxList ID="txtTowerValue" runat="server" SkinID="EmailTextbox" Font-Size="14px" Width="580px" Height="30px" BorderStyle="None" onClick="getChNotifValue()" >
<asp:ListItem Text="I1" Value="ch1" />
<asp:ListItem Text="I2" Value="ch2" />
<asp:ListItem Text="I3" Value="ch3" />
<asp:ListItem Text="I4" Value="ch4" />
<asp:ListItem Text="I5" Value="ch5" />
</asp:CheckBoxList>
I altered the code in the Javascript function and added the below code instead as txtNotifTo is a ASP.NET server control.
var listItems = document.getElementById('<%=txtNotifTo.ClientID%>').getElementsByTagName("input");
When I ran the code after this I am getting this error.
0x800a138f - JavaScript runtime error: Unable to get property 'checked' of undefined or null reference
Well, using a jQuery selector would be easier.
but, your code will look like this:
ckList = document.getElementById('<%= txtTowerValue.ClientID %>')
ckBoxInList = ckList.getElementsByTagName("INPUT")
if (ckBoxInList[0].checked) {
alert("Check box " + ckBoxInList[0].value + " is checked")
}
if (ckBoxInList[1].checked) {
alert("Check box " + ckBoxInList[1].value + " is checked")
}

document.getElementsByName(...)[0] is undefined when javascript value is insert to the .net textbox

I want to insert value from JavaScript variable to the textbox value. In JavaScript variable data is coming very well but when that variable data I am storing in the .net textbox using JavaScript at that time this type of error is coming.
Here is my code
<form>
<asp:TextBox name="password" ID="txt_pass" runat="server"></asp:TextBox>
<asp:Button ID="btn_captcha" runat="server" Text="Gen. Pass." OnClientClick="return false;" ClientIDMode="Static"/>
<script>
$(function () {
$(document).on("click", "#btn_captcha", function (e) {
var length = 5,
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
retVal = "";
for (var i = 0, n = charset.length; i < length; ++i) {
retVal += charset.charAt(Math.floor(Math.random() * n));
}
alert(retVal);
document.getElementsByName('password')[0].value = retVal;
});
});
</script>
</form>
You can use Id instead of name
document.getElementById('<%= txt_pass.ClientID %>').value = retVal;
or
document.querySelector('[id$=_txt_pass]').value = retVal;
I think that your problem is that the textbox name and id you are looking for is not static thats why javascript cannot find the element. Press F12 use developer tools to verify the above input's name and id and then use a static one.

How to get multiple value from html inputs that generated by C#

I have multiple Html inputText that is generated on page load by C#. This is my stored procedure:
ALTER PROCEDURE [dbo].[CharacteristicsFetch]
AS
BEGIN
SELECT chId, chName, chDesc
FROM Characteristics
ORDER BY chName
END
and my C# code:
public string generate_CharValues()
{
string post = "";
DataTable dt = cls.Fill_In_DataTable("CharacteristicsFetch");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
post += "<input id='" + dt.Rows[i]["chId"] + "' name='txt" + dt.Rows[i]["chId"] + "' title='" + dt.Rows[i]["chName"] + "' type='number' required='required' />";
}
}
return post;
}
I called this function from an .aspx page that I want use it:
charValues = cls.generate_CharValues();
The code will generate multiple html inputs that user must provide values for. Each input text has an Id related to it's database Id. Now I want get input values and input Ids then put them on a datatable to send it to database.
This is my try on submit test button:
DataTable dtChar = new DataTable();
dtChar.Columns.AddRange(new DataColumn[3] {
new DataColumn("chId", typeof(string)),
new DataColumn("animalId", typeof(string)),
new DataColumn("Rank", typeof(string))});
string animalId = "1";//animalId
int getcount = int.Parse(clsData.Select_One_Data("CharacteristicsGetCount", "chCount").ToString());
for(int i = 0; i < getcount; i++)
{
string chId = "";//input text id
string rank = "";//Request.Form["input text value"]
dtChar.Rows.Add(chId, animalId, rank);
}
any method with JS or JQuery will help me too. Thanks
i am sorry for the wrong answer
i was in hurry
try this
it wok for me and returns list of strings
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="check()" />
<asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button1_Click"/>
<input type="hidden" id="hdn" runat="server" />
</div>
<script>
function check() {
var val = document.getElementsByTagName("input");
var d = "";
for (var i = 0; i < val.length; i++) {
if (val[i].value != null && val[i].type == 'number') {
d += val[i].value+',';
}
}
d = d.slice(0, d.length-1);
document.getElementById("hdn").value = d;
}
</script>
</form>
and the code behind
protected void Button1_Click(object sender, EventArgs e)
{
string cd = hdn.Value;
List<string> values =cd.Split(',').ToList();
}

How to get the gridview textbox control ID in javascript?

I have ASP.NET Gridview and Textbox control in it. Now I want to get the Textbox ID in java script.
I had already referred this question in stack overflow but I couldn't get the exact answer.
My Gridview Template Code is
<asp:TemplateField HeaderText="Amt Recieve Now" ControlStyle-Width="100">
<ItemTemplate>
<asp:TextBox ID="txtAmountReceiveNow" runat="server" CssClass="textboxRight"
AutoPostBack="true" OnFocus= "GVtxtAmount()"
OnTextChanged="txtAmountReceiveNow_TextChange"
Text='<%#Eval("AMOUNT_RECEIVE_NOW")%>'>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
and Javascript code is as follows :
function GVtxtAmount() {
var txtAmountReceive = document.getElementById(
'<%= ((GVMaintainReceiptMaster)Container)
.FindControl("txtAmountReceiveNow").ClientID %>');
var selection = txtAmountReceive.value.indexOf(".");
alert(selection);
};
GVMaintainReceiptMaster is ID of GridView
Help me to overcome this problem.
Try this
function GVtxtAmount() {
var txtAmountReceive = $("input[id*=txtAmountReceiveNow]")
var selection = txtAmountReceive.value.indexOf(".");
alert(selection);
};
You can't get text box in this way. Here is the work-around I hope it will help.
function GVtxtAmount() {
var GVMaintainReceiptMaster = document.getElementById('<%= GVMaintainReceiptMaster.ClientID %>');
for (var rowId = 1; rowId < GVMaintainReceiptMaster.rows.length; rowId++) {
var txtbx = GVMaintainReceiptMaster.rows[rowId].cells[0].children[0];
alert(txtbx.value);
}
return false;
}

textbox value not saving in database

Here is my mark up code:
<p>
<label>Reference Code:</label>
<span class="field">
<asp:TextBox ID="GenerateCode" runat="server" CssClass="smallinput random" ></asp:TextBox>
<asp:HiddenField ID="txthidden" runat="server" />
<br /><small style="color: red">Please write the code at the back of yours check</small>
</span>
</p>
here is my random function:
function randomString()
{
var chars ="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var result = '';
for (var i = 8; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
return result;
}
here's how i get the random to be displayed in the textbox:
function generateRandomNumber() {
var rndStr = randomString();
$("#<%=GenerateCode.ClientID%>").val(rndStr);
$("#<%=txthidden.ClientID%>").val(rndStr);
}
window.onload = function () {
generateRandomNumber();
}
here's how i save it in the database:
string EchequeMaster = ClassEmailCheque.InsertEmailCheque(SenderID, Convert.ToInt32(ddlCurrency.SelectedIndex), Convert.ToDecimal(Amount.Text), ChequeNumber.Text, GenerateCode.Text, PendingStatus, DateTime.Now);
I solved this by using hidden field...i uodated my codes for reference.
Textboxes that are disabled (property Enabled = false) will not post back any value.
The solution is to have both a disabled textbox (to show the value to the user) and a hidden field which will post back the value. You could re write your code to something like this:
<asp:TextBox ID="txtGenerateCode" runat="server" CssClass="smallinput random" />
<asp:HiddenField ID="hdnGenerateCode" runat="server" class="random" />
function generateRandomNumber() {
var rndStr = randomString();
$(".random").val(rndStr);
}
Hope this helps!

Categories