validate a dynamicnumber of checkboxes using javascript - javascript

I have some ASP code which presents any where from 1-any number of checkboxes (which are named the same) on the page. This validation does work however I think its a bit weak:
if (document.getElementById('selectedDocs').checked)
{
//this is here to handle the situation where there is only one checkbox being displayed
}
else
{
var checked = false;
var field = myForm.selectedDocs;
for(var j = 0; j < field.length; j++)
{
if(field[j].checked == true)
{
checked = true;
break;
}
}
if(!checked)
{
alert("You have not ticked any options. At least one must be selected to proceed!")
return false;
}
}
I was working with the code in the else block but this only works when there is more than one checkbox. It ignores the fact I have ticked the one single option when there is only one. So I placed the code inside the if section......Although it woks its a bit of a hack, can someone kindly improve it for me?
Thanking you...

Use:
var field = myForm.getElementsByName('selectedDocs');
This always returns a NodeList that you can iterate over.

If they are in a form and all have the same name, they can be accessed as a collection that is a property of the form. So given:
<form id="f0" ...>
<input type="checkbox" name="cb0" ...>
<input type="checkbox" name="cb0" ...>
<input type="checkbox" name="cb0" ...>
...
</form>
All the following return a reference to the form:
var form = document.getElementById('f0');
var form = document.forms['f0'];
var form = document.forms[0]; // if first form in document
and and all the following return a collection of the checkboxes named "cb0":
var checkboxes = form.cb0
var checkboxes = form['cb0'];
var checkboxes = form.elements.['cb0'];

Related

How to identify the checked radio button by using getElementsByName?

I have a form fontVortMetodo, which I declared as
var fM = document.forms["fontVortMetodo"];
The user has the choice to submit the form to one of three PHP pages. I let him make the choice first by radio buttons with the name select. Then he should press a button, which fires the result of the form elements to the selected page.
For this firing I used the function
function destinu() {
if (fM.elements("select")[0].checked) {
fM.action = "private_php/Zamenhofa.php";
} else if (fM.elements("select")[1].checked) {
fM.action = "private_php/intereuropeco.php";
} else if (fM.elements("select")[2].checked) {
tutm = true;
fM.action = "private_php/tutmondeco.php";
}
}
There was this error:
TypeError: fM.elements("select")[0].checked is not a function".
Maybe I should try
var destiny = getElementsByName("select")
and then proceed with if (destiny[0].checked) or if (destiny[0].checked == true).
I don’t know jQuery, which somebody advised me to use, and also for JavaScript I have no reference text. Where can I find a good tutorial for jQuery, although I prefer to do everything by using JavaScript pure?
Using pure JS
Use dataset attribute to store the action.
Use this selector [name="select"]:checked to get the checked radio button.
document.querySelector('button').addEventListener('click', function(e)  {
e.preventDefault();
var checked = document.querySelector('[name="select"]:checked');
var action = checked.dataset.action;
var form = document.querySelector('#fontVortMetodo');
form.setAttribute('action', action);
var tutm = checked.dataset.tutm !== undefined;
console.log("Action: " + action);
console.log('Is tutm: '+ tutm);
//$form.submit(); // This is if you need to to submit the form.
});
<form id='fontVortMetodo' name='fontVortMetodo'>
<input type='radio' name='select' data-action="private_php/Zamenhofa.php">
<input type='radio' name='select' data-action="private_php/intereuropeco.php">
<input type='radio' name='select' data-action="private_php/tutmondeco.php" data-tutm='true'>
<button>Submit</button>
</form>

Getting the ID of a radio button using JavaScript

Is there a way to get the ID of a radio button using JavaScript?
So far I have:
HTML
<input type="radio" name="fullorfirst" id="fullname" />
JavaScript
var checkID = document.getElementById(fullname);
console.log(checkID);
It outputs as null.
Essentially what I want to do is:
document.getElementById(fullname).checked = true;
...in order to change the radio button fullname to be checked on page load.
you should put fullname between quotes, since it's a string:
document.getElementById("fullname");
function checkValue() // if you pass the form, checkValue(form)
{
var form = document.getElementById('fullname'); // if you passed the form, you wouldn't need this line.
for(var i = 0; i < form.buztype.length; i++)
{
if(form.buztype[i].checked)
{
var selectedValue = form.buztype[i].value;
}
}
alert(selectedValue);
return false;
}
Hope this helps.
JavaScript Solution:
document.getElementById("fullname").checked = true;
Jquery Solution:
$("#fullname").prop("checked", true);

Could someone please explain a piece of Javascript code?

I am doing a project in school, and as part of that I had to include radio buttons in my html form. Below is the Javascript code which some parts I don't quite understand. The code works fine. Could someone plz give me an explanation of how the code works.
var check = false;
for (var i=0; i < document.ExamEntry.Level.length; i++)
{
if (document.ExamEntry.Level[i].checked)
{
var radiovalue = document.ExamEntry.Level[i].value;
check =true;
var usermessage=confirm("You have chosen: ".concat(radiovalue));
if(usermessage == false)
{
var radiovalue = "";
check = false;
}
}
}
<!--I understand the code below, its just some parts of the above code.
if (check ==false)
{
msg+="ERROR:You must select an entry level \n";
document.getElementById ('Levelcell'). style.color = "red";
result = false;
}
I added comments to help explain this:
var check = false;
// set a variable 'i' from 0 up to the ExamEntry level length (so for each radio)
// if there are 10 items, this code will run 10 times, each time with 'i' a different value from 0 to 9
for (var i=0; i < document.ExamEntry.Level.length; i++)
{
// is the radio button checked? If so, do the stuff inside. If not, skip this part
if (document.ExamEntry.Level[i].checked)
{
// set variable radiovalue to the value of the particular radio button
var radiovalue = document.ExamEntry.Level[i].value;
// set the check variable to true
check =true;
// ask the user to confirm the value and set usermessage based on confirmation
var usermessage=confirm("You have chosen: ".concat(radiovalue));
// if the user hits no on confirm, it will reset the radiomessage to blank and check to false
if(usermessage == false)
{
var radiovalue = "";
check = false;
}
}
}
All form elements are bound to the global HTML document variable. So somewhere on the page there must be a form with the name of ExamEntry:
<form name='ExamEntry' id='ExamEntry` ...
The next part refers to an element in the form. Since they are expecting a radio button, Level must be an input of type radio:
<label name="Level" id="1" type="radio" ....
<label name="Level" id="2" type="radio" ....
The loop iterates through all radio buttons. If the the button is checked, it grabs the checked value, and shows that message. If it does not find a checked button, then it displays an error message.

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.

Simple JavaScript check not working?

I have this validate form function:
function ValidateForm() {
var chks = document.register.elements['sendto[]'];
var hasChecked = false;
for (var i=0;i<chks.length;i++){
if (chks[i].checked){
hasChecked = true;
break;
}
}
if (!hasChecked){
alert("Please select at least one friend.");
chks[0].focus();
return false;
}
}
html for this is:
<input type="checkbox" name="sendto[]" value="2" >
I know this is not full code. Full code is huge. But basically if i have only one checkbox in the code the above code gives a message undefined on ValidateForm(). Which is called when form is submitted and and above checkbox is checked.
But if i have two checkboxes in the code like this:
<input type="checkbox" name="sendto[]" value="2" >
<input type="checkbox" name="sendto[]" value="4" >
On submit when ValidateForm() function is called this works correctly. Am i doing something wrong that it is not working for 1 checkbox even if it is checked?
The statement
var chks = document.register.elements['sendto[]'];
gets the element (element*s*, if there are more then one) with namesendto[]
If there is only one element with name sendto[] then you have the reference of that element in chks.
If there are more than one element with name sendto[], then chks holds the reference to the array of those elements.
When you do this:
for (var i=0;i<chks.length;i++){
You try to loop based on chks.length. If chks is an array (see above: when there are multiple elements by name sendto[]), then chks.length will hold the number of elements in the array.
If there is only one sendto[] element, then chks will hold that element and since the element (<input type="checkbox" name="sendto[]" value="2" >) does not have a property called length, the browser says length is indefined
So you have o differentiate between two scenarios, when there is only one sendto[] checkbox and when there are more than one.:
var chks = document.register.elements['sendto[]'];
var hasChecked = false;
//Check whether there is one checkbox or whether there are more
if(chks.length)
{
for (var i=0;i<chks.length;i++)
{
if (chks[i].checked)
{
hasChecked = true;
break;
}
}
}
else
{
if(chks.checked)
{
haschecked = true;
}
}
PS:
code gives a message undefined on ValidateForm() does not convey much. Even for you it is not clear what this means right (That's why you have asked this question). Try to give more details. Any modern browser will give more details on the undefined, the what is undefined which line etc. Even pre-historic browsers will tell you the line number where the undefined error was thrown. With those details you can try to find the line and try to see what is happening. You most likely will find out. If you don't, post it to the community here with all these details.
<script language="javascript">
function validate() {
var chks = document.getElementsByName('sendto[]');
var hasChecked = false;
for (var i = 0; i < chks.length; i++) {
if (chks[i].checked) {
hasChecked = true;
break;
}
}
if (hasChecked == false) {
alert("Please select at least one friend.");
return false;
}
return true;
}
</script>
Here is how I would do it.
if(!validate()){
alert("Please select at least one.");
return false;
}
function validate(){
var els=document.getElementsByName('sendto[]');
for(var i=0;i<els.length;i++){
if(els[i].checked){
return true;
}
}
return false;
}
You could use validate as an anonymous function.

Categories

Resources