Getting bootstrap validation to work - html

I'm using bootstrap for my site and I'm busy creating a form. I have some required fields but if I submit my form without filling those fields I don't get a red box around the input field. But if I click on the input box I get the red box.
Here is my html
<li>
<div class="form-group">
<label>* First Name</label>
<div class="registration_firstName has-error">
<input id="firstName" type="text" name="firstName" class="form-control" required>
</div>
</div>
</li>
<button value="" class="registration_submit">Send</button>
Here is my js
$(".registration_submit").click(function(){
var errorMsg = "";
$(".error-success").hide();
$(".has-error").each(function(index, element){
if($.trim($(this).val()) == ""){
errorMsg+= "error";
}
if($(this).attr("id") == "firstName"){
errorMsg+= "error";
}
});
if(errorMsg != ""){
$(".submit").show();
$(".error-success").html("please fill out the required fields.");
$(".error-success").fadeIn(250);
return false;
}
if($.trim(ajaxemail) == "success"){
$(".submit").show();
$(".error-success").html("Thank you. A confirmation email has been sent.");
$(".error-success").fadeIn(250);
$('#email').val("");
}else{
$(".submit").show();
}
});
Here is a jsfiddle: JSFIDDLE

You can use a bootstrap extension for this:
http://1000hz.github.io/bootstrap-validator/
and use it like this:
$('form').validator().on('submit', function (e) {
if (e.isDefaultPrevented()) {
return false;
} else {
return true;
}
});

Related

How to prevent radiobutton loose "focus" when custom jQuery return false?

I have 3 radio buttons with same name (property).
If "Deleted" radio is checked and someone will click "Active" i wish to run custom function which returns true or false. If it fails i want to prevent "Deleted" radio to be unchecked.
Problem is that the radiobutton looses "focus" and the "Active" radio is selected.
I've used code below to prevent this but it seems to be dirty workaround.
Is there better way to prevent "Deleted" radiobutton to be unchecked if custom function return false?
$("#radioActive").on("change", function() {
if (!CustomFunction1()) {
$("#radioUnactive").prop('checked', true);
bootbox.alert('No Pain No Game');
}
});
$("#radioUnactive").on("change", function() {
if ($('#distributor').val() == '1') {
$("#radioActive").prop('checked', true);
bootbox.alert('NO NO NO')
}
if (CustomFunction2()) {
$("#radioActive").prop('checked', true);
bootbox.alert('Distributor has assigned users - cannot be disabled ');
}
});
$("#radioDelete").on("change", function() {
if ($('#distributor').val() == '1') {
$("#radioActive").prop('checked', true);
bootbox.alert('NO NO NO!');
}
if (CustomFunction2()) {
$("#radioActive").prop('checked', true);
bootbox.alert('No Way')
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/5.5.2/bootbox.min.js" integrity="sha512-RdSPYh1WA6BF0RhpisYJVYkOyTzK4HwofJ3Q7ivt/jkpW6Vc8AurL1R+4AUcvn9IwEKAPm/fk7qFZW3OuiUDeg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div class="radio-toolbar">
<input type="radio" id="radioActive" name="Buttons[activeState]" value="active">
<label for="radioActive">Active</label>
<input type="radio" id="radioUnactive" name="Buttons[activeState]" value="unactive">
<label for="radioUnactive">Unactive</label>
<input type="radio" id="radioDelete" name="Buttons[activeState]" value="deleted">
<label for="radioDelete">Deleted</label>
</div>
Instead of writing multiple codes, do it in one go.
A sample example is to first save the previous checked radio button id and then based on some checking inside a function and its return value make a new one checked or make the previous one checked only.
var prevCheckedId = '';
$('input[type=radio]').mouseup(function(){
prevCheckedId = $('input[type=radio]:checked').attr('id');
}).change(function(){
var value = $(this).val();
if(CustomFunction1(value)) {
$(this).prop('checked', true);
}else{
$(this).prop('checked', false);
$('#'+prevCheckedId).prop('checked', true);
}
});
function CustomFunction1(value){
if(value == 'active'){
return false;
}else{
return true;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="radio-toolbar">
<input type="radio" id="radioActive" name="Buttons[activeState]" value="active">
<label for="radioActive">Active</label>
<input type="radio" id="radioUnactive" name="Buttons[activeState]" value="unactive">
<label for="radioUnactive">Unactive</label>
<input type="radio" id="radioDelete" name="Buttons[activeState]" value="deleted">
<label for="radioDelete">Deleted</label>
</div>

JQuery autosubmit

I have a form with three input elements. I want to run my validate function when the last input element is not equal to null. Any ideas please. Here's the code :
$(document).ready(function () {
$("#number input").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).next('#number input').focus();
}
});
})
Here's the HTML :
<div id="number">
<form action="" id="myform">
<input placeholder="hr" maxlength="2" type="number" id="uHrs" pattern="[1-12]" autofocus></input>
<input placeholder="min" maxlength="2" type="number" id="uMins" pattern="[0-59]"></input>
<input placeholder="sec" maxlength="2" type="number" id="uSecs" pattern="[0=50]"></input>
<button type="submit" id="subtime" value="submit" onclick="checkInput()">Submit</button>
</form>
You can try filter, also I use the input event so we can paste. We could even split a too long number and spread it to the next fields if we want to support pasting the complete set of values
Full solution: https://jsfiddle.net/mplungjan/3mbqw80h/
$(function() {
const $inputs = $("#number input"),
$form = $("#number");
$inputs.on("input", function() {
if (this.value.length == this.maxLength) {
const $next = $(this).next('#number input');
if ($next.length) $next.select().focus();
if ($inputs.filter(function() {
return this.value.trim() !== ""
}).length === $inputs.length) {
checkInput();
}
}
});
})

email check and comma separated check jQuery codes work correctly in separation but not when mixed for disabling the submit button

I have to functions that each of them looks for an email being valid and the other one looks for an input being comma separated (not sure if I have the best comma separated jQuery code).
However, when I write a proper comma separated input in the input box, it still allows me to click on the submit button which is strange because the email is empty and I expect the submit button to stay disabled. Each of these two functions work correctly separately.
$("#category_names").on('keyup', function (event) {
$(".error").hide();
let hasError = false;
let isValid = true;
$('#category_names').each(function() {
if (($.trim($(this).val()).indexOf(",") == -1)) {
//alert('Please separate multiple keywords with a comma.');
$('#commaerror').show();
hasError = true;
} else {
$('#commaerror').hide()
hasError = false;
}
});
$('button[type="submit"]').prop('disabled', hasError);
})
$("#email").on('keyup', function() {
$(".error").hide();
let hasError = false;
let emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
let emailAddressVal = $(this).val();
if (emailAddressVal == '') {
$("#email").after('<span class="error">Please enter your email address.</span>');
hasError = true;
}
else if (!emailReg.test(emailAddressVal)) {
$("#email").after('<span class="error">Enter a valid email address.</span>');
hasError = true;
}
$('button[type="submit"]').prop('disabled', hasError);
})
You need to check both (all, if there are other inputs as well) conditions are valid in each event handler. It's probably simplest to put all the validation code into a function and call that in the event handler. For example:
function validate() {
$(".error, #commaerror").hide();
let hasError = false;
// validate category names
$('#category_names').each(function() {
if ($(this).val().indexOf(",") == -1) {
//alert('Please separate multiple keywords with a comma.');
$('#commaerror').show();
hasError = true;
}
});
// validate email
let emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
let emailAddressVal = $('#email').val();
if (emailAddressVal == '') {
$("#email").after('<span class="error">Please enter your email address.</span>');
hasError = true;
}
else if (!emailReg.test(emailAddressVal)) {
$("#email").after('<span class="error">Enter a valid email address.</span>');
hasError = true;
}
return hasError;
}
$("#category_names, #email").on('keyup', function(event) {
$('button[type="submit"]').prop('disabled', validate());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-3">
<label data-error="wrong" data-success="right">Enter your email</label>
<input type="email" class="form-control validate purple-border" id="email">
<br/>
<label>Enter categories:</label>
<input type="text" id="category_names" />
<br/>
</div>
<button type="submit" class="btn btn-purple purple-border" disabled="disabled">Perform Frame Classification</button>
Note I've cleaned up your category_names code a bit, but you need to add further checking so that if there is only one value it still passes, or that something like abc, doesn't pass. You might find something like
$(this).val().match(/^\s*\w+(\s*,\s*\w+)*\s*$/)
more useful.

Ng-hide doesn't work when using <div> tags together

I am trying to hide radio buttons using ng-hide functions. I am facing a strange problem.
When I use both ng-hide supplierAdminLogs and BuyerAdminLogs in div tags like shown in the html code below, both my radio buttons gets hidden instead of just one of them.
But when I remove one of the ng-hide in div tag, the other ng-hide div tag works perfectly by hiding the radio button. Thanks in advance.
$scope.supplierAdminLogs = function() { // Hiding supplier/ buyer radio buttons on current user login role.
return true;
};
$scope.buyerAdminLogs = function() {
return true;
};
$scope.adminRole = function() {
var currentUser;
if (localStorage.getItem("currentUser") !== null) {
currentUser = JSON.parse(localStorage.getItem("currentUser"));
console.log("Received", currentUser);
} else {
console.log("Not received");
}
if (currentUser[0].role == "Supplier-Admin") {
$scope.newUser.company = currentUser[0].company;
$scope.supplierAdminLogs(); //CALLING THE FUNCTION HERE
return false;
} else if (currentUser[0].role == "Buyer-Admin") {
$scope.newUser.company = currentUser[0].company;
$scope.buyerAdminLogs(); //CALLING THE FUNCTION HERE
return false;
}
};
<div class="form-group">
<label class="control-label col-sm-2">Role</label>
<div>
<div ng-hide="buyerAdminLogs()">
<input type="radio" name="addRole"
ng-model="newUser.role"
ng-required="true" value="Supplier-Admin">
Supplier-Admin <br />
</div>
<div ng-hide="supplierAdminLogs()">
<input type="radio" name="addRole"
ng-model="newUser.role"
ng-required="true" value="Buyer-Admin">
Buyer-Admin <br />
</div>
</div>
</div>
You can try with checkbox validation like here:
$scope.user = function(type){
if(type === 'Supplier-Admin'){
$scope.buyerAdminLogs = false;
} else if (type === 'Buyer-Admin'){
$scope.supplierAdminLogs = false;
}
console.log(type)
}
html:
<div >
<input type="checkbox"
ng-click="user('Supplier-Admin');supplierAdminLogs = true"
ng-model="supplierAdminLogs"
ng-required="true" ng-value="Supplier-Admin">
Supplier-Admin <br />
</div>
<div >
<input type="checkbox"
ng-click="user('Buyer-Admin');buyerAdminLogs = true"
ng-model="buyerAdminLogs"
ng-required="true" ng-value="Buyer-Admin">
Buyer-Admin <br />
</div>
</div>
</div>
<div ng-if="buyerAdminLogs">buyerAdminLogs</div>
<div ng-if="supplierAdminLogs">supplierAdminLogs</div>

Placeholder doesn't show

Guys I've read everything here about that topic already, but I still can't figure out why my Placeholder is not showing up. Hope you can share your expertise and tell what I'm doing wrong.
<input type="text" name="search" class="input-block-level search-query" placeholder="Enter your name" required="">
It's just not showing up in any browser. Thanks is advance!
You can try use this code to your placeholder show on this input.
$(document).ready(function() {
function add() {if($(this).val() == ''){$(this).val($(this).attr('placeholder')).addClass('placeholder');}}
function remove() {if($(this).val() == $(this).attr('placeholder')){$(this).val('').removeClass('placeholder');}}
if (!('placeholder' in $('<input>')[0])) {
$('input[placeholder]').blur(add).focus(remove).each(add);
$('div').submit(function(){$(this).find('input[placeholder]').each(remove);});
}
});
<div>
<input type="text" name="search" class="input-block-level search-query" placeholder="Enter your name" required>
</div>
I found this link which will give us a good idea about how we fix placeholder problem it will use jquery and it will be a good solution.
http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html
And here is the full jquery code
// Released under MIT license: http://www.opensource.org/licenses/mit-license.php
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder'); }
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur().parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});