I need some inputs to be required only if certain options are checked in another input (radio). In short, if Type 1 documents is chosen, I need type 1 field number to be obligatory. It's easier to visualize through this jsfiddle below:
https://jsfiddle.net/kbhatd51/2/
Could you please help me? Thanks in advance
<form id="registerform" method="post">
<div class="form-group">
<label >Type of Document</label><br>
<input type="radio" class="radioForm" id="fis" name="tipop" value="0" > <label for="fis"> Type 1</label><br>
<input type="radio" class="radioForm" id="jur" name="tipop" value="1" > <label for="jur"> Type 2</label><br>
</div>
<label for="tipop"> Number</label>
<div class="form-group">
<fieldset id="cpf1">
<label for=cpf1>Type 1 No.:</label>
<input type="number" class="form-control" placeholder="000.000.000-00" name="cpf" id="cpf" >
</fieldset>
<fieldset id="cnpj1">
<label for=cnpj1> Type 2 No.:
<input type="number" class="form-control" placeholder=" 00.000.000/0001-00" name="cnpj" id="cnpj"></label>
</fieldset>
</div>
<input name="submit" type="submit" value="Submit!">
</form>
JS validate:
$("#registerform").validate({
rules: {
cpf: {
required: "#fis:checked"
},
cnpj: {
required: "#jur:checked"
}
}
});
The required method needs to return true for the field to be required.
So you can simply pass a function to required which will check if the radio element is checked
required method
required( dependency-callback )
Type: Function()
The function is executed with the element as it's only argument: If it returns true, the element is required.
$("#registerform").validate({
debug: true,
rules: {
cpf: {
required: function(elem) {
return $('#fis').is(":checked")
}
},
cnpj: {
required: function(elem) {
return $('#jur').is(":checked")
}
}
}
});
Check out the -- JSFiddle Example -- here.
Related
I am trying to call a function when the check box is checked and set the field values accordingly. The checkbox and the address fields are like below
<div class="form-check">
<input class="form-check-input position-static" type="checkbox" id="SameAsShippingAddress" value="SameAsShippingAddress" data-bind="checked: sameAsShippingAddress" />
<label>Check this box if Shipping Address and Billing Address are the same.</label>
</div>
<div class="row">
<div class="col-md-6">
<h4>Shipping Address:</h4>
<div class="form-group required">
<label for="EmailCompetitor" class="control-label">Email:</label>
<input type="email" maxlength="150" id="EmailCompetitor" name="EmailCompetitor" class="form-control" data-bind="value: emailCompetitor" required />
</div>
<div class="form-group required">
<label for="FirstNameCompetitor" class="control-label">First Name:</label>
<input type="text" maxlength="150" id="FirstNameCompetitor" name="FirstNameCompetitor" class="form-control" data-bind="value: firstNameCompetitor" required />
</div>
</div>
<div class="col-md-6">
<h4>Billing Address:</h4>
<div class="form-group required">
<label for="EmailCompetitor_Billing" class="control-label">Email:</label>
<input type="email" maxlength="150" id="EmailCompetitor_Billing" name="EmailCompetitor_Billing" class="form-control" data-bind="value: emailCompetitor_Billing" required />
</div>
<div class="form-group required">
<label for="FirstNameCompetitor_Billing" class="control-label">First Name:</label>
<input type="text" maxlength="150" id="FirstNameCompetitor_Billing" name="FirstNameCompetitor_Billing" class="form-control" data-bind="value: firstNameCompetitor_Billing" required />
</div>
</div>
I want the check box boolean value captured seperately as well as when check box is checked it needs to call the function. So in js I have like
var orderRequestFormViewModel = function () {
var self = this;
self.currentPage = ko.observable(1);
self.referringPage = ko.observable();
...............
self.sameAsShippingAddress = ko.observable().extend({ required: false });
..........
self.sameAsShippingAddress = function () {
if (this.checked) {
$("#EmailCompetitor_Billing").val($("#EmailCompetitor").val());
$("#FirstNameCompetitor_Billing").val($("#FirstNameCompetitor").val());
} else {
$("#EmailCompetitor_Billing").val("");
$("#FirstNameCompetitor_Billing").val("");
}
}
But when the checkbox is checked/unchecked this function is not being called at all
I tried put the breakpoint but the function is not being it. New to this JS world, any help is greatly appreciated
Hey I made you a little snippet to show you that it works perfectly fine when using an observable and checked binding, when checkbox is checked, it is "true" if not it´s "false"
To make custom stuff like setting .val() of other input just use a computed function, it will be called whenever isChecked changes
var model = function () {
var self = this;
self.isChecked = ko.observable(false);
self.doStuffWhenChecked = ko.computed(function(){
if(self.isChecked()){
$('#textinput').val("whatever");
}else{
$('#textinput').val("");
}
},this);
}
var vm = new model();
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<label>Check this: </label>
<input type="checkbox" data-bind="checked: isChecked">
<span data-bind="visible: isChecked()"> Only show when checked </span>
<input type="text" id="textinput" >
I'm creating a form that requires to enter some fields.
The basic required attribute won't work on me, so I would like to use jQuery.
Then when those fields were already filled, the submit button will be enabled.
here's my code:
$(function() {
$('#catalog_order').validate(
{
rules:{
schedule: {
required: true
}
},
messages:{
schedule: "Please indicate schedule",
}
});
$('#checkin input').on('keyup blur', function (e) { // fires on every keyup & blur
if ($('#checkin').valid()) {
$('#submit').attr('disabled', false);
}
else {
$('#submit').attr('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
<form role="form" id="checkin" name="checkin" method="post">
<label for="dedicatalog"> Dedication Text: </label> <input type="text" name="dedicatalog" id="dedicatalog" size="20" placeholder="Dedication" /> <!-- NOT REQUIRED, but still disable the CHECK IN NOW-->
<label for="schedule"> Date: </label> <input type="date" id="schedule" name="schedule" value="M-D-YY"/> <!-- REQUIRED -->
<label for="figurine_select"> Figurine/s: </label> <!-- NOT REQUIRED, but still disable the CHECK IN NOW-->
<select name="figurine_sel" id="figurine_select" />
<option selected value=" ">--Figurines--</option>
<option value="angel">Angel</option>
<option value="teletubies">Teletubies</option>
</select>
<input type="submit" id="submit" class="btn btn-default" value="Check In Now" disabled="disabled" />
</form>
Hope someone can help me out.
Thank you!!
This Fiddle Should work
Note that for every field you should specify all its option inside js object ( between brackets )
schedule: {
required: true
},
Below working snippet
jQuery.validator.addMethod("dateFormat", function(value, element) {
console.log(value,/^(0?[1-9]|1[0-2])\/(0?[1-9]|1[0-9]|2[0-9]|3[01])\/\d{2}$/.test(value));
return /^(0?[1-9]|1[0-2])\/(0?[1-9]|1[0-9]|2[0-9]|3[01])\/\d{2}$/.test(value);
}, "Invalid Date !");
$(function() {
$('#checkin').validate(
{
rules:{
schedule: {
required:true,
dateFormat: true,
}
},
messages:{
required:"Required Field !"
}
});
$('#checkin input').on('keyup blur', function (e) { // fires on every keyup & blur
if ($('#checkin').valid()) {
$('#submit').attr('disabled', false);
}
else {
$('#submit').attr('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
<form role="form" id="checkin" name="checkin" method="post">
<label for="dedicatalog"> Dedication Text: </label> <input type="text" name="dedicatalog" id="dedicatalog" size="20" placeholder="Dedication" />
<label for="schedule"> Date: </label> <input id="schedule" name="schedule" placeholder="M-D-YY"/>
<input type="submit" id="submit" class="btn btn-default" value="Check In Now" disabled />
</form>
This is how I validate that.
return false is just the same us disabling it
<form role="form" id="checkin" name="checkin" method="post">
<input id="dedicatalog"/>
<input id="date" type="date"/>
</form>
<script>
$('#checkin').on('submit', function() {
var dedicatalog = $.trim($('#dedicatalog').val());
var date = $.trim($('#date').val());
if(dedicatalog == '' || date == '') {
return false;
}
});
</script>
You can use the invalidHandler parameter to check for any invalid fields:
invalidHandler: function(event, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
$('#button').hide();
} else {
$('#button').show();
}
}
I'm trying to work out how to push checked checkboxes, that are submitted via a form, to an object called services, using AngularJS.
These are my objects:
$scope.sectors = [ 'health', 'social', 'education' ];
$scope.services = [
{
'name': 'Hernia Repair',
'sectors': { 'health': true }
},
{
'name': 'Cancer',
'sectors': { 'health': true, 'social': true, 'education': true }
},
];
And this is my form:
<form role="form" ng-submit="createService(newService)">
<div class="form-group">
<label for="serviceName">Name of Service</label>
<input id="serviceName" type="text" class="form-control" ng-model="newService.name" placeholder="Name of Service">
</div>
<div class="form-group">
<label for="serviceName">Another</label>
<input id="serviceName" type="text" class="form-control" ng-model="newService.another" placeholder="Name of Antoher">
</div>
<div class="checkbox-inline" ng-repeat="sector in sectors">
<label>
<input type="checkbox" name="optionsRadios" id="{{sector}}" value="{{sector}}" ng-model="service.sectors[sector]">
{{sector}}
</label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
And here's the JS I'm using to push the data onto the form:
function createService(service) {
$scope.services.push(service);
}
$scope.createService = createService;
The name seems to get added to the list of services, but the sectors do not. Can anyone point me in the right direction, or explain what I might be doing wrong.
Any help is appreciated. Thanks in advance!
Problem
I'm not a programmer and I'm trying to do some programming.
I tried to use jQuery-validate plug-in to control the form input, it works perfectly, Bootstrap can even find the ".text-danger" class and change its' color.
However, the ".hasClass()" method just can't.
I put some "console.log()" functions in the for loops which are used to find this class.
The log messages I received every time are "changed", "hasSmall", "noClass".
Have I made mistakes in the JS code?
Please help me out.
Code
This is within my HTML form:
<div class="form-group">
<label for="username">Username </label>
<input type="text" class="form-control" name="username" id="signUpUserName" />
</div>
<div class="form-group">
<label for="password">Password </label>
<input type="password" class="form-control" name="password" id="signUpPassword" />
</div>
<div class="form-group">
<label for="email">Email </label>
<input type="text" class="form-control" name="email" id="signUpEmail" />
</div>
This is the JavaScript:
errorPlacement: function(error, element) {
var obj = $('[name="'+element.attr('name')+'"]');
obj.siblings('label').append(error);
},
I have changed some values in the valadate.min.js:
$.extend($.validator, {
defaults: {
messages: {},
groups: {},
rules: {},
errorClass: "text-danger", // I've changed this
validClass: "text-success", // this
errorElement: "small", // and this
focusInvalid: true,
errorContainer: $([]),
errorLabelContainer: $([]),
onsubmit: true,
ignore: ":hidden",
ignoreTitle: false,
Also, JS:
function changeInputAreaStatus(id) {
$(id).change(function(id) {
console.log('changed');
var errorMessageContainer = $(id).siblings('label');
if(errorMessageContainer.has('small')){
console.log('hasSmall');
if (errorMessageContainer.children('small').hasClass('text-danger')) {
console.log('hasDangerClass');
errorMessageContainer.parent().removeClass('has-error').addClass('has-error');
} else if (errorMessageContainer.children('small').hasClass('text-success')) {
console.log('hasSucessClass');
errorMessageContainer.parent().removeClass('has-error');
} else {
console.log('noClass');
}
}
});
}
changeInputAreaStatus('#signUpUserName');
changeInputAreaStatus('#signUpPassword');
changeInputAreaStatus('#signUpEmail');
You should try something like this :
var textSuccess = errorMessageContainer.find('.text-success');
if(textSuccess != null && textSuccess.length > 0){
console.log('hasSucessClass');
}
it should help you to verify if errorMessageContainer has a text-success class.
Best regards
This is my html
<div><center><b class="cust_heading">ONLINE FREIGHT QUOTES</b><br>
Instant prices with multiple carriers</center>
</div>
<div class="field_heading"><b>Shipment type* </b><span id="shipmentError" class="cust_error"></span></div>
<div class="fiftyPercent">
<input type="radio" name="shipment" value="export"> Export
</div>
<div class="fiftyPercent">
<input type="radio" name="shipment" value="import"> Import
</div>
<div class="field_heading"><b>Load type* </b><span id="loadError" class="cust_error"></span></div>
<div class="fiftyPercent">
<input type="radio" name="load" value="fcl"> FCL
</div>
<div class="fiftyPercent">
<input type="radio" name="load" value="lcl"> LCL
</div>
<div style="display:none; width:100%;" id="weight_volume_row">
<div class="fiftyPercent">
Weight (kg)*<span id="lcl_weightError" class="cust_error"></span><br><input type="text" name="lcl_weight" id="lcl_weight" value="" placeholder="e.g 100" style=" width:70%;">
</div>
<div class="fiftyPercent">
Volume (m<sup>3</sup>)*<span id="lcl_volumeError" class="cust_error"></span><br><input type="text" name="lcl_volume" id="lcl_volume" placeholder="e.g 1" value="" style=" width:70%;">
</div>
</div>
<div class="field_heading"><b id="cust_include_text">Include pickup* </b><span id="pickupError" class="cust_error"></span></div>
<div class="fiftyPercent">
<input type="radio" name="pickup" value="yes"> Yes
</div>
<div class="fiftyPercent">
<input type="radio" name="pickup" value="no"> No
</div>
<div class="field_heading"><b id="cust_zipcode_text">Pickup zip code* </b></div>
<div style="width:100%;">
<input id="pickupZipCode" placeholder="Enter a city or zip code" title="pickupZipCode" type="text" class="ui-autocomplete-input" autocomplete="off" role="textbox" aria-autocomplete="list" style=" width:85%;"><input type="hidden" name="postal_hid_data" id="postal_hid_data" value="">
<select name="choosePort" id="choosePort" style=" width:85%; display:none;"><option disabled="disabled" selected="selected" value="">Choose a port</option><option value="test1">test1</option><option value="test2">test2</option><option value="test3">test3</option></select>
<select name="choosePortOther" id="choosePortOther" style=" width:85%; display:none;"><option value="">Choose a port</option><option value="test4">test4</option><option value="test5">test5</option><option value="test6">test6</option></select>
<span id="zipError" class="cust_error"></span>
</div>
<div class="field_heading"><b id="cust_dest_text">Port of destination* </b></div>
<div style="width:100%;padding:5px 0px;">
<input id="destPort" placeholder="Enter a port or country" title="portDestination" type="text" class="ui-autocomplete-input" autocomplete="off" role="textbox" aria-autocomplete="list" style=" width:85%;"><input type="hidden" name="des_hid_data" id="des_hid_data" value="">
<span id="desError" class="cust_error"></span>
</div>
<div style="width:90%; float:left;padding:5px 0px;">
<input class="searchButton orange-bttn cust_btn" id="cust_form_submit" name="cust_form_submit" type="submit" value="Buscar Naviera" style="float:right;">
</div>
</div>
and my jquery validate form is lookin like this, what is it im doing wrong. Using the wrong form id?
$(function() {
$('cust_main_box').validate({
rules: {
pickupZipCodeUS: {
required: true
},
destPortUS: {
required: true
},
//lcl_weightForm2US: {
//required: true
//},
//lcl_volumeForm2US: {
//required: true
//},
},
messages: {
pickupZipCodeUS: {
required: 'Please enter a valid zip-code',
},
destPortUS: {
required: 'Please enter a valid port',
},
//lcl_weightForm2US: {
//required: 'Please enter a valid weight',
//},
//lcl_volumeForm2US: {
//required: 'Please enter a valid volume',
//},
}
)};
});
The code that was commented out had to do with another form within the jquery, I'd like to include it whenever i figure out what it is i'm doing wrong.
as #undefined already told you, proably the element should be .cust_main_box or #cust_main_box, but the problem in your code is validate closing:
)};
should be
});
So your correct JS:
$(function() {
$('#cust_main_box').validate({
rules: {
pickupZipCodeUS: {
required: true
},
destPortUS: {
required: true
}
//,lcl_weightForm2US: {
//required: true
//},
//lcl_volumeForm2US: {
//required: true
//},
},
messages: {
pickupZipCodeUS: {
required: 'Please enter a valid zip-code'
},
destPortUS: {
required: 'Please enter a valid port'
}
//,lcl_weightForm2US: {
//required: 'Please enter a valid weight',
//},
//lcl_volumeForm2US: {
//required: 'Please enter a valid volume',
//},
}
});
});
Your major problems:
1) The jQuery Validate plugin requires that all input elements to be validated must have name attributes. Those name attributes must also be where your declared rules are assigned.
<input type="text" name="pickupZipCodeUS" ...
<input type="text" name="destPortUS" ...
2) You are missing a form element. The jQuery Validate plugin can only work when the user input elements are contained within a set of <form></form> tags.
3) $('cust_main_box') is not a valid selector in this context. Give the new <form> element an id="cust_main_box" and change the selector to $('#cust_main_box').
<form id="cust_main_box" ...
4) The closing braces for your .validate() call are reversed. They should be this: }).
$('#cust_main_box').validate({
// rules & options
}); // <-- this here
Working Code:
$(function () {
$('#cust_main_box').validate({
rules: {
pickupZipCodeUS: { // <-- this is the field name
required: true
},
destPortUS: { // <-- this is the field name
required: true
}
},
messages: {
pickupZipCodeUS: {
required: 'Please enter a valid zip-code',
},
destPortUS: {
required: 'Please enter a valid port',
}
}
});
});
Working DEMO: http://jsfiddle.net/fTwsG/
You're using a bunch of invalid and deprecated markup, so you should also put your HTML through the W3C HTML Validation tool.