validation of radiobuttonlist in asp.net using javascript - javascript

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

Related

Client side validation for Textbox inside Gridview control Using Javascript Or Jquery

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>

How to call javascript function on checkboxlist item selection

HTML :
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem>C++</asp:ListItem>
<asp:ListItem>ASP.Net</asp:ListItem>
<asp:ListItem>Javascript</asp:ListItem>
<asp:ListItem>CSS</asp:ListItem>
<asp:ListItem>HTML</asp:ListItem>
<asp:ListItem>Java</asp:ListItem>
<asp:ListItem>Other</asp:ListItem>
</asp:CheckBoxList>
<div id="idskill">
<asp:Label ID="lblskilldescription" runat="server">Description</asp:Label>
<asp:TextBox ID="txbskilldescription" runat="server" Width="150px" OnTextChanged="TextBox8_TextChanged" Rows="5" TextMode="MultiLine"></asp:TextBox>
</div>
Scripts :
function toggleDiv()
{
$("#idskill").slideToggle("slow");
return false;
}
What I want is on selection Other div should toggle, on uncheck it should hide.
There should be "onchange" listener for the element. At least using JS we use the onchange event listener.
Try like this might help.
function list_onclick() {
var list = document.getElementById('CheckBoxList1');
var inputs = list.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked && inputs[i].value == "1") {
//do your work
}
else{
}
}
}

RadioButtonList checked with javascript

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>

How to ensure that if dropdown selection is first item nothing happens

I have the code below to open a pop up when user makes a selection. What I would like is to block when user selects the first item in the drop down as it has no real value. Also, I want to allow user to reselect already selected option by clicking the dropdownlist option again.
function OnClientSelectedIndexChanged(sender, eventArgs) {
var inputFieldValue;
var item = eventArgs.get_item();
grid = $find("<%= rggrid.ClientID %>");
var selectedRows = grid.get_selectedItems();
if (selectedRows.length > 0) {
for (var i = 0; i < selectedRows.length; i++) {
var row = selectedRows[i];
inputField = MasterTable.getCellByColumnUniqueName(row, "Item")
if (inputField) {
inputFieldValue = inputField.value
break;
}
}
}
else {
var inputFieldID = window['textItembox'];
inputField = document.getElementById(inputFieldID);
if (inputField) {
inputFieldValue = inputField.value;
}
}
window.radopen('<%=linker %> , "UserDialog");
return false;
}
When is the OnClientSelectedIndexChanged fired??
Anyway here is a quick sample:
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Text="-1" />
<asp:ListItem Text="1" />
<asp:ListItem Text="2" />
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Select" onclick="Button1_Click" />
$('#<%=Button1.ClientID %>').click(function () {
if ($('#<%=DropDownList1.ClientID %>').val() == "-1")
return false;
alert($('#<%=DropDownList1.ClientID %>').val());
});
Try
onclick = return(false);
to diable action on the first block and
mousedown = function(e){e.target.checked;}
or
mousedown = function(e){e.target.parentNode.selectedIndex = e.target.index;}
to be able to select your selected option again

Multiple DropDownLists - Call Single Function with ID

I have the following code which toggles the visibility of one of a pair of DropDownLists based on the selected radio button. This code works but my problem is that I have several sets of controls just like this on a single form. How can I use a single JavaScript Toggle() function, irrespective of the ID of the RadioButtonList that triggered it?
function Toggle()
{
var list = document.getElementById("produceDDL");
var inputs = list.getElementsByTagName("input");
var selected;
for (var i = 0; i < inputs.length; i++)
{
if (inputs[i].checked)
{
selected = inputs[i];
break;
}
}
if (selected.value == 'Vegetables')
{
div1.style.display = 'none';
div2.style.display = 'block';
}
else
{
div1.style.display = 'block';
div2.style.display = 'none';
}
}
<asp:radiobuttonlist ID="produceDDL" OnClick="javascript:Toggle();"
RepeatDirection="Horizontal" runat="server">
<asp:ListItem Selected="True">Fruit</asp:ListItem>
<asp:ListItem>Vegetables</asp:ListItem>
</asp:radiobuttonlist>
<div id="div1">
<asp:DropDownList ID="fruitDDL" Width="120" runat="server">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>Apples</asp:ListItem>
<asp:ListItem>Oranges</asp:ListItem>
</asp:DropDownList>
</div>
<div id="div2" style="display:none;">
<asp:DropDownList ID="vegDDL" Width="120" runat="server">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>Onions</asp:ListItem>
<asp:ListItem>Potatoes</asp:ListItem>
</asp:DropDownList>
</div>
Let the radio button list pass itself as function argument.
OnClick="javascript:Toggle(this);"
Then you can replace
function Toggle()
{
var list = document.getElementById("produceDDL");
// ...
by
function Toggle(list)
{
// ...
This way you can use OnClick="javascript:Toggle(this);" in other radio button lists.
By the way, the javascript: pseudoprotocol is unnecessary and the normal JavaScript naming convention is that function names should start with lowercase. I'd sanitize it as well :)

Categories