I have a poll with a couple a questions. Here is html code
<form id="pool">
<div class="questions>
<input type="radio" name="sex">Male
<input type="radio" name="sex">Female
</div>
<div class="questions>
<input type="radio" name="hair">Brown
<input type="radio" name="hair">Blonde
</div>
.... a lot of qestions div's
</form>
What to do so after the form is submitted to be sure that there is a checked radio button in all div`s ?
If you know how many groups you have you can just do:
if($('#pool input:radio:checked').length < numGroups){
// At least one group isn't checked
}
Otherwise you need to count the number of groups first. I can't think of any way to do this better then:
var rgroups = [];
$('#pool input:radio').each(function(index, el){
var i;
for(i = 0; i < rgroups.length; i++)
if(rgroups[i] == $(el).attr('name'))
return true;
rgroups.push($(el).attr('name'));
}
);
rgroups = rgroups.length;
if($('#pool input:radio:checked').length < rgroups)
alert('You must fill in all the fields.');
else
alert('Thanks!');
set default values or create handler for submit button and check if some values was checked. If no radio button is checked, show error message and do not submit form ( return false)
Untested code, but this is the idea:
if($('#pool').children().length == $('pool
div').find('#pool input:radio:selected').length) {
//do stuff
}
You can use the jquery validate plugin
from my experience this plugin is very efficient
Related
I have two sets of checkboxes, named pizzaBase and pizzaTopping. I want to validate my form so that on submission at-least 1 base and topping must be selected.
function main() {
var form = document.getElementById('formname');
form.addEventListener('submit', validate);
}
function validate(event) {
var form = document.getElementById('formname');
if(!form.pizzaBase.checked) {
alert("select a base");
event.preventDefault();
}
else if(!form.pizzaTopping.checked) {
alert("select topping");
event.preventDefault();
}
else {
return true;
}
}
Problems
Only first if statement works.
Form submits true if checkbox is checked and then unchecked before
submission.
Doesn't validate, doesn't work.
Where am I going wrong?
Thank you GG for pointing out JS is working, I have HTML below if someone wouldn't mind correcting me. I basically have two identical versions of the below code, one for bases and the other toppings.
**
HTML
**
<section>
<h2> Bases </h2>
<p><input type="checkbox" name="pizzaBase" data-price="1.00" data-human-desc = "Small" value="Small"> Small (£1.00) </p>
<p><input type="checkbox" name="pizzaBase"data-price="1.50" data-human-desc = "Medium" value="Medium"> Medium (£1.50) </p>
<p><input type="checkbox" name="pizzaBase" data-price="2.50" data-human-desc = "Large"value="Large"> Large (£2.50) </p>
<p><input type="checkbox" name="pizzaBase" data-price="3.50" data-human-desc = "XLarge"value="XLarge"> XLarge (£3.50) </p>
</section>
Not sure if I should ask a separate question here, but this is my messy HTML. Is it the sections? I was trying to split each set of check boxes (bases, toppings) into two separate sections so used this tag.
Any ideas?
When you have multiple inputs with the same name, form.elementName will be an array-like list of elements.
The list won't have a checked property. Each item within it will.
You need to loop over the list and check to see if any of the elements are checked.
function areAnyChecked(list) {
for (var i = 0; i < list.length; i++) {
if (list[i].checked) {
return true;
}
}
return false;
}
if(! areAnyChecked(form.pizzaBase)) {
...
<label for="Merital Status">Marital Status:</label>
<input type="radio" title="Marital Status" name="Marital_Status" id="Marital Status" value="Single"/>Single
<input type="radio" title="Marital Status" name="Marital_Status" value="Married"/>Married
<input type="radio" title="Marital Status" name="Marital_Status" value="Divorced"/>Divorced
And I want to write a JavaScript function that checks whether a radi button named "Merital_Status" is selected. I represent the function that I wrote for this purpose. The function gets as an argument the element id and returnes boolen:
function radio_button_checker(elemId)
{
var radios = document.getElementsByTagName(elemId);
var value = false;
for (var i = 0; i < radios.length; i++)
{
if (radios[i].checked)
{
value = true;
break;
}
}
return value;
}
And I invoke this function like this:
if (radio_button_checker('Marital_Status') == false)
{
alert('Please fill in your Merital Status!');
return false;
}
But it does not work. Please tell me how to modify my function in order to check if radiobutton is checked.
What you are doing is looking for an element with the tag name "Merital_Status". Replace document.getElementsByTagName with document.getElementsByName and it should work.
You are mixing ID's and NAME's.
Your radio button "set" needs to all have the same name (which you have), and if you need to refer to them individually by id, then you'll need to add an id to the last two (currently not set... and not required if you apply the labels to each individual option). You will want the label tags for each radio button as it improves the usability by allowing the user to click on the word not just the small radio button.
Marital Status:
<label><input type="radio" name="Marital_Status" value="Single"/>Single</label>
<label><input type="radio" name="Marital_Status" value="Married"/>Married</label>
<label><input type="radio" name="Marital_Status" value="Divorced"/>Divorced</label>
However when you test... you want to see that at least 1 radio in the set is checked. You can do this with:
function radioButtonChecker(fieldNAME){
var radioSet = document.forms[0].elements[fieldName];
for(var i=0;i<radioSet.length;i++){
if(radioSet[i].checked){
return true;
}
}
return false;
}
There are a few presumptions made here.
You always have more than 1 radio button in the set
Your form is the 1st (index 0) form... if not you'll need to adjust the radioSet lookup
I am trying to make a page that allows users to select 8 checkboxes from a total of 25.
Im wondering, how to detect the exact order in which they check them. I am using a plain html front page that will be verified by a form action pointing to a php page.
Im trying to get a result like (checkbox1,checkbox2,checkbox6,checkbox3,checkbox7,etc) for eight checkboxes, and the exact order in which they were clicked.
I think I have found what I am looking for,Im not too sure, but Im having trouble implementing it.
This is what I have so far, I guess my question is, what type of php do I need to gather this info once a user has submitted the form.
For the form I have:
<form id="form1" name="form1" method="post" action="check_combination.php">
<label id="lblA1"></label>
<input name="checkbox1" type="checkbox" value="a1" onclick="setChecks(this)"/> Option 1
<label id="lblA2"></label>
<input name="checkbox1" type="checkbox" value="a2" onclick="setChecks(this)"/> Option 2
<label id="lblA3"></label>
<input name="checkbox1" type="checkbox" value="a3" onclick="setChecks(this)"/> Option 3
<label id="lblA4"></label>
<input name="checkbox1" type="checkbox" value="a4" onclick="setChecks(this)"/> Option 4
</form>
For the Javascript I have:
<script type="text/javascript">
<!--
//initial checkCount of zero
var checkCount=0
//maximum number of allowed checked boxes
var maxChecks=8
function setChecks(obj){
//increment/decrement checkCount
if(obj.checked){
checkCount=checkCount+1
}else{
checkCount=checkCount-1
}
//if they checked a 4th box, uncheck the box, then decrement checkcount and pop alert
if (checkCount>maxChecks){
obj.checked=false
checkCount=checkCount-1
alert('you may only choose up to '+maxChecks+' options')
}
}
//-->
</script>
<script type="text/javascript">
<!--
$(document).ready(function () {
var array = [];
$('input[name="checkbox1"]').click(function () {
if ($(this).attr('checked')) {
// Add the new element if checked:
array.push($(this).attr('value'));
}
else {
// Remove the element if unchecked:
for (var i = 0; i < array.length; i++) {
if (array[i] == $(this).attr('value')) {
array.splice(i, 1);
}
}
}
// Clear all labels:
$("label").each(function (i, elem) {
$(elem).html("");
});
// Check the array and update labels.
for (var i = 0; i < array.length; i++) {
if (i == 0) {
$("#lbl" + array[i].toUpperCase()).html("first");
}
if (i == 1) {
$("#lbl" + array[i].toUpperCase()).html("second");
}
}
});
});
//-->
</script>
I have gotten the part that only allows 8 checkboxes to be checked, but Im stuck as to what I need to do to actually parse the data once it has been submitted to a page with a name like check_combination.php.
I would appreciate any help
create a hidden input field with the order
update this input field when something changes
you'll have the order ready to be processed by PHP
I am relatively new to Javascript so I'm hoping this is a simple mistake. I building a generic form validation function that is called on the form's onSubmit. The function loops through all the form's child elements, looks for certain classes, and analyzes the contents of the appropriate fields. If it finds something missing or erroneous, it displays the appropriate error message div and returns false, thus preventing the form from being submitted to the php page.
It works well in firefox 3.6.3, but in every other browser I've tested (Safari 4.0.4, Chrome 4.1, IE8) it seems to ignore the onSubmit and jump straight to the php processing page.
HTML CODE:
<form name='myForm' id='myForm' action='process_form.php' method='post' onSubmit="return validateRequired('myForm')">
<fieldset class="required radioset">
<label for='selection1'>
<input type='radio' name='selection' id='selection1' value='1'/>
Option 1
</label>
<label for='selection2'>
<input type='radio' name='selection' id='selection2' value='2'/>
Option 2
</label>
<label for='selection3'>
<input type='radio' name='selection' id='selection3' value='3'/>
Option 3
</label>
<label for='selection4'>
<input type='radio' name='selection' id='selection4' value='4'/>
Option 4
</label>
<div class='errorBox' style='visibility:hidden'>
Please make a selection
</div>
</fieldset>
<fieldset class="required checkset">
<label>
Choice 1
<input type='checkbox' name='choices' id='choice1' value='1'/>
</label>
<label>
Choice 2
<input type='checkbox' name='choices' id='choice2' value='2'/>
</label>
<label>
Choice 3
<input type='checkbox' name='choices' id='choice3' value='3'/>
</label>
<label>
Choice 4
<input type='checkbox' name='choices' id='choice4' value='4'/>
</label>
<div class='errorBox' style='visibility:hidden'>
Please choose at least one
</div>
</fieldset>
<fieldset class="required textfield" >
<label for='textinput1'>
Required Text:
<input type='text' name='textinput1' id='textinput1' size='40'/>
</label>
<div class='errorBox' style='visibility:hidden'>
Please enter some text
</div>
</fieldset>
<fieldset class="required email textfield">
<label for='email'>
Required Email:
<input type='text' name='email' id='email' size='40'/>
</label>
<div class='errorBox' style='visibility:hidden'>
The email address you have entered is invalid
</div>
</fieldset>
<div>
<input type='submit' value='submit'>
<input type='reset' value='reset'>
</div>
</form>
JAVASCRIPT CODE:
function validateRequired(id){
var form = document.getElementById(id);
var errors = 0;
var returnVal = true;
for(i = 0; i < form.elements.length; i++){
var elem = form.elements[i];
if(hasClass(elem,"required")){
/*RADIO BUTTON or CHECK BOX SET*/
if(hasClass(elem,"radioset") || hasClass(elem,"checkset")){
var inputs = elem.getElementsByTagName("input");
var check = false;
for(j = 0; j < inputs.length; j++){
if(inputs[j].checked){
check = true;
}
}
if(check == false){
errors += 1;
showError(elem);
} else {
hideError(elem);
}
}
/*TEXT FIELD*/
else if(hasClass(elem,"textfield")){
var input = elem.getElementsByTagName("input");
if(input[0].value == ""){
errors += 1;
showError(elem);
} else {
hideError(elem);
/*EMAIL ADDRESS*/
if(hasClass(elem,"email")){
if(isValidEmail(input[0].value) == false){
errors += 1;
showError(elem);
} else {
hideError(elem);
}
}
}
}
}
}
if(errors > 0){
returnVal = false;
} else {
returnVal = true;
}
return returnVal;}
I know this is a lot of code to look at, but any help would be appreciated. Since it works fine in one browser, Im not sure how to start debugging.
Thanks
Andrew
for(i = 0; i < form.elements.length; i++){
var elem = form.elements[i];
if(hasClass(elem,"required")){
The problem is that your required and other classes are put on the <fieldset> element.
Fieldset elements are included in the form.elements collection on IE, Firefox and Opera, but not WebKit browsers (Chrome, Safari). It is these browsers where your form fails for me.
It has always been a weird quirk that <fieldset> was included in the elements collection. The DOM Level 2 HTML spec states that only ‘form control elements’ should be present in the collection, and by HTML4's definition that would seem not to include fieldsets, which have no control name or value.
You could perhaps change your code to use getElementsByTagName to pick up the fieldsets instead:
var fieldsets= form.getElementsByTagName('fieldset');
for (var i= 0; i<fieldsets.length; i++) {
var elem= fieldsets[i];
I would not use hasClass. Here's another way to try that might work better for you:
var node_list = document.getElementsByTagName('input');
for (var i = 0; i < node_list.length; i++) {
var node = node_list[i];
if (node.getAttribute('type') == 'text') {
// do something here with a <input type="text" .../>
alert(node.value);
}
}
I know that IE has problems getting the classes from some elements which have multiple classes associated with them. Regardless, this is a handy function.
If you have any kind of JavaScript error, the function will not return false, and therefore the default behavior of submitting the data will be triggered.
Try running your code through [http://www.javascriptlint.com/online_lint.php][1] first, then a debugger.
try not to use if(errors > 0)...just in every condition (for wrong input) put return false;
and at the end before the last bracket put return true;
and better use:
onSubmit="return validateRequired(this)"
and there is no need in this lines (in case you remove the errors var)
var form = document.getElementById(id);
var errors = 0;
var returnVal = true;
Not the cause of your problem, I'm sure, but it's best not to serve a set of radio buttons without one of them selected.
In your particular case, if you know that you set one when you serve the page, you don't need a "required" check; there's no way the user can get the radio buttons into a state where none are selected. Pick a sensible default, make it the first option, and make it selected. Simplify your life :)
From the W3C:
http://www.w3.org/TR/html401/interact/forms.html#radio
If no radio button in a set sharing
the same control name is initially
"on", user agent behavior for choosing
which control is initially "on" is
undefined. Note. Since existing
implementations handle this case
differently, the current specification
differs from RFC 1866 ([RFC1866]
section 8.1.2.4), which states:
At all times, exactly one of the radio
buttons in a set is checked. If
none of the <INPUT> elements of a set
of radio buttons specifies `CHECKED',
then the user agent must check the
first radio button of the set
initially.
Since user agent behavior differs,
authors should ensure that in each set
of radio buttons that one is initially
"on".
Back to basics for a second: You say it "seems to ignore the onsubmit". That leaves three possibilities that I can think of:
Your function is never called
It's called, and is bombing out part-way through due to an error
It's called, and isn't doing what you think it is, always returning true
It's not clear from your question which it is, so if I were you I'd start debugging this by putting an alert at the beginning of the function to see whether IE's calling it at all - then move that alert down and run the validation again, and see where it stops appearing (any error must be above that point).
I'd also want to alert the return value from the place it was called, to see what was coming back. If it's always true, then your code is working but not doing what you think it does.
From there, you at least have a clearer grasp of what's going on, if not an exact block of code to be scrutinising.
I have two forms, one with a radio button that users must select to edit.
[form name="A"]
<li>[input type="radio" name="BookItem" value="1" /]</li>
<li>[input type="radio" name="BookItem" value="2" /]</li>
<li>[input type="radio" name="BookItem" value="3" /]</li>
[form]<p>
After "BookItem" is selected from form (A) I call the $("#EditFormWrapper").load("callEditData.cfm? ID="+ID); function to load the second form (B)
<div id="EditFormWrapper"><div></p>
<!---// begin dynamic form generated by external file callEditData.cfm //--->
[form id="editForm" name="B"]
<ul class="hourswrapper">
<li><input type="checkbox" id="TOR2Hours" class="TOR2Hours" name="TOR2Hours" value="AM2Hrs1" /> 2 Hours AM</li>
<li><input type="checkbox" id="TOR2Hours" class="TOR2Hours" name="TOR2Hours" value="PM2Hrs1" /> 2 Hours PM</li>
<li><input type="checkbox" id="TOR2Hours" class="TOR2Hours" name="TOR2Hours" value="AM2Hrs2" /> 2 Hours AM</li>
<li><input type="checkbox" id="TOR2Hours" class="TOR2Hours" name="TOR2Hours" value="PM2Hrs2" /> 2 Hours PM</li>
</ul>
[input type="image" src="images/submit-btn.gif" id="addBTN" name="addBTN" class="buttons" alt="SubmitRrequest" /]
[input type="image" src="images/cancel-btn.gif" id="editBTNcancel" name="editBTNcancel" class="buttons" alt="Cancel Request" /]
[/form]
<!---// end dynamic form from external file //--->
I want to uncheck the radio button on form (A) when user click on cancel button (editBTNcancel) in form(B).
Here's my script:
$("#editBTNcancel").live("click", function(event){
event.preventDefault();
$("#EditFormWrapper").slideUp("fast").empty();
//$('.TOR2Hours').removeAttr('checked');
$('.TOR2Hours').attr('checked', false);
});
I hope I clearly state my problem, any suggestion would be greatly appreciated!
you can access form like so ...
var exampleForm = document.forms['form_name'];
then loop through the form
for( var i=0; i<exampleForm.length; i++ ){
alert( exampleForm[i].type );
}
you can test for checked like so ...
if( exampleForm[i].checked )
to deselect the checked radio button try ...
exampleForm[i].checked=false;
the final code would look like this ...
var exampleForm = document.forms['form_name'];
for( var i=0; i<exampleForm.length; i++ ){
if( exampleForm[i].type ) == 'radio' && exampleForm[i].checked == true ){
exampleForm[i].checked = false;
}
}
I'm not sure exactly what you want but you might try using a reset input.
<input type='reset' />
Seeing as this is pretty much the easiest DOM task there is and works in every scriptable browser, I suggest not using the jQuery methods for it:
$(".TOR2Hours")[0].checked = false;
The other thing that ocurs to me is whether your selector is correct. Did you mean to select a set of elements by class or should it be an ID selector?
Your selector is simply wrong.
If you want to uncheck the radio button from first form you should use $('input[name="BookItem"]') and not $('.TOR2Hours') :
$("#editBTNcancel").on("click", function(event){
$("#EditFormWrapper").slideUp("fast").empty();
$('input[name="BookItem"]').attr('checked', false);
});
As far as which method to use to uncheck radio buttons, The following 3 methods should all work:
$('input[name="BookItem"]').attr('checked', false);
$('input[name="BookItem"]').removeAttr('checked');
$('input[name="BookItem"]').prop('checked', false);
However, check out jQuery's docs on jQuery prop() for the difference between attr() and prop().
I just discovered a great solution to this problem.
Assuming you have two radios that need to be able to be checked/unchecked, implement this code and change what's necessary:
var gift_click = 0;
function HandleGiftClick() {
if (document.getElementById('LeftPanelContent_giftDeed2').checked == true) {
gift_click++;
memorial_click = 0;
}
if (gift_click % 2 == 0) {document.getElementById('LeftPanelContent_giftDeed2').checked = false; }
}
var memorial_click = 0;
function HandleMemorialClick() {
if (document.getElementById('LeftPanelContent_memorialDeed2').checked == true) {
memorial_click++;
gift_click = 0;
}
if (memorial_click % 2 == 0) { document.getElementById('LeftPanelContent_memorialDeed2').checked = false; }
}
:) your welcome
I use this way to solve your problem in ASP.net, check this..
radioButton.InputAttributes["show"] = "false";
string clickJs = " if(this.show =='true'){this.show ='false'; this.checked = false;}else{this.show='true'; this.checked = true;};";
radioButton.Attributes["onClick"] = clickJs;
In asp.net, you can use this way to add an attribute. And you can also to add an attribute manually to the radioButton, and do the function(clickJs) to change the ckecked attributes!!!