I need to validate that both the text input, .search-results div within the "Current Images" fieldset and dropdown selection are all not empty. I have the logic for the text input and dropdown working, but can't figure out why the empty div logic is not working:
<div class="input-group col-md-6">
<input type="text" class="form-control" placeholder="Search by Asset ID" maxlength="64" class="form-control" id="imageid" name="imageid"> <span class="input-group-btn">
<button class="btn btn-default image-search" type="button">Search</button>
</span>
</div>
<fieldset class="scheduler-border">
<legend class="scheduler-border">Current Images</legend>
<div class="scheduler-broder">
<div class="search-results"></div>
</div>
</fieldset>
</div>
<div class="form-group">
<label for="image">Select Asset Type:</label>
<select id='crop' class="btn btn-default" data-toggle="dropdown">
<option value="default">Choose Type</option>
<option value="now">Now</option>
<option value="livefeeds">Live Feeds</option>
</select>
</div>
<div class="form-group">
<label for="imageid">Select an image</label>
<input type="file" name="file" class="btn btn-default form-control" id="file" accept="image/jpg, image/png, image/jpeg" />
</div>
function checkForInputs() {
var filledUp = $("#imageid").val() != '' && $("#crop").val() != "default" && $(".search-results").val() != '';
if (!filledUp) {
$("#file").attr("disabled", true);
} else if (filledUp) {
$("#file").attr("disabled", false);
}
}
$("#imageid").keyup(function () {
checkForInputs();
});
$("#crop").change(function () {
checkForInputs();
});
checkForInputs();
JSfiddle: link
Use $(".search-results").text() instead of $(".search-results").val()
Do the same for all the elements that don't belong to a form, like div, span, p, etc.
Take a look at the doc: http://api.jquery.com/val/
Method .val() as it described on jquery website:
Get the current value of the first element in the set of matched elements or set the value of every matched element.
You should use .text() instead of .val()
In this case your validation should be
var filledUp = $("#imageid").val() != '' && $("#crop").val() != "default" && $(".search-results").text() != '';
So this jsfiddle is working
you can use
if($('#mydiv').html().length() == 0)
{
//do something
}
this is for compare with empty value
other way to do this task is compare with function "children", example.
if($('.search-results').children.length == 0)
{
// dosomething
}
good luck !
Related
I am trying to render a form for each person that I get based on a specific input from the database.
#forelse($driverNames as $driver)
<form id="inspection_report_form" enctype="multipart/form-data" action="/inspection-report/store" method="POST">
#csrf
I am trying to hide some fileds if no is selected from dropdown.
<div class="row">
<div class="col-lg-2">
<div class="form-group">
<label>Equipment</label>
<div class="input-group mb-3">
<select class="custom-select" id="branded_equipment" name="branded_equipment" required>
<option value="">Select</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
</div>
</div>
<script>
let branded_equipment = document.getElementById('branded_equipment');
branded_equipment.addEventListener('change', function () {
if (branded_equipment.value === 'no') {
document.getElementById('branded_equipment_picture').required = false;
document.getElementById('branded_equipment_picture').disabled = true;
document.getElementById('branded_equipment_picture').style.display = 'none';
document.getElementById('branded_equipment_picture_label').style.display = 'none';
} else {
document.getElementById('branded_equipment_picture').required = true;
document.getElementById('branded_equipment_picture').disabled = false;
document.getElementById('branded_equipment_picture').style.display = 'block';
document.getElementById('branded_equipment_picture_label').style.display = 'block';
}
});
</script>
The problem that I am facing is that it works only for the first form in the list , if i am clicking on the next person form on the same dropdown id does nothing.
Same with the spinner
>! html
<div class="float-right">
{{--loader--}}
<button class="btn btn-primary" type="button" style="display: none" disabled id="spinner">
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
Loading ...
</button>
<button class="btn btn-success" id="report_submit_btn">Save</button>
</div>
>! javascript
let report_submit_btn = document.getElementById('report_submit_btn');
report_submit_btn.addEventListener('click', function () {
report_submit_btn.style.display = 'none';
document.getElementById('spinner').style.display = 'block';
});
I am assuming that because of the form is generated multiple times and the dropdown is having the same id for each iteration it does not know how to make the difference after the first form.
Much appreciated if anyone can help.
I have tryied using multiple selectors or techniques but nothing works. I am wondering if is achievable what I am trying to do or I should try something different.
I am calling onchange event on form but when I checked in console values are coming in Nan
HTML
<form onchange="calculateHSA(event)">
<div class="col-sm-4">
<input type="number" name="claim-amnt" id="claim-amnt" required="">
</div>
<div class="col-sm-4">
<input type="number" name="admin-percent" id="admin-percent" required="">
</div>
<div class="col-sm-4">
<span class="dataText">Select your province
</span><br>
<select name="province" id="province">
<option value="abc">ABC</option>
</select>
</div>
</form>
JavaScript
function calculateHSA(e) {
e.preventDefault();
const claimAmount = parseInt($(e.target).find('#claim-amnt').val());
console.log(claimAmount);
const adminPercent = parseInt($(e.target).find('#admin-percent').val());
console.log(adminPercent);
const province = $(e.target).find('#province').val();
console.log(province);
displayTaxDetails(claimAmount, adminPercent, province);
}
Where I did wrong code?
Please use e.currentTarget instead of e.target because e.target can be your text fields but e.currentTarget will always be your form. This code is working fine.
<form onchange="calculateHSA(event)">
<div class="col-sm-4">
<input type="number" name="claim-amnt" id="claim-amnt" required="">
</div>
<div class="col-sm-4">
<input type="number" name="admin-percent" id="admin-percent" required="">
</div>
<div class="col-sm-4">
<span class="dataText">Select your province
</span><br>
<select name="province" id="province">
<option value="abc">ABC</option>
</select>
</div>
</form>
<script>
function calculateHSA(e) {
e.preventDefault();
const claimAmount = parseInt($(e.currentTarget).find('#claim-amnt').val());
console.log(claimAmount);
const adminPercent = parseInt($(e.currentTarget).find('#admin-percent').val());
console.log(adminPercent);
const province = $(e.currentTarget).find('#province').val();
console.log(province);
displayTaxDetails(claimAmount, adminPercent, province);
}
</script>
There's no need to use e.target in your example. You can just access the values from the selectors directly:
function calculateHSA(e) {
e.preventDefault();
const claimAmount = parseInt($('#claim-amnt').val());
console.log(claimAmount);
const adminPercent = parseInt($('#admin-percent').val());
console.log(adminPercent);
const province = parseInt($('#province').val());
console.log(province);
displayTaxDetails(claimAmount, adminPercent, province);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onchange="calculateHSA(event)">
<div class="col-sm-4">
<input type="number" name="claim-amnt" id="claim-amnt" required="">
</div>
<div class="col-sm-4">
<input type="number" name="admin-percent" id="admin-percent" required="">
</div>
<div class="col-sm-4">
<span class="dataText">Select your province
</span><br>
<select name="province" id="province">
<option value="abc">ABC</option>
</select>
</div>
</form>
Note that you will get NaN in the console for any field that doesn't have a value that can be parsed as an integer. So if you leave the field blank, you're still going to get NaN in the console.
You are getting NaN because your target element is pointing to the input tag instead of form element
I have made some changes in the function and added new line in the code
function calculateHSA(e) {
e.preventDefault();
var form = $(e.target).parent().parent(); // <-- get the form element
const claimAmount = form.find('#claim-amnt').val();
console.log(claimAmount);
const adminPercent = form.find('#admin-percent').val();
console.log(adminPercent);
const province = form.find('#province').val();
console.log(province);
displayTaxDetails(claimAmount, adminPercent, province);
}
have a look at this plunker https://plnkr.co/edit/BQ538zbYBk857zT1wAgT
I have a form and when the user clicks submit, I would like the form to hide and a thank you message to appear. Unfortunately with the code I have, it's not working and I can't figure out why. I think it might be something with the jQuery so I'd like to try and re-write this function using vanilla JS, but I'm not sure how.
It is the last part of the function, the if (empty.length), hide form, show thank you message that is causing me problems. Everything else is working fine, so its this function I would like to try and write in JavaScript, or try another way using jquery to make it work. The problem is it doesn't work in my code, but when I open this in a jsfiddle, it doesnt just hide the form it opens a new page and I get an error. I don't want the user to be directed to a new page, I just want the form to close and thank-you message to appear. I am very new to this so I apologize if my code is messy.
UPDATE: I really think the issue here is the jQuery, can I write this in plain JS and would that fix it?
var $subscribe = $('#click-subscribe');
var $subscribeContent = $('#subscribe-content');
var $subscribeClose = $('#subscription-close');
$subscribeContent.hide();
$subscribe.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
$subscribeClose.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
})
var $form = $('#signup-form'),
$signupForm = $('.form-show'),
$formReplace = $('#thank-you');
$formReplace.hide();
$form.on('submit', function() {
var empty = $(this).find("input, select, textarea").filter(function() {
return this.value === "";
});
if (empty.length <= 0) {
$signupForm.hide();
$formReplace.show();
} else {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click-subscribe">Show / hide form</button>
<div id="subscribe-content">
<div class="subscription-signup">
<div class="subscription-close" id="subscription-close"></div>
<div class="email-signup">
<p class="cat-title subscription-text">lorem ipsum</p>
<p class="subscription-text">lorem ipsum</p>
<p class="subscription-text">lorem ipsum</p>
<div class="subscription-form">
<form id="signup-form" class="form-show" name="signup-form" method="post" action="${URLUtils.url('Newsletter-SubscribeMobile')}">
<div class="form-row salutation header">
<label for="salutation">Title</label>
<div class="chzn-row valid salutation">
<select id="title" name="title" class="chzn-global-select input-select optional required">
<option value="">--</option>
<option value="Mr">Mr.</option>
<option value="Mrs">Mrs.</option>
<option value="Ms">Ms.</option>
<option value="Miss">Miss</option>
</select>
</div>
</div>
<div class="form-row required">
<label for="firstname">
<span aria-required="true">First Name</span>
<span class="required-indicator">*</span>
</label>
<input class="input-text required" id="firstname" type="text" name="firstname" value="" maxlength="500" autocomplete="off">
</div>
<div class="form-row required">
<label for="lastname">
<span aria-required="true">Surname</span>
<span class="required-indicator">*</span>
</label>
<input class="input-text required" id="lastname" type="text" name="lastname" value="" maxlength="500" autocomplete="off">
</div>
<div class="form-row required">
<label for="signup-email" style="display:none;">Email</label>
<input class="header-signup-email" type="text" id="signup-email-header" name="signup-email" value="" placeholder="Email" />
</div>
<div class="form-row text-center">
<input type="submit" name="signup-submit" id="signup-submit" class="subscribe-submit" value="Submit" />
</div>
</form>
<div id="thank-you">
<p>Thanks for subscribing!</p>
</div>
</div>
</div>
</div>
</div>
I think some other javascript/jQuery code are making issues to run the codes, for simple solution make your code as plugin and called it like following.
create new js file called validation.js
(function($){
$.fn.validation = function(){
var $subscribe = $('#click-subscribe');
var $subscribeContent = $('#subscribe-content');
var $subscribeClose = $('#subscription-close');
$subscribeContent.hide();
$subscribe.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
$subscribeClose.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
var $form = $('#signup-form'), $signupForm = $('.form-show'), $formReplace = $('#thank-you'); $formReplace.hide();
this.on('submit', function(e){
var empty = $(this).find("input, select, textarea").filter(function() {
return this.value === "";
});
if(empty.length == 0){
$signupForm.hide();
$formReplace.show();
}
e.preventDefault();
});
};
})(jQuery);
Now, call the validation.js at the head like below
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="validation.js"></script>
<script type="text/javascript">
$(function(){
$('#signup-form').validation();
});
</script>
when clicked on submit button, it will call function, in that function i am trying to write logic to disable submit button when fields are not valid, here email must be contain #, dot and after dot minimum 2 & maximum 4 alphabet characters. I tried bellow code.
HTML:
<div ng-app="myApp" ng-controller="myCtrl">
<form name="myForm">
<div>
<select id="country" style="width:250px;" class="" name="selectFranchise" ng-model="state1" ng-change="displayState(state1)"
ng-required>
<option ng-repeat="(key,country) in countries" value="{{key}}">{{country[0]}}</option>
</select>
</div>
<div>
<select id="state" ng-disabled="!states[state1].length" ng-model="cities" ng-required>
<option ng-repeat="(state,city) in states[state1]" value="{{city}}">{{city}}</option>
</select>
</div>
<input type="email" ng-disable="myForm.user.email.$valid" ng-model="user.email" name="eamil" ng-required/>
<button ng-disable="myForm.user.email.$valid" ng-click="formsubmit();">submit</button>
</form>
</div>
SCRIPT:
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.formsubmit = function () {
}
$scope.states = {
"IN": [
"Delhi",
"Goa",
"Gujarat",
"Himachal Pradesh",
]
};
$scope.countries = {
IN: ["India"],
ZA: ["South Africa"],
AT: ["Austria"]
}
$scope.state1 = Object.keys($scope.countries)[0];
$scope.lastName = "Doe";
});
jsfiddle
<form role="form" name="signupForm" ng-submit="signup()" novalidate>
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6">
<div class="clearfix"> </div>
<div class="inputGroup">
<input type="text" id="su_username" name="username" class="form-control input-md"
ng-model="user.username" ng-minlength="8" required>
<span class="inputBar"></span>
<label translate="signup.form.username">Username</label>
<span class="text-danger" ng-show="signupForm.username.$dirty && signupForm.username.$invalid">
<span ng-show="signupForm.username.$error.required" translate="signup.messages.validate.username.required">Username is required.</span>
<span ng-show="signupForm.username.$error.minlength" translate="signup.messages.validate.username.minlength">Username must be at least 8 characters.</span>
</span>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6">
<div class="clearfix"> </div>
<div class="inputGroup">
<input type="email" name="email" id="su_email" class="form-control input-md"
ng-model="user.email" required>
<span class="inputBar"></span>
<label translate="signup.form.email">Email Address</label>
<span class="text-danger" ng-show="signupForm.email.$dirty && signupForm.email.$invalid">
<span ng-show="signupForm.email.$error.required" translate="signup.messages.validate.email.required">Email is required.</span>
<span ng-show="signupForm.email.$error.email" translate="signup.messages.validate.email.invalid">Invalid email address.</span>
</span>
</div>
</div>
</div>
<button type="submit" class="btn btn-custom btn-lg btn-block"
ng-disabled="signupForm.$invalid ">
1st of all you need to give your form a name here its signupForm .
2nd from there you need to give your input fields names for example here they areusername and email.
Then you can use various angular validation directives to set validation constrains like require , length then you can check for validation error using signupForm.username.$invalid and check various error like signupForm.email.$error.email.
Finally if you want to check if the whole from is valid use signupForm.$invalid
and for number validation use
angular.module('test')
.directive('validNumber', function() {
return {
require: '?ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
if(!ngModelCtrl) {
return;
}
ngModelCtrl.$parsers.push(function(val) {
if (angular.isUndefined(val)) {
val = '';
}
var clean = val.replace( /[^0-9\.]/g, '');
if (val !== clean) {
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}
return clean;
});
element.bind('keypress', function(event) {
if(event.keyCode === 32) {
event.preventDefault();
}
});
}
};
});
you can find github example from here
var app = angular.module('jsbin', []);
app.controller('DemoCtrl', function() {
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Angular JS</title>
</head>
<body ng-app="jsbin">
<div ng-controller="DemoCtrl as demo">
<form name="form" novalidate ng-submit="validate()">
<input type="email" name="email" ng-model="email" required />
<span class="help-inline" ng-show="submitted && form.email.$error.required">Required</span>
<span class="help-inline" ng-show="submitted && form.email.$error.email">Invalid email</span>
<button type="submit" class="btn btn-primary btn-large" ng-disabled="submitted && form.email.$error.required || submitted && form.email.$error.email" ng-click="submitted=true">Submit</button>
</form>
</div>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
</body>
</html>
Check This Out.
In order to disable the submit button, you can do something like this:
<form name="myForm">
<input ...>
...
<button type="button" ng-disabled="myForm.$invalid" ng-click="formsubmit();">
Submit
</button>
</form>
Notice that I have put ng-disabled with a condition of myForm being invalid. So, instead of waiting for user to click the button, we are disabling the submit button upfront when form is invalid!
For Email validation, I would suggest you to go with <input type = "email"...> unless you have specific email validation requirements not handled by type = "email"
Here's the updated fiddle which disables the submit button until we put a valid email address.
Edit: Here's an example of how ng-pattern can be used to validate email for given rules (i.e. email must contain #, dot and after dot minimum 2 & maximum 4 alphabet characters)
<input type="text" ng-model="user.email" name="email" required
ng-pattern="/[a-zA-Z0-9_.]+\#[a-zA-Z0-9_]+\.[a-zA-Z]{2,4}$/"/>
Here's the updated fiddle
Also, regex101 for the email validation regex
I would have 3 questions concerning the JQuery syntax:
1) The modal is not showing up. This may be an operator (&&) problem? How do I get it right? It should show up only if the thing is valid.
2) How to combine submit prevent Default with valid classes? I have used that before but never combined with JQuery. I want the modal only to show when is_email is valid and when the InputEmail, InputMessage and InputName fields were filled out.
$('#submit').click(function(submit){
if($('#InputEmail'&&'#InputMessage'&&'#InputName').val().length === 0)&& (is_email=="valid") {
$('#myModal').modal('show');
submit.preventDefault();
}
);
4) If I put the col-lg6, it will change size, however the documentation says that I have to add this:
$('.message-group').attr({
class: 'has-success'
works but if I add col-lg6 form-group name-group it will change the size. Why is this?
My syntax is:
/*JQUERY FORM EFFECTS*/
/*$('#InputName').on('input', function() {
var input=$(this);
var is_name=input.val();
if(is_name){input.removeClass("invalid").addClass("valid");}
else{input.removeClass("valid").addClass("invalid");}
}); Can I comment that out? */
$('#InputEmail').on('input', function() {
var input=$(this);
var re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var is_email=re.test(input.val());
if(is_email){
input.removeClass("invalid").addClass("valid");
}
else{
input.removeClass("valid").addClass("invalid");
}
});
/* Display please enter a name. */
$('#InputName').focusout(function(){
if($('#InputName').val().length === 0) {
$('.name-group .message-block').text('Please enter your name.');
$('.name-group').attr({
class: 'has-error'
}); // end attr
} else {
$('.name-group .message-block').text('');
$('.name-group').attr({
class: 'has-success'
}); //end attr
}
}); //end focus out
$('#InputMessage').focusout(function(){
if($('#InputMessage').val().length === 0) {
$('.message-group .message-block').text('Please enter your message.');
$('.message-group').attr({
class: 'has-error'
}); // end attr
} else {
$('.message-group .message-block').text('');
$('.message-group').attr({
class: 'has-success'
}); //end attr
}
}); //end focus out
$('#InputEmail').focusout(function(){
if($('#InputEmail').val().length === 0) {
$('.mail-group .email-block').text('Please enter your email.');
$('.mail-group').attr({
class: 'has-error'
}); // end attr
} else {
$('.mail-group .email-block').text('');
$('.mail-group').attr({
class: 'has-success'
}); //end attr
}
}); //end focus out
$('#submit').click(function(submit){
if($('#InputEmail'&&'#InputMessage'&&'#InputName').val().length === 0)&& (is_email=="valid") {
$('#myModal').modal('show');
submit.preventDefault();
}
);
My form:
<div class="form-group name-group">
<label for="InputName">Your Name</label>
<div class="input-group">
<input type="text" class="form-control" name="InputName" id="InputName" placeholder="Enter Name" required>
<span class="input-group-addon">
<i class="glyphicon glyphicon-ok form-control-feedback"></i>
</span>
</div>
<span class="text-block"></span>
</div>
<div class="form-group mail-group">
<label for="InputEmail">Your Email</label>
<div class="input-group">
<input type="email" class="form-control" id="InputEmail" name="InputEmail" placeholder="Enter Email" required>
<span class="input-group-addon">
<i class="glyphicon glyphicon-ok form-control-feedback"></i>
</span>
</div>
<span class="email-block"></span>
</div>
<div class="form-group message-group">
<label for="InputMessage">Message</label>
<div class="input-group"
>
<textarea name="InputMessage" id="InputMessage" class="form-control" rows="5" required></textarea>
<span class="input-group-addon"><i class="glyphicon glyphicon-ok form-control-feedback"></i></span>
</div>
<span class="message-block"></span>
</div>
<input type="submit" name="submit" id="submit" value="Submit" class="btn btn-info pull-right">
</div>
</form>
Can you show your markup for your div with the id of myModal?
Also, are you looking for a multiselect? If so here is a link to jQuery's documentation on including multiple element queries in a single selector call: http://api.jquery.com/multiple-selector/
Something more like:
if($('#InputEmail,#InputMessage,#InputName').val().length === 0)
{
alert('not filled out');
return false;
}
else return true;
Also, if that is a direct copy/paste, you are missing a closing parenthesis on your if statement:
if($('#InputEmail'&&'#InputMessage'&&'#InputName').val().length === 0)&& (is_email=="valid"))
Also, could you please clarify what you are asking in your bootstrap .css question?