Hi I am developing web application. I have 4 radio button. I am trying to validate radio buttons. By default none of the radio box should be checked. On clicking on submit if none of the radio button is not checked then i want to display error message.
<form name="payment" novalidate>
<fieldset ng-disabled="paymentform">
<div class="upload-button-container">
<div class="upload-button bank button1">
<div class="upload-button-icon">
<label for="visa" class="visa">
<img src="images/visa.png">
<input type="radio" id="visa" name="selector" ng-model="card">
<span class="selector-visa"></span>
</label>
</div>
</div>
<div class="upload-button bank button2">
<div class="upload-button-icon">
<label for="americanexpress" class="americanexpress">
<img src="images/americanexpress.png">
<input type="radio" id="americanexpress" name="selector" ng-model="card">
<span class="selector-americanexpress"></span>
</label>
</div>
</div>
</div>
<div class="button-container margin-top80">
<input type="submit" value="{{ 'BACK' | translate }}" class="brown-button">
<input type="submit" value="{{ 'NEXT' | translate }}" class="blue-button" ng-click="makepayment()">
</div>
</fieldset>
</form>
I want to validate here in javascript file.
$scope.makepayment = function () {
if($scope.card!=null)
{
}else
{
toastr.error($filter('translate')('Error Occured', ''));
}
}
Above code always returns null. May I know what i am missing in the above code? Any help would be appreciated. Thank you.
There should be a value attribute in radio input tag.
The value to which the ngModel expression should be set when selected. Note that value only supports string values, i.e. the scope model needs to be a string, too. Use ngValue if you need complex models (number, object, ...).
Related
Edit: altered example code to include relevant typescript
I have a form with different buttons for the user to select. The button to submit the form is disabled until the user selects a button. The trick here is that I would like one of the options to not enable the submission button, but to instead show a textbox. The button should then be enabled if the user enters something into the textbox. At the moment, my HTML looks a little something like this:
<h1>Do you like sandwiches?</h1>
<form id="my-form" action="onSubmit()">
<div>
<button *ngFor="let option of myOptions"
class="form-button"
(click)="selectThisButton(option)">{{ option }}</button>
<div id="other-input" *ngIf="showInput">
<label for="text-input">Please elaborate.</label>
<input id="text-input" type="text" required>
</div>
</div>
</form>
<!--...some other code...-->
<button id="submit-button" form="my-form" type="submit" disabled="!my-form.valid">Next</button>
The typescript class is fairly straightforward as well:
selectedOption: string
showInput = false
needsExplanation = false
myOptions = ["Yes", "No", "I don't understand", "Other"]
selectThisButton(option: string){
this.selectedOption = option
this.needsExplanation = (option === "I don't understand")
this.showInput = (option === "Other")
}
onSubmit(){
if(this.selectedOption === "Other"){
this.selectedOption = (document.getElementById("text-input") as HTMLInputElement).value
}
continueAndDoOtherStuff()
}
All of this works except for the last step, i.e. entering something into the textbox doesn't enable the "next" button when it should.
I've also tried not using a form and just putting an EventListener on the textbox after the ngIf has rendered to listen for a keyup event, but that didn't work either.
Any help would be appreciated, especially suggestions that don't rely on jQuery.
a little bit short on time, so I'll work this answer further out later if you would like me to do so.
Why don't you add a (keyup.enter)-event in the input-box, e.g. (Angular 6 add input on enter key)?
The method you link to this event in the html-template, use it in the typescript template to switch a boolean true/false and link that boolean to the submit-button you want to enable/disable. (Like you're already doing.)
Please let me know:
(i) if you want this answer to be worked out
(ii) if it didn't help you (and what happened).
Take care and good luck.
(Sorry for the limited answer.)
Is there a motivation for using plain buttons instead of radio buttons?
Then, why don't you use the the APIs that Angular gives you?
First of all you could use [(ngModel)] instead of the selectThisButton function:
<form id="my-form" #form="ngForm">
<div>
<input type="radio" class="form-button" [(ngModel)]="selectedValue" value="yes" id="yes" name="selection" />
<label for="yes">Yes</label>
<input type="radio" class="form-button" [(ngModel)]="selectedValue" value="no" id="no" name="selection" />
<label for="no">No</label>
<input type="radio" class="form-button" [(ngModel)]="selectedValue" value="dont-understand" id="dont-understand" name="selection" />
<label for="dont-understand">I don't understand the question</label>
<input type="radio" class="form-button" [(ngModel)]="selectedValue" value="other" id="other" name="selection" />
<label for="other">Other</label>
<div id="other-input" *ngIf="selectedValue === 'other'">
<label for="text-input">Please elaborate.</label>
<input id="text-input" type="text" required>
</div>
</div>
</form>
<!--...some other code...-->
<button id="submit-button" form="my-form" type="submit" [disabled]="!form.valid">Next</button>
The only thing you need on your component.ts file is the selectedValue field:
#Component({
selector: ...,
templateUrl: './....component.html',
})
export class YourComponent {
selectedValue: string = undefined;
}
And your text input should be shown only when the other button is selected
Is there a way to validate the following checkbox ?
<form name="rmn-form" id="rmn-form" action="send.php" enctype="multipart/form-data" method="POST">
<div class="row">
<div class="col-md-12 col-xs-12">
<div class="rmn-input-field">
<label for="gdpr" class="checkbox-container"> Accept terms and conditions
<input type="checkbox" checked="checked" id="gdpr" name="gdpr">
<span class="checkmark"></span>
</label>
</div>
</div>
</div>
<button type="submit" name="submit" id="submit-all" class="waves-effect waves-light btn submit-button pink mt-30">Send</button>
</form>
The checkbox is generated by https://www.w3schools.com/howto/howto_css_custom_checkbox.asp
I have the following JSFiddle with my code with the bootstrap library and jquery.validate.min.js:
http://jsfiddle.net/2837qdeu/
Just change your input tag to the code below
<input type="checkbox" required="required" id="gdpr" name="gdpr">
It will check before submit that this checkbox must be checked.
Fiddle
You also can take control of this yourself, as below:
$("[name=submit]").click(function(){
if ( $('#gdpr').is(':checked') ){
alert('submit will proceed - checkbox is checked') //This alert not required, only added for demo
}else{
alert('Error - submit will not proceed');
return false; //<== Here is the magic, along with checking that the box is checked
}
});
Revised jsFiddle
return false will stop the submit procedure, allowing you to display a message, or do some js wizardry, before returning control to the user.
I added the following line in the js file and it worked just fine:
$("#rmn-form").validate({
ignore: ':hidden:not(:checkbox)',
....
});
I'm trying get the value of selected radio button using the selector $("input[name='job-destination[0]']") and $("input[name='job-destination[1]']"). However when I select the radio button in $("input[name='job-destination[1]']") it outputs the value from $("input[name='job-destination[0]']")
<div class="form-group">
<p>Destination</p>
<div class="radio-btn-grp">
<input class="job-destination" name="job-destination[0]" value="Australia" type="radio" required>
<label for="job-destination">Australia</label>
</div>
<div class="radio-btn-grp">
<input class="job-destination" name="job-destination[0]" value="Canada" type="radio">
<label for="job-destination">Canada</label>
</div>
</div>
<div class="form-group">
<p>Destination</p>
<div class="radio-btn-grp">
<input class="job-destination" name="job-destination[1]" value="Australia" type="radio" required>
<label for="job-destination">Australia</label>
</div>
<div class="radio-btn-grp">
<input class="job-destination" name="job-destination[1]" value="Canada" type="radio">
<label for="job-destination">Canada</label>
</div>
</div>
Seems that your values of $("input[name='job-destination[0]']") and $("input[name='job-destination[1]']") are equal. For the test purposes try to change the values. BTW, you can get HTML element, value of which you see, just type console.log($("input[name='job-destination[0]']")), for example
When you use $("input[name='job-destination[0]']").val() it will always return the value of first element irrespective of whether it is selected or not.
You need to use :checked Selector, along with .val() to get its value.
Matches all elements that are checked or selected.
$("input[name='job-destination[0]']:checked").val()
I am using the following Javascript code to validate that at least one of the radio inputs are checked before submitting the form, but I am facing a problem as the form always submit even if there are no radio inputs checked...can someone please help by telling me what I am missing here and how to fix it? Thanks
<script type="text/javascript">
function processPayment() {
if ($("input[name='orderAmount']:checked").length > 0){
alert('OK');
document.getElementById('orderFrm').submit();
return false;
}
else{
alert('Please select order amount');
}
}
</script>
<div id="content">
<form id="orderFrm" name="orderFrm" action="https://...." method="post" target="_top">
....
<div class="orderamnt">
<label for="orderAmount50">
<span class="labelText">50</span>
<input type="radio" id="orderAmount50" name="orderAmount" value="50"/>
</label>
</div>
<div class="orderamnt">
<label for="orderAmount100">
<span class="labelText">100</span>
<input type="radio" id="orderAmount100" name="orderAmount" value="100"/>
</label>
</div>
<div class="orderamnt">
<label for="orderAmount200">
<span class="labelText">200</span>
<input type="radio" id="orderAmount200" name="orderAmount" value="200"/>
</label>
</div>
<a class="buyNowButton" href="javascript:{}" onclick="processPayment()">Order</a>
....
</form>
</div>
Note:
I noted when checking any of the radio buttons that it changes from:
<div id="orderamnt">
<span class="">
<input type="radio" id="orderAmount200" name="orderAmount" value="200"/>
to...
<div id="orderamnt">
<span class="checked">
<input type="radio" id="orderAmount200" name="orderAmount" value="200"/>
obviously the radio input don't have checked and that's why obviously it is not working on my side, so wondering is there a way I can validate the first parent span from the radio button?
you need to do like this using is()
if ($('input[name="orderAmount"]').is(':checked'))
{
}
Using jquery 1.6.4 or +, this code is working!
$('.buyNowButton').click(function(){
if ($("input[name='orderAmount']:checked").length > 0){
document.getElementById('orderFrm').submit();
return false;
}
else{
alert('Please select order amount');
}
});
How do I validate that the input text corresponding to the radio option is checked?
For example, using the image above:
If Contact 1's E-Mail radio option is selected, Contact 1's E-Mail text field cannot be blank, but Contact 1's Phone and US Mail text fields are still permitted.
If Contact 2's US Mail radio option is selected, Contact 2's US Mail text field cannot be blank, but Contact 2's Phone and E-Mail text fields are still permitted.
I have built the form above using the HTML below, but you can play with my Fiddle here: fiddle.
BEGIN UPDATE: I have a newer fiddle with better code here:
fiddle2
It has more instructions in the HTML and a closer attempt at my jQuery. For some reason, though, it still does not seem to be doing anything.
END UPDATE
I have tried naming the fields so that my jQuery can parse them, but that does not mean there is not a better way.
<body>
<form name="jp2code" action="#" method="POST">
<fieldset>
<legend>Contact 1</legend>
<span>
<input type="radio" id="group1_PhoneRadio" name="group1"/>
<label for="group1_PhoneText">Phone:</label>
<input type="text" id="group1_PhoneText" name="group1_PhoneText"/>
<br/>
<input type="radio" id="group1_EMailRadio" name="group1"/>
<label for="group1_EMailText">E-Mail:</label>
<input type="text" id="group1_EMailText" name="group1_EMailText"/>
<br/>
<input type="radio" id="group1_USMailRadio" name="group1"/>
<label for="group1_USMailText">US Mail:</label>
<input type="text" id="group1_USMailText" name="group1_USMailText"/>
</span>
</fieldset>
<fieldset>
<legend>Contact 2</legend>
<span>
<input type="radio" id="group2_PhoneRadio" name="group2"/>
<label for="group2_PhoneText">Phone:</label>
<input type="text" id="group2_PhoneText" name="group2_PhoneText"/>
<br/>
<input type="radio" id="group2_EMailRadio" name="group2"/>
<label for="group2_EMailText">E-Mail:</label>
<input type="text" id="group2_EMailText" name="group2_EMaiText"/>
<br/>
<input type="radio" id="group2_USMailRadio" name="group2"/>
<label for="group2_USMailText">US Mail:</label>
<input type="text" id="group2_USMailText" name="group2_USMailText"/>
</span>
</fieldset>
<div>
<input type="submit" name="submit" value="submit" />
</div>
</form>
</body>
What is the best way to write the jQuery?
I am new to jQuery, but I attempted my hand at it based on some Show/hide examples.
What I created below does not work, but hopefully indicates what I am trying to accomplish.
$(function() {
$("input[type='radio']").change(function() { // when a radio button in the group changes
var id = $(this).id;
var index = id.indexOf('group');
if (index == 0) { // is there a better way to do this?
var groupN_Len = 7; // Length of 'groupN_'
var radio_Len = 5; // Length of 'radio'
var preStr = id.substring(0, groupN_Len);
$"input[name*='preStr']".validate = null; // clear validation for all text inputs in the group
var postStr = id.substring(groupN_Len + 1, id.Length() + 1 - radio_Len); // extract Phone, EMail, or USMail
$(preStr+postStr+'Text').validate({ rules: { name: { required: true } } });
}
});
});
To make sure that the radiobutton is checked for each field, add attribute required="" in one of the radiobuttons for each fieldset.
demo
OK, whatever radio button is selected in the Contact Group's Contact Preferences, that corresponding text field is required.
Here is where I am so far on my jQuery checking:
EDIT:
Modified with tilda's important detail about adding '.' to the class name.
Added Required Attribute: how to dynamically add REQUIRED attribute to textarea tag using jquery?
Removed Required Attribute: jquery removing html5 required attribute
Final code works and looks like this:
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script type="text/javascript">
$(function() {
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$("input[type='radio']").change(function() {
$('.'+$(this).attr('name')).each(function(index) {
$(this).removeAttr('required');
});
if($(this).is(':checked')) {
$('.'+$(this).attr('id')).each(function(index) {
$(this).prop('required',true);
});
}
});
$('#submit').click(function() {
$(this).validate();
});
});
Back to the HTML of the document: I did a lot of subtle editing to the text by creating specific ids and names for the radio buttons that matched up with the class names for the text controls.
Here is that end result:
<body>
<form name="jp2code" action="#" method="POST">
<div>For each field below, provide the Phone Number, E-Mail Address, and Street Address. <b>Indicate the preferred contact method using the radio button.</b></div>
<fieldset>
<legend>Contact 1</legend>
<span>
<input type="radio" id="group1_Phone" name="group1"/>
<label for="group1_Phone">Phone:</label>
<input type="text" name="group1_PhoneText" class="group1 group1_Phone" />
<br/>
<input type="radio" id="group1_EMail" name="group1"/>
<label for="group1_EMail">E-Mail:</label>
<input type="text" name="group1_EMailText" class="group1 group1_EMail" />
<br/>
<input type="radio" id="group1_USMail" name="group1"/>
<label for="group1_USMail">US Mail:</label>
<input type="text" name="group1_USMailText" class="group1 group1_USMail" />
</span>
</fieldset>
<fieldset>
<legend>Contact 2</legend>
<span>
<input type="radio" id="group2_Phone" name="group2"/>
<label for="group2_Phone">Phone:</label>
<input type="text" name="group2_PhoneText" class="group2 group2_Phone" />
<br/>
<input type="radio" id="group2_EMail" name="group2"/>
<label for="group2_EMail">E-Mail:</label>
<input type="text" name="group2_EMailText" class="group2 group2_EMail" />
<br/>
<input type="radio" id="group2_USMail" name="group2"/>
<label for="group2_USMail">US Mail:</label>
<input type="text" name="group2_USMailText" class="group2 group2_USMail" />
</span>
</fieldset>
<div>
<input type="submit" value="Send" id="submit"/>
</div>
</form>
</body>
Let me explain what is going on in the jQuery, using the HTML above:
When a radio button's checked state changes, each control with a class name that matches the radio button's name attribute has the required property removed.
If a radio button is checked (i.e. checked=true), then each control with a class name that matches the radio button's id attribute has the required property added.
Finally, the validator seems to have to be run on a single form control (not on individual text controls like I was doing).
Here is the sample Fiddle that I ended with: Fiddle v8
At tilda: You didn't say much, but what you did say helped a lot!