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>
Related
I have a form with multiple text fields.
In the form at the top is a question of two radio buttons:
Go direct or go public.
Go direct means you have to supply an email address.
Go public means the email box is disabled.
<input type="radio" name="target" value="public" />
<label for "public">Open to anyone </label></br>
<input type="radio" name="target" value="direct"/>
<label for="newEmail">Email address of the person:</label>
<input type="text" name="newEmail" id='newEmail'>
</br>
</br>
</br>
<label for="title">Book title:</label>
<input type="text" name="title" id='title'></br>
<label for="location">Location:</label>
<input type="text" name="location" id='location'>
No other form fields must be affected
You can do stuff like this
$('input:radio').on('click',function(){
if(this.checked && this.value == "public") // this.checked is not necessary as checking value already
$("#newEmail").prop("disabled",true);
else
$("#newEmail").prop("disabled",false);
});
Fiddle
Side Note: I would suggest click instead change() because radio buttons are often toggled in a group, you do not need to add more than one case or conditional logic like you do with checkboxes. though change can also be used
This will trigger the disabled state of the email input based on which radio button is selected.
var $radios = $('input[type="radio"]');
$radios.change(function() {
$('#newEmail').prop('disabled', $radios.first().is(':checked'));
});
JSFiddle
Got 2 radio buttons. If the second one is selected a div with a group of checkboxses is shown. In that case one of the checkboxses needs to be selected. But if the first radio button is selected then the div with the checkboxses isn't visibile but the validation messages is shown anyway.
<script>
webshims.setOptions('wspopover', { appendTo: 'body' });
$.webshims.activeLang("sv");
$.webshims.setOptions('forms', {
replaceValidationUI: true,
addValidators: true,
customMessages: true
});
$.webshims.setOptions('forms-ext', {
replaceUI: true
});
$.webshims.polyfill('forms forms-ext');
</script>
<input id="PersonOrCostDiv1" class="user-success" type="radio" required="" value="1" name="Level" data-cacheval="false">
<input type="radio" id="PersonOrCostDiv2" name="Level" required="" value="2" data-cacheval="false" class="user-success">
<input type="checkbox" data-dependent-validation='{"from": "PersonOrCostDiv2", "prop": "required", "from-prop": "value:2"}' value="100000001" id="checkbox-group100000001" class="group-required user-error" name="SelectedCostDivisions" aria-invalid="true">
<input type="checkbox" data-dependent-validation="'{"from": "PersonOrCostDiv2", "prop": "required", "from-prop": "value:2"}' value="100000004" id="checkbox-group100000004" class="group-required user-error" name="SelectedCostDivisions" aria-invalid="true">
I've been testing with and without "from-prop" and had some looks on this page:
http://afarkas.github.io/webshim/demos/demos/webforms/4-webforms-custom-validity.html
Notice what I think is a bug. If I fill up the requierd properties and then choose 'test 3' in the special case in the button. The page is posted to server.
But if I as in the first case fills up the requierd values and then choose 'test1' I got an error message. If I then choose 'test 3' that should work the error message is still there.
And another thing is when I use the 'group-required' I cant manage to get the error message in the selected language. The other messages works as it should.
Yeah, there was a small bug in the data-dependent-validation rule. The reason is, that data-depnendent-validation isn't really a customValidity modifier but a general property modifier, which has to be executed even if the control is invalid by another rule. (in your case group-required). I have fixed this issue (https://github.com/aFarkas/webshim/commit/7f670cf7693ab03dfc86097bda0491faf57b00ea).
But you should do it a little bit different. Instead of using data-dependent-validation='{"from": "PersonOrCostDiv2", "prop": "required", "from-prop": "value:2"}', you should simply use: data-dependent-validation="PersonOrCostDiv2". This will automatically check if the control is checked and will disable/enable the form-controls. Your HTML would look something like this (much simpler!):
<form>
<input id="PersonOrCostDiv1" class="user-success" type="radio" required="" value="1" name="Level" data-cacheval="false">
<input type="radio" id="PersonOrCostDiv2" name="Level" required="" value="2" data-cacheval="false">
<fieldset data-dependent-validation="PersonOrCostDiv2">
<input type="checkbox" value="100000001" id="checkbox-group100000001" class="group-required" data-errormessage="Please check on this group" name="SelectedCostDivisions">
<input type="checkbox" value="100000004" id="checkbox-group100000004" name="SelectedCostDivisions">
</fieldset>
<input type="submit" />
</form>
In case you don't want to update to the fixed version (It may have some bugs, because it's not a stable tested build (Note this is only fixed in master branch not the main gh-pages branch), you should remove data-dependent-validation. And disable/enable the controls or the fieldset yourself with JS depending on the checkedness of PersonOrCostDiv1. In case you use filedset:disabled, you have to use $.prop(fieldset, 'disabled', true/false) to make it work in IE. see: http://jsfiddle.net/trixta/K6nn9/).
To change the errormessage you need to either set it descriptive using the data-errormessage attribute (see html above) or with the following JS code:
webshims.ready('form-validators', function(){
webshims.customErrorMessages['group-required'].sv = "you really have to check on of these controls";
});
Feel free to ask again, if this doesn't help.
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'); }
});
I'm 95% there in writing an HTML5 'required' attribute fallback, I'm having a small issue and I've come to the end of the road in my knowledge!
What works:
Detecting 'required' attributes, looping through and alerting the user in several ways (onsubmit and entering data into the field).
Problem:
I'm taking the form one step further and want to make checkboxes and radio buttons required as well. By doing this, I need to add a required attribute to each radio/checkbox. I need to find out how to differentiate the group of buttons, as currently you need to tick/untick both sets of buttons for the form to validate and let you submit. So in a nutshell, I have three required radios for example, each will need to be ticked, how can I detect whilst looping through the inputs that one of the required radios/checked is ticked - I assume this would be done by matching the 'name' attribute, and if none in the name group are selected then alert just one error.
Here's the state of my loop, you can see I detect the input type as well, just unsure of the next steps forward. a jsFiddle is also below if anyone would be kind enough to help out. Many thanks.
// loop through class name required
$('.required').each(function () {
// this
var self = $(this)
// check shorthand if statement for input[type] detection
var checked = (self.is(':checkbox') || self.is(':radio')) ? self.is(':not(:checked)') : false
// run the empty/not:checked test
if (self.val() === '' || checked) {
// show error if the values are empty still (or re-emptied)
// this will fire after it's already been checked once
self.siblings('.form-error').show()
// stop form submitting
e.preventDefault()
// if it's passed the check
} else {
// hide the error
self.siblings('.form-error').hide()
}
})
Here's my jsFiddle: http://jsfiddle.net/zykF9/
With class selectors you could archive it
http://jsbin.com/owokuw/1/edit
UPDATE
to make easier to understand, here a update:
<input type="radio" name="myradio" class="myradio" />
<input type="radio" name="myradio" class="myradio" />
<input type="radio" name="myradio" class="myradio" />
<input type="radio" name="myradio" class="myradio" />
<input type="hidden" id="selectedRadioYes" />
<input type="button" id="botton" value="Botton" />
Jquery
$(".myradio").click(function(){
$("#selectedRadioYes").val(1);
});
$("#botton").click(function(){
if($("#selectedRadioYes").val() === "1")
alert("you can go on");
else
alert("need select one radio");
});
http://jsbin.com/owokuw/2/edit
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.