Why isn't this simple javascript working? - javascript

This javascript all but works with exception of radiobuttonlist.
<script language="javascript" type="text/javascript">
function validate() {
if (document.getElementById("<%=txtballotName.ClientID%>").value == "") {
alert("Ballot Name can not be blank");
document.getElementById("<%=txtballotName.ClientID%>").focus();
return false;
}
if (document.getElementById("<%=txtballotCity.ClientID %>").value == "") {
alert("Ballot City can not be blank");
document.getElementById("<%=txtballotCity.ClientID %>").focus();
return false;
}
if (document.getElementById("<%=txtballotState.ClientID%>").value == "") {
alert("Ballot State cannot be blank");
document.getElementById("<%=txtballotState.ClientID%>").focus();
return false;
}
if (document.getElementById("<%=txtballotZip.ClientID%>").value == "") {
alert("Zip Code cannot be blank");
document.getElementById("<%=txtballotZip.ClientID%>").focus();
return false;
}
if (document.getElementById("<%= txtreceivedby.ClientID %>").checked == false) {
alert("Request Received By can not be blank");
document.getElementById("<%=txtreceivedby.ClientID%>").focus();
return false;
}
return true;
}
The radiobuttonList looks like this:
<tr>
<td>
<label for="txtreceivedby_0">FAX</label>
<input id="txtreceivedby_0" type="radio" name="txtreceivedby" value="Fax" />
</td>
<td>
<label for="txtreceivedby_1">EMAIL</label>
<input id="txtreceivedby_1" type="radio" name="txtreceivedby" value="Mail" />
</td>
<td>
<label for="txtreceivedby_2">PHONE</label>
<input id="txtreceivedby_2" type="radio" name="txtreceivedby" value="Phone" />
</td>
</tr>
So far, the other form field are validating except the txtreceivedby radio button. I am not getting any errors but it isn't validating either.
Thanks in advance

You can create a short little utility function that will get you the value of any radio group:
function getRadioValue(name) {
var items = document.getElementsByName(name);
for (var i = 0; i < items.length; i++) {
if (items[i].checked) {
return(items[i].value);
}
}
}
You can then get the checked item in your radio group like this:
var val = getRadioValue("txtreceivedby");
Working Demo: http://jsfiddle.net/jfriend00/PHXaC/

ASP's radiobuttonlist render as a table containing radio button items. Therefore, it is a bit complicated to get the checked status of radio button.
You might find various sources if you google for "ASP radiobuttonlist and javascript". I have tested some of them and not every of them worked well specially if your page created from Master page.
However, I have tried in my own way and here it is:
<asp:RadioButtonList ID="txtReceivedBy" runat="server">
<asp:ListItem Text="Fax" Value="0"></asp:ListItem>
<asp:ListItem Text="Email" Value="1"></asp:ListItem>
<asp:ListItem Text="Phon" Value="2"></asp:ListItem>
</asp:RadioButtonList>
<input type="button" onclick="alert(checkedRadio());" value="Test RadioButtonChecked Status" />
and the javascript I have used to get the cehcked status is here
function checkedRadio() {
var rtn = false;
var i = 0;
var radioBoxesContainer = document.getElementById("<%=txtReceivedBy.ClientID%>");
if (radioBoxesContainer) {
var radioBoxes = radioBoxesContainer.getElementsByTagName("input");
if (radioBoxes && radioBoxes.length > 0) {
for (i - 0; i < radioBoxes.length; i++) {
if (radioBoxes[i].checked) {
rtn = true;
break;
}
}
}
}
return rtn;
}
if you are interested to get a live demo,
you can find it here http://plugins.amiwithyou.com/sof/

In a nutshell major headache; if you'd page me, I'd go with a nice good ol' fashion <select> box.
But to be useful, you need to have a look with view source at exactly what the ASP code plasts out to the browser. I don't know ASP but I bet it's either outputting 3 different ids on each radio, or the same id (#txtreceivedby) on all three of them.
Whatever it gives out, the validation code if(bla_bla_blah.checked===false) is wrong because it only targets just one in the set of radios and even with that fixed, that radio might not return .checked===false cross-browser.

Related

Form validation for Empty checking is not working properly In asp.net

I want to validate my form to avoid Empty. I am using asp.net inbuilt controls on my page i am using loop to check all fields are fill or not but its always showing empty even-though after filled all field. Is there any another approach to achieve same.
I have design my page in such way that its post back after selection of drop down list. that's why its not working i don't know.
<body>
<form id="form1" runat="server">
<div id="DivMainWindow" class="mainHeaderOuter">
<%--Inside this Div my all ASP controls are present--%>
<asp:ListBox ID="ddlregion" runat="server"
<asp:ListItem Value="0">Select</asp:ListItem>
</asp:ListBox>
<dx:ASPxDateEdit ID="deOrderDate" runat="server" Width="220px" AllowUserInput="false" Height="25px"EditFormatString="dd-MMM-yyyy" DisplayFormatString="dd-MMM-yyyy" EditFormat="Custom"ClientInstanceName="deOrderDate" OnInit="deOrderDate_Init">
..............
<asp:Button ID="btnGenerate" OnClientClick="return validate();" runat="server" OnClick="btnGenerate_Click" Text="Generate" />
so on
JAva script :
<script>
function validate() {
var inputTags = document.getElementsByTagName("input");
for (i = 0; i < inputTags.length; i++) {
if (inputTags[i].value === "") {
alert("All fields are required");
return false;
}
}
return true;
}
while inspecting on browser i am getting this :
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="">
I also tried individual control to check its empty or not but its not looping in such a way :
var Region = document.getElementById('<%=ddlregion.ClientID %>').value;
var Depot = document.getElementById('<%=ddlDepot.ClientID %>').value;
var INQFileType = document.getElementById('<%=ddlInqfileType.ClientID %>').value;
var QUOFileType = document.getElementById('<%=ddlqoutatfileType.ClientID %>').value;
var elements = document.getElementById("form1").elements;
for (var i = 0, element; element = elements[i++];) {
if (deOrderDate.GetValue() == null) {
alert("Please Enter Order Date");
return false;
}
if (Region == "None Selected" || null) {
alert("Please Select Region");
return false;
}
if (Depot == "Select" || null) {
alert("Please Select Depot");
return false;
}
if (deInqDate.GetValue() == null) {
alert("Please Enter INQ Date");
return false;
}
if (QUOFileType == "Select") {
alert("Please Select File Type");
return false;
}
}
}
What i need to change in that to fix this issues

How to get value of many selected radio buttons

I'm using JavaScript to get value from the radio boxes to insert it to the database as a string. What I need is that I have more than 2 radio boxes. How would I make use of Javascript to add the values to my database?
Here is my code:
<td>
<input type="radio" name="company_grp" class="largerCheckbox" value='Sentinel' checked="checked">
Sentinel GM
</td>
<td>
<input type="radio" name="company_grp" class="largerCheckbox" value='GuardTrack'>
GuardTrack
</td>
<td>
<input type="radio" name="company_grp" class="largerCheckbox" value='GuardingProduct'>
Guarding Product
</td>
if (!document.frmAdd_Visit.company_grp[0].checked && !document.frmAdd_Visit.company_grp[1].checked && !document.frmAdd_Visit.company_grp[2].checked) {
alert("Please Select the company group does this client belong's to!");
form.company_grp.focus();
return false;
}
It's very tricky but I don't get the correct value. When I select the 3rd radio, it doesn't add to the database but instead it reloads the page.
you can use jquery to get value form radio box
$(document).ready(function(){
$('input[name="company_grp"]:checked').val();
});
The jquery code below returns the value:
$('input[name=company_grp]:checked').val()
can use radio type checked as $(':radio:checked')
var selectedvalue;
if($(':radio:checked').length > 0){
$(':radio:checked').each(function (i) {
selectedvalue = $(this).val();
});
}
console.log(selectedvalue);
Here what I found and it working well for me.
function test_company_grp() {
var radios = document.getElementsByName("company_grp");
var found = 1;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
alert(radios[i].value);
found = 0;
break;
}
}
if(found == 1)
{
alert("Please Select the company group does this client belong's to!");
}
}

Using javascript to check if a radio button is selected and return a specific answer based on the selection

I am looking, in the cleanest way possible to be able to take a simple yes or no question and test for which answer has been chosen.
For instance in this case if a "yes" I want it to return a value of "Continue" into a specified area (a 3 column table which has a question in the first, the radio buttons in the second, and I want it to update and display the answer in the third).
My code for the JS stands thus far:
<script type="text/javascript">
var answer = 'place-holder';
var user_input;
function checkForm()
{
var substanceab = document.getElementById('Sub');
for (i = 0; i < substanceab.length; i++)
{
if(substanceab.length[i].checked)
{
user_input = substanceab.length[i].value;
}
}
if (user_input ="yes")
{
return answer = "Continue";
}
else if (user_input ="no")
{
return answer = "Provide Alternate Referral";
}
else
{
return;
}
};
function writeAns()
{
document.getElementById('answerwrite').innerHTML = checkForm[user_input];
};
</script>
and the Body text (minus the actual question):
<table class="table table-bordered">
<tr>
<td width="58%"><center><strong>Required:</strong></center></td>
<td width="19%"></td>
<td width="23%"><center><u><strong>___________</strong></u></center></td>
</tr>
<tr>
<td> <span class="sub depend"> <strong><i>_________</i> </strong></span></td>
<td> <span class="sub depend ans">
<form name="Substance">
<label class="radio inline">
<input type="radio" value="yes" name="substance" onclick="writeAns()">
yes </label>
<label class="radio inline">
<input type="radio" value="no" name="substance" onclick="writeAns()">
no </label> </form></span></td>
<div id="answerwrite"></div>
<script type="text/javascript">
document.write("<td>" + writeAns() + "</td>")
</script>
</tr></table>
Ok, fixed the 'funk' but like I said, more used to java than javascript, completely tougher syntax. I agree, I only used the ID thing to try and get this to work with a different method, but it never did. Now with some of the suggestions it is just giving me undefined everywhere. And while I agree this will eventually turn to jquery, I have NO clue how to work with it, hence figuring out this in javascript first.
A few things:
document.getElementByID()
will always return the first element, as ID's are supposed to be unique.
Instead, use:
document.getElementsByName('substance');
Next, in your loop, you are improperly referencing the array's members using the .length property. Try this instead:
for (i = 0; i < substanceab.length; i++)
{
if(substanceab[i].checked)
{
user_input = substanceab[i].value;
}
}
Finally, in javascript, the '=' opertator is always an assignment statement. To do comparisons, always use '==':
if (user_input == "yes")
{
return answer = "Continue";
}
else if (user_input =="no")
{
return answer = "Provide Alternate Referral";
}
else
{
return;
}
Also, try to avoid global variables whenever possible.
Here is the working code, refactored a bit:
<input type="radio" value="no" id= "Sub" name="substance" onclick="writeAns()">
function checkForm()
{
var user_input;
var substanceab = document.getElementsByName('substance');
for (i = 0; i < substanceab.length; i++)
{
if(substanceab[i].checked)
{
user_input = substanceab[i].value;
}
}
if (user_input == "yes")
{
return "Continue";
}
else if (user_input =="no")
{
return "Provide Alternate Referral";
}
else
{
return;
}
};
function writeAns()
{
document.getElementById('answerwrite').innerHTML = checkForm();
};
Very easy if you are using JQuery.
Ensure your elements have the same "name" attribute and use:
var RadioGroupResult = $('input[name="MyRadioGroupNameHere"]:checked').val();
Nice and simple.

Logic for multiple and single select/combo boxes

Below is my code:
<%#taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
<%#taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<script type="text/javascript">
var flag = false;
function test(selObject)
{
alert("hi");
var form = document.forms[0];
alert("form"+form);
var txtS = form["city"];
alert("txt"+txtS);
var len = txtS.length;
alert("len"+len);
for(var i=0; i<len; i++)
{
if (selObject == txtS[i] )
{
if(txtS[i].value==txtS[i].options[3].value)
{
alert("YOU ARE SELECTING MYSORE CITY");
flag = true;
}
if(!txtS[i].options[3].selected && flag)
{
var result = confirm("Are you sure you wnat to travel to this city");
if(result)
{
flag = false;
}
else
{
txtS[i].options[txtS[i].options.selectedIndex].selected=false;
txtS[i].options[4].selected=true;
}
}
}
}//end of for loop
}
</script>
<html:form action="/login">
username:<input type="text" name="username" /></br>
password:<input type="password" name="password"/></br>
<%
for(int i = 0; i < 10; i++){
%>
<html:select property="city" onchange="javascript:test(this);">
<html:option value="B">BANGALORE</html:option>
<html:option value="C">CHENNAI</html:option>
<html:option value="M">MANGALORE</html:option>
<html:option value="MR">MYSORE</html:option>
</html:select></br>
<%
}
%>
<input type="submit" value="submit"/>
</html:form>
When select-box or combo-box is looped for ten times then I am getting form["city"] length as 10 properly and behaviour of alerts within combox-box is appropriate, but if I have a single-select-box, then instead of giving form["city"] length as 1 it gives it as 4 which is the number of option elements in my dropdown-box.
So my logic doesn't work here.
How do I make it work for both single as well as multiple combo/select boxes.
Any help would be appreciated.
Please use a javascript library like jQuery for cross-browser compatibility.
You can use the following code to determine that only a single select element is present or multiple select elements with the same name are present:
if (selObject == txtS) {
alert("Single select");
// ... your logic for a single combo-box follows after this
} else {
// your logic for multiple combo-box follows, like the "for" loop and if-else
}
When there is only one select box the line var txtS = form["city"]; will return an array of option elements within that select box and when more than one select box with the same name it returns an array of the select boxes.
Hope this helps.
Not related to your question, but this logic if(!txtS[i].options[3].selected && flag) will always return false.

How do I make sure that at least one checkbox is checked?

I am using checkboxes whose values is coming from database. Its name is same but name is fetching like:
<input type="checkbox" id="chkBankServices" name="<%=bs.getServiceID()%>">
<%=bs.getServiceDesc()%>
through this i am getting the values from the database.
Now i have to validate that at least one checkbox should be selected..
If any one can help me i shall be thankful to u.
If i am giving like this the javascript code:
var services = document.getElementsById( 'chkBankServices' );
if(!(services[0].checked) &&
!(services[1].checked) &&
!(services[2].checked) &&
!(services[3].checked) &&
!(services[4].checked) &&
!(services[5].checked) &&
!(services[6].checked) &&
!(services[7].checked) &&
!(services[8].checked))
{
alert( "Please select at least one service to submit." );
return false;
}
It's not giving any alert message.
Is anything wrong in that.
Plz help me...
Thanks in advance
in jQuery :
alert( $("#chkBankServices input[type=checkbox]:checked").length > 0 );
Try this:
var services = document.getElementById( 'chkBankServices' );
var checkboxes = services.getElementsByTagName('input');
var checked = false;
for (var i=0,i0=checkboxes.length;i<i0;i++)
if (checkboxes[i].type.toLowerCase()=="checkbox")
{
if (checkboxes[i].checked) checked = true;
}
and then:
if (!checked)
{
alert('Not checked');
return false;
}
There is no getElementsById method, since there should only be one element with a given id. Perhaps you meant to use getElementsByName? This allows multiple elements to be returned.
As this is really a client side issue, it would help if you could post a sample of the generated HTML, and we can guide you further.
Have you checked the rendered source to make sure your checkboxes are being given the expected names?
I don't know if this will help you with your specific problem, but your code would be easier to read if you avoided the massive if block and used a loop instead:
var checked = false;
for(var i=0;i<services.length;i++){
if(services[i].checked){
checked = true;
}
}
if(!checked){
alert( "Please select at least one service to submit." );
return false;
}
Looking at your code, I'm betting you have that checkbox in a repeater of some sort and are creating multiple checkboxes with the same ID which is invalid html. I would wrap it in a div/span or something with an id like below:
if (!isSomethingChecked()) {
alert( "Please select at least one service to submit." );
return false;
}
function isSomethingChecked() {
var parent = document.getElementById("chkBankServices");
for (var child in parent.childNodes) {
var node = parent.childNodes[child];
if (node && node.tagName === "INPUT" && node.checked) {
return true;
}
}
return false;
}
I assumed the HTML looks like :
<div id="chkBankServices">
<input type="checkbox" id="Checkbox1" />
<input type="checkbox" id="Checkbox2" checked="checked"/>
<input type="checkbox" id="Checkbox3" checked="checked"/>
<input type="checkbox" id="Checkbox4" />
<input type="checkbox" id="Checkbox5" />
<input type="checkbox" id="Checkbox6" />
<input type="checkbox" id="Checkbox7" />
</div>

Categories

Resources