I am trying for a simple validation which consist of a RadioButtonList rblstPallet. I tried the below code:
javascript
var rblstPallet = document.getElementById('rblstPallet');
var counter = 0;
for (var intCount = 0; intCount < rblstPallet.length; intCount++) {
if (rblstPallet[intCount].checked) { //this step is not working
console.log(intCount); //I checked using this step
counter++;
}
}
if (counter == 0) {
//MSG: please select any item
}
else {
// Redirect to next page function
}
.aspx
<asp:RadioButtonList ID="rblstPallet" runat="server" RepeatDirection="Horizontal">
<asp:ListItem>Wood</asp:ListItem>
<asp:ListItem>Plastic</asp:ListItem>
<asp:ListItem>None</asp:ListItem>
</asp:RadioButtonList>
The problem is that if I even select one of the Radio Button, then also the counter value is remaining same. when I debugged the code, I came to know that the line
if (rblstPallet[intCount].checked) {
is not even executing nor even showing any errors in console. I am going through this link. I tried this link(not working).
Please help.
RadioButtoList is converted in radio buttons having id similar to radiobuttonlist id, you need to iterate through DOM to find the matching elements.
function getRadioButtonListSelections(radioButtonListName)
{
int selectionCount = 0;
for(i=0;i<document.forms[0].length;i++)
{
e=document.forms[0].elements[i];
if (e.id.indexOf(radioButtonListName) != -1 && e.checked)
selectionCount++;
}
return selectionCount;
}
alert(getRadioButtonListSelections('rblstPallet'));
Either use:
var rblstPallet = document.getElementById('<%=rblstPallet.ClientID=>');
Or
set the client id mode to static:
<asp:RadioButtonList ID="rblstPallet" runat="server" RepeatDirection="Horizontal" ClientIDMode="static">
And find and loop through each radio button:
var rblstPallet = document.getElementById('rblstPallet');
rblstPallet = rblstPallet.querySelectorAll('input[type="radio"]')
Replace
var rblstPallet = document.getElementById('rblstPallet');
By
var rblstPallet = document.getElementById('<%= rblstPallet.ClientID %>');
If you want to validate your radiobuttonlist why don't you use a validator control ?
<asp:RequiredFieldValidator ID="rfvPallet" runat="server"
ControlToValidate="rblstPallet" ErrorMessage="RequiredFieldValidator">
</asp:RequiredFieldValidator>
Related
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.
I have searched for a while but i couldn't find an answer to my situation
This is my problem:
I have a Textbox inside a Gridview like this:
<asp:TemplateField HeaderText="<%$ Resources:DCAAStrategicManagement, obj_lblStandardWeight %>" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtStandardWeight" onkeypress="return onlyNumbers();" Text='<%# Eval("StandardWeight") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
And i need to set a blur event on that TextBox using JQuery.
This is my attempt to achieve that:
$("input[id*='<%=txtStandardWeight.ClientID %>']").blur(function () {
Read();
var currentSum = document.getElementById('<%=hidden.ClientID %>').value;
var oldLabelData = $('#<%= lblStandardWeightCurrently.ClientID %>').value;
var newLabelData = oldLabelData + currentSum;
$('#<%= lblStandardWeightCurrently.ClientID %>').value(newLabelData);
})
This function should change the lblStandardWeightCurrently Text whenever the blur even occurs.
But There is no changes in lblStandardWeightCurrently label..
Read() Function:
function Read() {
debugger;
var oDataGrid = document.getElementById("<%= grdPlanObjectivesStandardWeights.ClientID %>");
var tableRows = oDataGrid.rows;
var sum = 0;
for (var i = 1; i < tableRows.length; i++) {
var col1 = oDataGrid.rows[i].cells[2];
for (j = 0; j < col1.childNodes.length; j++) {
if (col1.childNodes[j].type == "text") {
if (!isNaN(col1.childNodes[j].value) && col1.childNodes[j].value != "") {
sum += parseInt(col1.childNodes[j].value)
}
}
}
}
if (!isNaN(sum)) {
document.getElementById('<%=hidden.ClientID %>').value = sum;
}
}
I think the problem is here:
$("input[id*='<%=txtStandardWeight.ClientID %>']").blur(function ()
since i can't debug this function .
Any help would be appreciated.
Note that your textbox is inside a template. That means that it actually does not exist until grid view is databound, and even what it is, there are many textboxes, one per row, each having a different ID. That means that you cannot simply access it by txtStandardWeight.
However since you are using jQuery anyway, why don't assign some class to the textbox which would allow you to query for it easily?
<asp:TextBox runat="server" ID="txtStandardWeight" CssClass="weightText" ...
$("input.weightText").blur(function () {
One more thing - make sure your javascript is defined in .aspx file, otherwise syntax <%# %> won't work.
$().ready(function () {
$("#<%= text.ClientID%>").find("tr").each(function () {
$(this).find("td").each(function () {
$(this).find("input[id*=txtStandardWeight]").blur(function () {
alert("Hello");
});
});
});
});
Let's take an example where gridview has id=text and your textbox has an id=txtStandardWeight then we have to traverse each row and column to get proper result and when you find your textbox then manage the proper functioning according to you.
I am developing asp.net application, in that i have a page contains gridview with text boxes,
in that i need to validate to fill atleast one text box in that gridview.
I googled many pages, but i have found only check box validation like this,
when save button click, i need to validate to fill atleast one text box in deposit amount in that gridview..
please any answers would be appreciated..
Use RequiredFieldValidator
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txtAmount" ErrorMessage="Fill This"></asp:RequiredFieldValidator>
<script type="text/javascript">
function validateTextBox() {
//get target base & child control.
var TargetBaseControl = document.getElementById('<%=this.Gridview1.ClientID%>');
var TargetChildControl1 = "txtDepositAmount";
//get all the control of the type INPUT in the base control.
var Inputs = TargetBaseControl.getElementsByTagName("input");
for (var n = 0; n < Inputs.length; ++n)
if (Inputs[n].type == 'text' && Inputs[n].id.indexOf(TargetChildControl1, 0) >= 0)
if (Inputs[n].value != "") return true;
alert('Enter Atleast One Deposit Amount!');
return false;
}
</script>
<asp:ImageButton ID="btnSave" runat="server" ValidationGroup="valInsert" ImageUrl="~/images/save6.png"
Width="40px" Height="40px" OnClientClick="javascript:return validateTextBox();" OnClick="btnSave_Click" ToolTip="Save" />
You can use a CustomValidator and jQuery to check if at least one TextBox has text in it.
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="At least one TextBox is required" ClientValidationFunction="validateMyTextBoxes"></asp:CustomValidator>
<script type="text/javascript">
function validateMyTextBoxes(oSrc, args) {
var isValid = false;
$("#<%= GridView1.ClientID %> input[type=text]").each(function () {
if ($(this).val() != "") {
isValid = true;
}
})
args.IsValid = isValid;
}
</script>
i have to validate a radio button using javascript. it should show a message if none of the option is selected.
my radio button code is:
<asp:RadioButtonList ID="welldata" runat="server" RepeatDirection="Horizontal" Width="100px">
<asp:ListItem></asp:ListItem>
<asp:ListItem></asp:ListItem>
</asp:RadioButtonList>
and the submit button is:
<asp:Button ID="next2" runat="server" Text=">>" Width="46px"
OnClientClick="return next2()"/>
the corresponding javascript function is :
function next2() {
var listItemArray = document.getElementById('<%=welldata.ClientID %>');
var isItemChecked = false;
var length1 = listItemArray.length;
for (var i=0; i<length1; i++)
{
var listItem = listItemArray[i];
document.write(listItem);
if ( listItem.checked )
{
alert(listItem.value);
isItemChecked = true;
}
}
if ( isItemChecked == false )
{
alert('Nothing is checked for welldata!');
return false;
}
return true;
}
while debugging i noticed thaat function is executed but doesn't enter the for loop.
also i tried
document.write(isItemChecked);
document.write(listItemArray);
document.write(length1);
and the output was :
false [object HTMLTableElement] undefined
The wellData RadioButtonList ASP.NET server control will render in the browser as a table with a number of input type="radio" controls under it, each with the same name.
So, you need to get the input tags inside the table tag first:
var wellData = document.getElementById('<%=welldata.ClientID %>');
var listItemArray = wellData.getElementsByTagName('input');
This is, of course, if you are doing this manually for some odd reason. You can do it automatically with a RequiredFieldValidator control.
<asp:RadioButtonList ID="welldata" runat="server" RepeatDirection="Horizontal" Width="100px">
<asp:ListItem></asp:ListItem>
<asp:ListItem></asp:ListItem>
</asp:RadioButtonList>
<asp:RequiredFieldValidator ID="rfvWellData" runat="server" ControlToValidate="wellData" Display="Dynamic" ErrorMessage="Pick yourself some well data" />
You are using a RadiobuttonList which is rendered as table per default. If you select the dom element by id document.getElementById('<%=welldata.ClientID %>') then you are selecting the table and not the RadioButtonList. If you want to select the radio buttons then you have to loop through the childNodes of listItemArray to get the radio buttons. Alternatively you could use jquery to select the radio buttons, as their ids will start with the id of your radio button list (they will look like welldata_0 or welldata_1).
This line of jquery code will get the your radio buttons
var listItemArray = $("input[id^='welldata']")
Try this:
function next2() {
if(document.getElementById('<%=welldata.ClientID %>').checked==false)
{
alert('Nothing is checked for welldata!');
return false;
}
return true;
}
or
Use RequiredFieldValidator
<asp:RequiredFieldValidator
ID="ReqiredFieldValidator1"
runat="server"
ControlToValidate="welldata"
ErrorMessage="Select your welldata!"
>
Check these below links
http://asp-net-example.blogspot.in/2009/02/aspnet-requiredfieldvalidator-example.html
http://www.itechies.net/tutorials/jscript/jsexample.php-pid-jform.htm#rb
http://www.codeproject.com/Questions/499602/RequiredplusFieldplusValidatorplusForplusRadioplus
var rblItems = document.getElementById('<%=radioBtnListId.ClientID %>').getElementsByTagName('input');
var checkedItems = true;
for (var i = 0; i < rblItems.length; i++) {
if (rblItems[i].checked) {
checkedItems = true;
break;
}
else {
checkedItems = false;
}
}
if (!checkedItems) {//Hence No items checked
alert("Nothing is checked");
return false;
}
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;
}