Checkbox Validations - javascript

I cant simply get my head around javascript validations. I've seen tutorials and its just not getting to me. Someone please give me a SIMPLE step by step guide on how I can add validations to checkboxes. So say this is my form:
<form name="form1" method = "post">
<input name="Conservatives" type="checkbox" value="Conservatives" /> Conservative
<input name="Liberal Democrats" type="checkbox" value="Liberal Democrats" /> Liberal Democrats
<input name="Labour" type="checkbox" value="Labour" /> Labour
</form>
i want the user to select at least 2 checkboxes. the validation should be done from the client side of things which i will then take the values using php to send to the database?
any help guys?

It looks like you actually want radio buttons, not checkboxes.
If that is the case, use this:
<form action="" method="post">
<label><input type="radio" name="vote" value="Conserv" /> Conservative</label><br />
<label><input type="radio" name="vote" value="LibDem" /> Liberal Democrats</label><br />
<label><input type="radio" name="vote" value="Labour" /> Labour</label><br />
</form>
Then, in whatever server-side code you have, the vote POST variable will have either "Conserv", "LibDem" or "Labour" depending on user choice.

So you want to validate that, based on your comment, at least two of these checkboxes are checked? I would give them all the same name:
<input name="partyAffiliation" type="checkbox" value="Conservatives" /> Conservative
<input name="partyAffiliation" type="checkbox" value="Liberal Democrats" /> Liberal Democrats
<input name="partyAffiliation" type="checkbox" value="Labour" /> Labour
Then loop them and see how many are checked. document.getElementsByName will give you the checkboxes, each of which will have a checked property.
var allCbs = document.getElementsByName("partyAffiliation");
var numChecked = 0;
for(var i = 0, max = allCbs.length; i < max; i++)
if (allCbs[i].checked)
numChecked++;
if (numChecked < 2)
alert("Select at least two parties!");
I don't know the details of your project, but I'll just mention that jQuery will make the above code quite simple, if using this library is something you're not opposed to:
var numChecked = $("input[name='partyAffiliation']:checked").length;
if (numChecked < 2)
alert("Select at least two parties!");
EDIT
In response to a comment below, don't worry about having multiple inputs with the same name. Your server-side code should receive a comma delimited list of all (selected) values associated with that name. So if you check all three checkboxes, you'd see something like the below.

Related

Angular ngRepeat - How to have multiple objects containing radio buttons

I am doing some updates to a clients Ionic app but stuck on some binding.
There is a form with some fields including a couple of radio buttons.
E.g.
<div class="fields">
<input ng-model="student.name" type="text" name="student_name" id="name" />
<input ng-model="student.has_booked" type="radio" checked="checked" name="made_booking" id="made_booking_yes" value="1" />
</div>
The request for the update is to have a button that duplicates the details in this first form and add its to an array where the details can be used for another student as they are normally similar.
To do this I have a button that calls this method:
$scope.additionalStudents = []; // <-- for context of question
$scope.duplicateStudentDetails = function() {
var firstStudent = angular.copy($scope.student);
$scope.additionalStudents.push(firstStudent);
}
Then in my view:
<div class="fields" ng-repeat="(key, student) in additionalStudents track by $index">
<input ng-model="student.name" type="text" name="student_name" id="name" />
<input ng-model="student.has_booked" type="radio" checked="checked" name="made_booking" id="made_booking_yes" value="1" />
</div>
The issue I am having is that the name came be changed independently, but the checkbox always affects the original student. Im guessing this is because of the name attribute...
How do I go around this?
There might be two solutions to your problem.
If your case is just to show the status and not to change the booking status
Then, remove name attribute
If you want change the booking status in future
Better to have input of type checkbox with different names

Radio buttons ng-required checkbox like

I'm having a little problem with some radio buttons inside my form. I know that a checkbox could do this in a real easy way but, you know, customer asking for this.
So, this is the form part:
<label>
<span>Acconsento*</span>
<input type="radio" name="privacy_1" value="1" ng-model="ctrl.utente.privacy_1" ng-required="!ctrl.isValidPrivacy()"/>
</label>
<label>
<span>Non acconsento</span>
<input type="radio" name="privacy_1" value="0" ng-model="ctrl.utente.privacy_1"/>
</label>
With respective JS part:
self.isValidPrivacy = function () {
return (!self.utente.privacy_1 || self.utente.privacy_1 == 0) ? false : true;
};
and ctrl.utente.privacy_1 must be == 1.
After trying ng-required="ctrl.utente.privacy_1 != 1"
or ng-required="!ctrl.utente.privacy_1 (removing value="0" from 2nd radio input) I still haven't found a way to accomplish this.
ctrl.utente.privacy_1 == 0 isn't shown as validation error, and it can't be selected by default (ctrl.utente.privacy_1 can't be false by default)
All others answers on StackOverflow doesn't solve my problem
Well, I think you have some messed concepts...
First, you don't need a ternary operator to discern between true and false, just return the result of the comparision:
return (!self.utente.privacy_1 || self.utente.privacy_1 == 0);
would be enough. That said, you don't even need a function to check for this, you could do it directly on the attribute, since it's a simple check:
<... ng-required="!$ctrl.utente.privacy_1 || $ctrl.utente.privacy_1 == 0" .../>
That said, I don't understand why do you need an ng-required at all, maybe you've missunderstood its meaning... ng-required it's used to force the user to give a value to an input field, is NOT for checking it's value, that is what it seems you're trying to do. If you want to be sure that the user selects one of the two options just use the html attribute 'required' on both inputs, and that's enough.
<label>
<span>Acconsento*</span>
<input type="radio" name="privacy_1" value="1" ng-model="ctrl.utente.privacy_1" required />
</label>
<label>
<span>Non acconsento</span>
<input type="radio" name="privacy_1" value="0" ng-model="ctrl.utente.privacy_1" required />
</label>

radio button checked binding html5, durandal

even that I see very many similar questions in this site, no one of them answer to my question.
So pleas, don't be angry with me that I discuss this subject again.
I work in durandal project, I have html pages with javascript files behind.
I have two radio button in one of the pages.
I want their "checked" attribute to be binding to a variable in the view-model behind.
It is looked simple... but it is not!
I try two ways, any one of them didn't succeed:
first-way: in the html:
<input type="radio"
name="radSearchBy"
id="byNo"
data-bind:"checked:isId" />
in javascript:
isId: ko.observable(true)
second-way: in the html:
in javascript:
isId: ko.observable("checked")
I know what is the problem.
even if I simply write
<input type="radio"
name="radSearchBy"
id="byNo"
data-bind:"checked:true" />
or:
<input type="radio"
name="radSearchBy"
id="byNo"
checked="checked" />
it doesn't work.
only whem I write:
<input type="radio"
name="radSearchBy"
id="byNo"
**checked** />
yes, the "checked" word without anything follow- it works well.
but it is problem, becouse how can I do it *binding?*
please help me as quick as you can.
Unfortunately, the answer is a bit complicated. Radio buttons match the value of your observable to the value attribute of the radio button. In the boolean case, it is impossible to handle simply because HTML will return 'true' or 'false' as strings, not as booleans.
The solution requires AFAIK computed observables:
HTML
<input type="radio"
name="radSearchBy"
value="true"
data-bind="checked: value" />True
<input type="radio"
name="radSearchBy"
value="false"
data-bind="checked: value" />False
JavaScript
radSearchBy = ko.observable(true);
value = ko.computed({
read: function() { return radSearchBy.toString(); },
write: function(val) { radSearchBy(val === 'true'); }
});

Radio Button Getting Value

I have some html like this
<form id="reportform" method='post'>
<input type='hidden' id='qid' name='qid' value="<?php echo $id ?>" />
<span><input type="radio" id="reporttp" name="reporttp" value="spam" /> spam</span>
<span><input type="radio" id="reporttp" name="reporttp" value="attack" /> attacking</span>
<span><input type="radio" id="reporttp" name="reporttp" value="nonsense" /> nonsense</span>
<span><input type="radio" id="reporttp" name="reporttp" value="other" /> other</span
<input type="image" name='Submit' value='Submit' src="../Images/buttons/reportButton.png"/>
</form>
when i try to read the value in $('#reportform').submit(function() {
i read it as $(reportttp).attr("value"). And then i did some posting (which works fine). The problem is I always get "spam" postedf to me even though i select the other radio boxes. If i switch the first and second radio button around, ill get "attacking".... Could you tell me what is wrong?
You cannot have multiple elements with the same id
I assume you want to read the checked radio button's value? Is so, give them all unique ids, then do:
$("input[type='radio']:checked", "#reportform").val();
This will grab all radio buttons inside of you reportform, grab the checked one, then retrieve its value.
My guess is that your names and ids for each radio button are identical, causing the browser to make weird decisions arbitrarily.
In addition to Adam's answer, this is also invalid:
$(reportttp).attr("value")
should be
$('input[name="reportttp"]').val()
and I hereby retract my statement cause Adam updated his answer to a much better one.
and get rid of the duplicate id's
You should be able to do $('#reportttp').val() to get the selected value.

using checkbox as radio button

I am looking for a way for users to select one of the two options (strength or weakness) for a list of qualities.
for eg:
strength weakness not applicable
1. Communication
2. Punctuality
...
Radio button lets me select either a strength or weakness. However, I want the user to check only those qualities that apply and if a user accidentally selects a quality there is no way to undo the selection for a radio button unless there is a third radio button called not applicable or have the user re-enter the page. I was wondering if there is a way to be able to get the flexibility of a checkbox (check / uncheck) in addition to disabling or enabling the other checkbox when one of them is checked or unchecked instead of using three radio buttons.
I don't think I have seen this behavior before so wondering if there is a more elegant way of doing this. I am open to other ideas to get the same functionality. Using a checkbox as radio button was just a thought.
thanks much.
Solution based on javascript
function SetSel(elem)
{
var elems = document.getElementsByTagName("input");
var currentState = elem.checked;
var elemsLength = elems.length;
for(i=0; i<elemsLength; i++)
{
if(elems[i].type === "checkbox")
{
elems[i].checked = false;
}
}
elem.checked = currentState;
}​
<input type="checkbox" class="chkclass" onclick="SetSel(this);" />
<input type="checkbox" class="chkclass" onclick="SetSel(this);" />
<input type="checkbox" class="chkclass" onclick="SetSel(this);" />
<input type="checkbox" class="chkclass" onclick="SetSel(this);" />
Working Demo
Solution based on jQuery
$(function(){
$("input:checkbox.chkclass").click(function(){
$("input:checkbox.chkclass").not($(this)).removeAttr("checked");
$(this).attr("checked", $(this).attr("checked"));
});
});​
<input type="checkbox" class="chkclass" />
<input type="checkbox" class="chkclass" />
<input type="checkbox" class="chkclass" />
<input type="checkbox" class="chkclass" />
Working Demo
You should not use checkboxes as radio buttons (or vice-versa): this is inconsistent with the user's mental model, so it confuses people.
This is a problem with no ideal solution, but your initial suggestion of having a "not applicable" option as part of a group of 3 radio buttons is fairly common. If you pre-select the "not applicable" option by default and perhaps de-emphasize it visually (eg. gray it out) then from the user's point of view it will be almost as if there are only 2 options, but they can recover if they accidentally select one and want to "unselect" it.
this is correct form, "checked" is a proprietary and not attribute
$(function(){
$("input:checkbox.chkclass").each(function(){
$(this).change(function(){
$("input:checkbox.chkclass").not($(this)).prop("checked",false);
$(this).prop("checked", $(this).prop("checked"));
});
});
});

Categories