I'm trying to latch onto a checkbox change event using jQuery, currently I have this:
<script type="text/javascript">
$(document).ready(function () {
$('.timepicker').datetimepicker({ datepicker: false, format: 'H:i' });
$('.mondaystartfinish').hide();
//subscribe to change events
$('#IsMonday').change(function () {
RunsOnMondays();
});
});
function RunsOnMondays() {
if ($('#IsMonday').prop('checked') == 'true') {
$('.mondaystartfinish').slideDown();
} else {
$('.mondaystartfinish').slideUp();
}
}
</script>
However in debug when I check/uncheck the box the RunsOnMondays() method is not firing.
I have tried using this also but still didn't work:
$('IsMonday').prop('checked').change(function () { RunsOnMondays();});
Browser output
<div class="form-group">
<label class="control-label col-md-2" for="IsMonday">Monday</label>
<div class="col-md-10">
<input class="check-box" data-val="true" data-val-required="The IsMonday field is required." id="IsMonday" name="IsMonday" type="checkbox" value="true" /><input name="IsMonday" type="hidden" value="false" />
<span class="field-validation-valid" data-valmsg-for="IsMonday" data-valmsg-replace="true"></span>
</div>
</div>
<div class="startfinish">
<div class="form-group">
<div class="mondaystartfinish">
<label class="control-label col-md-2" for="MondayFrom">Monday Start</label>
<div class="col-md-10">
<input class="timepicker" data-val="true" data-val-date="The field MondayFrom must be a date." id="MondayFrom" name="MondayFrom" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="MondayFrom" data-valmsg-replace="true"></span>
</div>
</div>
</div>
</div>
<div class="startfinish">
<div class="form-group">
<div class="mondaystartfinish">
<label class="control-label col-md-2" for="MondayTo">Monday Finish</label>
<div class="col-md-10">
<input class="timepicker" data-val="true" data-val-date="The field MondayTo must be a date." id="MondayTo" name="MondayTo" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="MondayTo" data-valmsg-replace="true"></span>
</div>
</div>
</div>
</div>
The reason it does not work is that this is not true true == 'true' is actually false: http://jsfiddle.net/TrueBlueAussie/2wwz1ore/6/
prop('checked') returns a boolean value! No need for == 'true'.
http://jsfiddle.net/TrueBlueAussie/2wwz1ore/1/
$(document).ready(function () {
//$('.timepicker').datetimepicker({ datepicker: false, format: 'H:i' });
$('.mondaystartfinish').hide();
// subscribe to change events
$('#IsMonday').change(function () {
RunsOnMondays();
});
});
function RunsOnMondays() {
if ($('#IsMonday').prop('checked')) {
$('.mondaystartfinish').slideDown();
} else {
$('.mondaystartfinish').slideUp();
}
}
Better yet, use slideToggle(): http://jsfiddle.net/TrueBlueAussie/2wwz1ore/3/
// subscribe to change events
$('#IsMonday').change(function () {
$('.mondaystartfinish').slideToggle($(this).prop('checked'));
});
If (and I very much doubt it) your element is added dynamically, use a delegated event handler attached to a non-change ancestor element (document is the default if nothing else is closer/convenient)
e.g.
$(document).on('click' , '#IsMonday', function () {
$('.mondaystartfinish').slideToggle($(this).prop('checked'));
});
You could use the below as follows:
$('#IsMonday').change(function(){
RunsOnMondays(this.checked);
});
function RunsOnMondays(isChecked) {
if (isChecked) {
$('.mondaystartfinish').slideDown();
} else {
$('.mondaystartfinish').slideUp();
}
}
jsFiddle
Related
There is an input which is Date Picker.
It is impossible to type in the input, everybody can only pick a date by mouse.
enter image description here
How can I call an event when the user changes Date ?
Here is HTML Code:
<div class="col-lg-3 col-md-3 col-xs-12">
<label for="homeWorkStartDate">From: </label>
<input type="text" id="homeWorkStartDate" class="pdate form-control" />
<input type="hidden" id="txtHomeWorkStartDate" />
<script>
var objCal1 = new AMIB.persianCalendar('homeWorkStartDate', {
extraInputID: 'txtHomeWorkStartDate',
extraInputFormat: 'YYYY-MM-DD'
});
</script>
</div>
<div class="col-lg-3 col-md-3 col-xs-12">
<label for="homeWorkEndDate">To: </label>
<input type="text" id="homeWorkEndDate" class="pdate form-control" />
<input type="hidden" id="txtHomeWorkEndDate" />
<script>
var objCal1 = new AMIB.persianCalendar('homeWorkEndDate', {
extraInputID: 'txtHomeWorkEndDate',
extraInputFormat: 'YYYY-MM-DD'
});
</script>
</div>
Here is what I tried but doesn't work:
$("#homeWorkStartDate,#homeWorkEndDate").on('input propertychange',function(){
alert("hi");
});
Did you try something like this ?
$( "#datepicker" ).datepicker({
onSelect: function () {
alert('hello');
}
})
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 need some help. I am trying to load my javascript file and listing to changing on checkbook when I click my checkbox to show or hide password. But for some reason it is not working. I have try everything, but out of ideas how to solve the problem.
$(document).ready(function () {
$('#showPassword').on('click', function () {
if ($(this).prop('checked')) {
$('#password').attr('type', 'text')
} else {
$('#password').attr('type', 'password')
}
})
<template>
<div class="container-fluid p-0">
<div class="col-md-12 content">
<div class="col-md-6 join-container" id="join-container">
<form class="col-md-12 col-sm-12"
>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control"
id="password" v-model="password"
placeholder="Password">
</div>
<div class="form-group pl-0">
<div class="form-check">
<input class="form-check-input" type="checkbox"
id="showPassword" />
<label class="form-check-label"
for="show-password">Show Password</label>
</div>
</div>
<br>
</form>
</div>
</div>
</template>
<script>
import Main from '../script/Index.js'
export default {
name: 'Register',
data: () => ({
}),
methods: {
},
components: {
Main
}
}
</script>
You're using jQuery event handlers (the $ bit) outside a script tag in a Vue component file. I wouldn't expect that code to do anything.
If you wanted that code to execute, you'd need it to be inside the <script> tags in your component. However, Vue already has event listeners (link to documentation), including listening for clicks on elements. There is no need to use two frameworks for this.
To implement a rough show password button (using your existing markup), here's how I'd do it (removing extra markup to highlight the important Vue-logic):
<template>
<div>
<input :type="passwordType" v-model="password">
<input v-model="showPassword" type="checkbox"/>
</div>
</template>
<script>
export default {
data() {
return {
showPassword: false,
password: ''
}
},
computed: {
passwordType() {
if (this.showPassword) {
return 'text'
} else {
return 'password'
}
}
}
}
</script>
It's not advisable to mix jQuery and Vue since they have separate lifecycles.
Vue is able to do everything you're after by itself.
Simply bind your checkbox state to a Vue data property and use that to determine the password field's type, eg
<input :type="passwordFieldType" class="form-control"
id="password" v-model="password"
placeholder="Password">
<!-- snip -->
<input v-model="passwordFieldType" true-value="text" false-value="password"
class="form-check-input" type="checkbox"
id="showPassword">
data: () => ({
passwordFieldType: 'password'
})
See https://v2.vuejs.org/v2/guide/forms.html#Checkbox-1
new Vue({
el: '#app',
data: () => ({
password: '',
passwordFieldType: 'password'
})
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<form class="col-md-12 col-sm-12" id="app">
<div class="form-group">
<label for="password">Password</label>
<input :type="passwordFieldType" class="form-control" id="password" v-model="password" placeholder="Password">
</div>
<div class="form-group pl-0">
<div class="form-check">
<input v-model="passwordFieldType" true-value="text" false-value="password"
class="form-check-input" type="checkbox" id="showPassword" />
<label class="form-check-label" for="show-password">Show Password</label>
</div>
</div>
<br>
</form>
I'm new to jQuery and Bootstrap, I'm using jquery and Bootstrap 4 for validation of my form modal, whenever there is an error it must show the error below the corresponding fields, but in my case the select field gets overwritten by the error and select field disappears but it works fine for input field.
here have a look and if you want to have a close look on image just click on it..
As you can see the select fields get overwritten by the fieldError but it's fine for input field.
here's my jQuery validation code:
$(function(){
setCategorySelect();
$(document).on('shown.bs.modal','#manageItemsModal', function () {
$('#manageItemsModal #btnSubmit').on('click', function(){
if (validateForm()) {
messageSuccess("Very well");
} else {
messageError("Oops!!");
}
});
});
});
function validateForm() {
var validationStatus = true;
if ($('#manageItemsForm #selectedCategory').val().length == 0) {
showFieldError(('#manageItemsForm #selectedCategory'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #selectedCategory').focus() };
validationStatus = false;
}
if ($('#manageItemsForm #selectedBrandModel').val().length == 0) {
showFieldError(('#manageItemsForm #selectedBrandModel'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #selectedBrandModel').focus() };
validationStatus = false;
}
if ($('#manageItemsForm #serialNo').val().length == 0) {
showFieldError(('#manageItemsForm #serialNo'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #serialNo').focus() };
validationStatus = false;
}
if ($('#manageItemsForm #selectedVendor').val().length == 0) {
showFieldError(('#manageItemsForm #selectedVendor'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #selectedVendor').focus() };
validationStatus = false;
}
if ($('#manageItemsForm #selectedBranch').val().length == 0) {
showFieldError(('#manageItemsForm #selectedBranch'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #selectedBranch').focus() };
validationStatus = false;
}
return validationStatus;
}
function showFieldError(element, message) {
$(element).addClass('is-invalid');
$(element).next().html(message);
$(element).next().show();
}
function clearFieldError(element) {
$(element).removeClass('is-invalid');
$(element).removeAttr('required');
$(element).next().html('');
}
function setCategorySelect() {
var $categorySelect = $('#manageItemsForm #selectedCategory').selectize({
selectOnTab: true,
closeAfterSelect: true,
persist: false,
create: false,
valueField: 'id',
labelField: 'text',
options: [],
preload: true,
onInitialize : function() {
var self = this;
$.ajax({
url: '/assetCategory/search',
type: 'POST',
dataType: 'json',
data: {
searchText: '*'
},
error: function() {
callback();
},
success: function(res) {
self.addOption(res.data);
}
});
},
load: function(query, callback) {
if (query.length <= 2) return callback();
$.ajax({
url: '/assetCategory/search',
type: 'POST',
dataType: 'json',
data: {
searchText: query + "*"
},
error: function() {
callback();
},
success: function(res) {
console.log(res.data);
callback(res.data);
$categorySelect.refreshItems();
},
fail : function() {
callback();
}
});
}
});
}
here's my HTML:
<div class="modal-body">
<form id="manageItemsForm">
<input type="hidden" id="id" name="id">
<div class="row">
<div class="col-4">
<div class="form-group">
<label for="selectedCategory" class="col-form-label"><span class="text-danger">* </span>Category</label>
<select class="form-control" name="selectedCategory" id="selectedCategory"></select>
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-8">
<div class="form-group">
<label for="selectedBrandModel" class="col-form-label"><span class="text-danger">* </span>Brand & Model</label>
<select class="form-control" name="selectedBrandModel" id="selectedBrandModel"></select>
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-4">
<div class="form-group">
<label for="serialNo" class="col-form-label"><span class="text-danger">* </span>Serial No.</label>
<input type="text" class="form-control" id="serialNo" name="serialNo">
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-8">
<div class="form-group">
<label for="description" class="col-form-label">Description</label>
<input type="text" class="form-control" id="description" name="description">
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-6">
<div class="form-group">
<label for="selectedVendor" class="col-form-label"><span class="text-danger">* </span>Purchase Vendor</label>
<select class="form-control" name="selectedVendor" id="selectedVendor"></select>
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="selectedVendor" class="col-form-label"><span class="text-danger">* </span>Purchase Date</label>
<div class="input-group date" data-date-format="dd-M-yyyy">
<input type="text" class="form-control" id="purchaseDate" name="purchaseDate" />
<span class="input-group-text input-group-append input-group-addon"><i class="simple-icon-calendar"></i></span>
</div>
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="supportTillDate" class="col-form-label"><span class="text-danger">* </span>Support till date</label>
<div class="input-group date" data-date-format="dd-M-yyyy">
<input type="text" class="form-control" id="supportTillDate" name="supportTillDate" />
<span class="input-group-text input-group-append input-group-addon"><i class="simple-icon-calendar"></i></span>
</div>
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-9">
<div class="form-group">
<label for="selectedBranch" class="col-form-label"><span class="text-danger">* </span>Branch</label>
<select class="form-control" name="selectedBranch" id="selectedBranch"></select>
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-3">
<label for="purchasePrice" class="col-form-label">Purchase Price</label>
<div class="input-group">
<div class="input-group-prepend"><span class="input-group-text input-group-addon" style="padding: 0.4rem 0.75rem 0.3rem 0.75rem;">₹</span></div>
<input id="purchasePrice" name="purchasePrice" type="text" class="form-control" aria-label="Amount" style="text-align:right;">
</div>
<div class="invalid-feedback"></div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button id="btnSubmit" type="button" class="btn btn-primary">Save</button>
</div>
</div>
By the way I am using jQuery in Spring boot and everything is working fine(save, update, delete) except for validation from jQuery.
Please help!!
I can't see working code because you using some external references like selectize.
I suggest you get used to "snippets" to provide code.
Bytheway, your problem seems to be just about styles. I can't know, but my bet is you just need to provide a css style for
.select::after.error {
color:red;
}
You can inspect and copy CSS code.
The problem is in Your HTML, the nodes of your .input-group does not have allways the same structure. In some cases you have .invalid-feedback just after the input such as this HTML
<div class="form-group">
<label for="serialNo" class="col-form-label"><span class="text-danger">*
</span>Serial No.</label>
<input type="text" class="form-control" id="serialNo" name="serialNo">
<div class="invalid-feedback"></div>
</div>
For other fields the .invalid-feedback isn't after the input but outside from .form-group. take a look
<div class="input-group date" data-date-format="dd-M-yyyy">
<input type="text" class="form-control" id="purchaseDate" name="purchaseDate" />
<span class="input-group-text input-group-append input-group-addon">
<i class="simple-icon-calendar"></i>
</span>
</div>
<div class="invalid-feedback"></div>
This difference in HTML structure of the form made your showFieldError() and clearFieldError() not working allways as you expected, because $(element).next() don't catch the right DOM node for insert/remove the validation message. So in some cases clearFieldError remove the wrong HTML tag and this can make your selects disappear
function showFieldError(element, message) {
$(element).addClass('is-invalid');
$(element).next().html(message);
$(element).next().show();
}
function clearFieldError(element) {
$(element).removeClass('is-invalid');
$(element).removeAttr('required');
$(element).next().html('');
}
So you have to fix Your HTML to obtain the same structure for all fields. Put the <div class="invalid-feedback"></div> allways just below the select or input field. Otherwise you have to change the selector that you pass to showFieldError() and clearFieldError() functions according to your HTML
Otherwise a simply approach is to add a ID to divs with class .invalid-feedback, an ID which you can easily manage by his related input ID, something like
<div class="input-group date" data-date-format="dd-M-yyyy">
<input type="text" class="form-control" id="purchaseDate" name="purchaseDate" />
<span class="input-group-text input-group-append input-group-addon">
<i class="simple-icon-calendar"></i>
</span>
</div>
<div id="purchaseDate_err_mex" class="invalid-feedback"></div>
in this way you can pass the input name to your functions and them becomes
function showFieldError(input_id, message) {
$('#'+input_id).addClass('is-invalid');
$('#'+ input_id +'_err_mex').html(message).show();
}
function clearFieldError(input_id) {
$('#'+input_id).removeClass('is-invalid');
//$('#'+input_id).removeAttr('required');
/* don't need to remove required attribute from mandatory fields */
$('#'+ input_name +'_err_mex').html('').hide();
}
and the validation function
function validateForm() {
var validationStatus = true;
if ($('#selectedCategory').val().length == 0) {
showFieldError('selectedCategory', 'Must not be blank');
if (validationStatus) { $('#selectedCategory').focus() };
validationStatus = false;
}
........
return validationStatus;
}
You only check if the length of all fields is more than 0, so you can validate the entire form within a loop
function validateForm() {
var validationStatus = true;
var form_inputs = $('#manageItemsForm input, #manageItemsForm select')
$.each(form_inputs,function(){
var input_id = $(this).attr('name');
clearFieldError(input_id);
if ($.trim($(this).val()).length == 0 && $(this).is("[required]")) {
showFieldError(input_id, 'Must not be blank');
if (validationStatus) { $('#'+input_id).focus() };
validationStatus = false;
}
});
return validationStatus;
}
Here is my Fiddle
Here is the html
<form action='includes/pgd_cc.php' METHOD='POST' id="ccSelectForm">
<div class="control-group">
<label class="control-label" for="inputEmail"><strong>Email Address</strong>
</label>
<div class="controls">
<input type="text" name="inputEmail" placeholder="jane.smith#email.com" id="inputEmail" />
</div>
<label class="control-label" for="inputEmailConfirm"><strong>Confirm Email Address</strong>
</label>
<div class="controls">
<input type="text" name="inputEmailConfirm" placeholder="jane.smith#email.com" id="inputEmailConfirm" />
</div>
</div>
<button type="submit" id="emailSubmit" disabled="disabled" class="btn btn-danger" data-toggle="tooltip" data-placement="bottom" title="Click me to buy">Credit Card Checkout »</button>
Here is the script
$(document).ready(function () {
$('#ccSelectForm').validate({
rules: {
inputEmail: {
required: true,
email: true
},
inputEmailConfirm: {
equalTo: '#inputEmail'
}
}
});
$('#ccSelectForm input').on('keyup blur', function () {
if ($('#ccSelectForm').valid()) {
$('button.btn').prop('disabled', false);
} else {
$('button.btn').prop('disabled', 'disabled');
}
});
});
As i am doing
$('#ccSelectForm input').on('keyup blur', function () {
if ($('#ccSelectForm').valid()) {
$('button.btn').prop('disabled', false);
} else {
$('button.btn').prop('disabled', 'disabled');
}
});
My Form is always getting validated and showing errors.
I don't want to show the errors in the form while the user type a single word itself.
I want to show errors only after going to next field and it should only validate the current field is typed.
How can i alter this code to achieve this..
It is better to bind it to the submit. So that, it validates everything only once, and not every time for every input, when the keyup is fired. Try this:
$('#emailSubmit').on('click', function () {
return $('#ccSelectForm').valid();
});
Fiddle: http://output.jsbin.com/valiwetese