I have a form with 6 inputs, the inputs are grouped by two and I enable/disable them using a checkbox like in this fiddle.
How do I restrict the search? For example, I need to let the user know they need to fill both inputs if they select the check1 checkbox, or if they selected checkboxes check1 and check2 that they need to fill all 4 inputs. Right now I have this:
if( (check1.checked || check2.checked || check3.checked) ){
if($scope.tolPositivaDim1 == '' || $scope.tolNegativaDim1 == '' ||
$scope.tolPositivaDim2 == '' || $scope.tolNegativaDim2 == '' ||
$scope.tolPositivaDim3 == '' || $scope.tolNegativaDim3 == ''){
console.log(''Need to fill all inputs);
} else
console.log('Something');
} else {
console.log('Need to check at least one');
}
But with this it doesn't let me search until I have filled the six inputs. Is there a way to do this without having to do an if for each specific case?:
if(check1.checked) || if(check1.checked && check2.checked).....
You could improve the code to work with any number of such checkbox & double input combinations. Then define a handler for the form's submit event, and check that inputs are not empty when they are not disabled. If one of those is empty return false, so to cancel the submission.
Some of the code below uses ES6 features. If you cannot use those, it should not be hard to translate the idea to ES5:
var checks = [...document.querySelectorAll('[id^=checkDimension]')],
positivaDims = [...document.querySelectorAll('[id^=tolPositivaDim')],
negativaDims = [...document.querySelectorAll('[id^=tolNegativaDim')];
checks.forEach(function (check, i) {
check.onchange = function() {
positivaDims[i].disabled = !checks[i].checked;
negativaDims[i].disabled = !checks[i].checked;
}.bind(i);
// call the above code also on page load, so to initialise the disabled
// properties correctly:
check.onchange();
});
document.forms[0].onsubmit = function (e) {
if (positivaDims.concat(negativaDims).some(function (input) {
// if for any non-disabled input the value is blank...
return !input.disabled && input.value == '';
})) {
alert('All inputs are required.');
// cancel form submission (either of the two methods below will do it)
e.preventDefault();
return false;
}
}
<form class="" method="post">
<div class="form-group col-sm-12">
<div class="col-sm-4">
<div class="checkbox">
<label><input type="checkbox" id="checkDimension1"> Dimension 1</label>
</div>
</div>
<div class="col-sm-4">
<input type="text" class="form-control" id="tolPositivaDim1" placeholder="0.03" ng-model="tolPositivaDim1">
</div>
<div class="col-sm-4">
<input type="text" class="form-control" id="tolNegativaDim1" placeholder="0.03" ng-model="tolNegativaDim1">
</div>
</div>
<div class="form-group col-sm-12">
<div class="col-sm-4">
<div class="checkbox">
<label><input type="checkbox" id="checkDimension2"> Dimension 2</label>
</div>
</div>
<div class="col-sm-4">
<input type="text" class="form-control" id="tolPositivaDim2" placeholder="0.03" ng-model="tolPositivaDim2">
</div>
<div class="col-sm-4">
<input type="text" class="form-control" id="tolNegativaDim2" placeholder="0.03" ng-model="tolNegativaDim2">
</div>
</div>
<div class="form-group col-sm-12">
<div class="col-sm-4">
<div class="checkbox">
<label><input type="checkbox" id="checkDimension3"> Dimension 3</label>
</div>
</div>
<div class="col-sm-4">
<input type="text" class="form-control" id="tolPositivaDim3" placeholder="0.03" ng-model="tolPositivaDim3">
</div>
<div class="col-sm-4">
<input type="text" class="form-control" id="tolNegativaDim3" placeholder="0.03" ng-model="tolNegativaDim3">
</div>
</div>
<button type="submit" class="btn btn-default pull-right" >Search</button>
<button class="btn btn-default pull-right">Cancel</button>
</form>
The same is also available in this fiddle.
Related
After some reconfiguring I have some jQuery that handles enabling a "save" button when a field has a value:
$(document).ready(function () {
$('.save-button').attr('disabled', true);
$('#selection').keyup(function () {
if ($('#selection').val().length != 0) {
$('.save-button').attr('disabled', false);
} else {
$('.save-button').attr('disabled', true);
}
});
});
... but I realize now I should only enable this button when three separate form elements have values -- two of which are input fields, and one being a text-area.
The thing is, these could be filled in in any order, so how do I get my check to run so as to make sure it enables the "save" button when all three have values? In other words, what event can I use to check this?
The three IDs in question are: selection, schedule, and json-data
Here is my relevant HTML:
<div class="form-group">
<label>Job Name</label>
<input type="text" class="job-name form-control" id="selection">
</div>
<div class="form-group">
<div><label for="meeting-time">Schedule</label></div>
<input type="datetime-local" class="job-schedule form-control" min="getDateDefault()" max="getEndDate()"
id="schedule">
</div>
<div class="form-group">
<label>Repeat Every</label>
<input type="text" class="job-repeat-every form-control">
</div>
<div class="form-group">
<label>Job Data (json)</label>
<textarea class="job-data form-control" id="json-data">{}</textarea>
</div>
<div class="form-group">
<span class="btn btn-default btn-success save-button" data-action="save">Save</span>
<span class="btn btn-default btn-warning" data-action="cancel">Cancel</span>
</div>
You should use the focusout event on each element you need to check its value.
I have created a snippet, you can see the updated version of your code.
$(document).ready(function () {
$('.save-button').attr('disabled', true);
$('#selection, #schedule, #json-data').focusout(function () {
if ($('#selection').val() == "" ||
$('#json-data').val() == "" ||
$('#schedule').val() == ""
) {
$('.save-button').attr('disabled', true);
} else {
$('.save-button').attr('disabled', false);
}
});
});
.btn[disabled="disabled"] {
color: #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label>Job Name</label>
<input type="text" class="job-name form-control" id="selection">
</div>
<div class="form-group">
<div><label for="meeting-time">Schedule</label></div>
<input type="datetime-local" class="job-schedule form-control" min="getDateDefault()" max="getEndDate()"
id="schedule">
</div>
<div class="form-group">
<label>Repeat Every</label>
<input type="text" class="job-repeat-every form-control">
</div>
<div class="form-group">
<label>Job Data (json)</label>
<textarea class="job-data form-control" id="json-data">{}</textarea>
</div>
<div class="form-group">
<span class="btn btn-default btn-success save-button" data-action="save">Save</span>
<span class="btn btn-default btn-warning" data-action="cancel">Cancel</span>
</div>
I have a registration form that I would like to have multiple field validation. What I mean by this is if more than one field is not filled in it will be highlighted red. I have some code already written but instead of highlighting the field not filled in, it's highlighting all of them. I realise it is quite long winded but I'm fairly new to this. My JS code is as follows:
`function formCheck() {
var val = document.getElementById("fillMeIn").value;
var val = document.getElementById("fillMeIn2").value;
var val = document.getElementById("fillMeIn3").value;
var val = document.getElementById("fillMeIn4").value;
var val = document.getElementById("fillMeIn5").value;
var val = document.getElementById("fillMeIn6").value;
var val = document.getElementById("fillMeIn7").value;
if (val == "") {
alert("Please fill in the missing fields");
document.getElementById("fillMeIn").style.borderColor = "red";
document.getElementById("fillMeIn2").style.borderColor = "red";
document.getElementById("fillMeIn3").style.borderColor = "red";
document.getElementById("fillMeIn4").style.borderColor = "red";
document.getElementById("fillMeIn5").style.borderColor = "red";
document.getElementById("fillMeIn6").style.borderColor = "red";
document.getElementById("fillMeIn7").style.borderColor = "red";
return false;
}
else {
document.getElementById("fillMeIn").style.borderColor = "green";
document.getElementById("fillMeIn2").style.borderColor = "green";
document.getElementById("fillMeIn3").style.borderColor = "green";
document.getElementById("fillMeIn4").style.borderColor = "green";
document.getElementById("fillMeIn5").style.borderColor = "green";
document.getElementById("fillMeIn6").style.borderColor = "green";
document.getElementById("fillMeIn7").style.borderColor = "green";
}
}`
My HTML is as follows:
'<form id="mbrForm" onsubmit="return formCheck();" action="thanks.html" method="post">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
FIRST NAME:
<input id="fillMeIn" type="text" class="form-control" placeholder="First Name" >
</div>
<div class="col-md-4 vertical-gap">
LAST NAME:
<input id="fillMeIn2" type="text" class="form-control" placeholder="Last Name" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8 vertical-gap">
ADDRESS:
<input id="fillMeIn3" type="text" class="form-control vertical-gap" placeholder="First Line" >
<input id="fillMeIn4" type="text" class="form-control vertical-gap" placeholder="Second Line" >
<input id="fillMeIn5" type="text" class="form-control vertical-gap" placeholder="Town/City" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
POST CODE:
<input id="fillMeIn6" type="text" class="form-control vertical-gap" placeholder="Postcode" >
</div>
<div class="col-md-4 vertical-gap">
PHONE No:
<input type="number" class="form-control vertical-gap" placeholder="Tel no">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
EMAIL ADDRESS:
<input id="fillMeIn7" type="email" class="form-control vertical-gap" placeholder="Email address" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row vertical-gap">
<div class="col-md-2"></div>
<div class="col-md-8">
DISCIPLINE:
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Cross Country"> CROSS COUNTRY
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Enduro"> ENDURO
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Downhill"> DOWNHILL
</label>
</div>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-10">
<!--<button type="button" input type="hidden" class="btn btn-success" name="redirect" value="thanks.html">SUBMIT</button>-->
<input type="submit" value="SUBMIT" class="btn btn-success btn-lg">
</div>
<div class="col-md-2"></div>
</div>
</form>'
Thanks!
You could have the ids in an Array, iterate through its values, and execute the repeatable code in a function that groups all the logic inside.
example :
["fillMeIn1", "fillMeIn2", "fillMeIn3", "fillMeIn4"].each(function(id){
// do things with id
})
Why not use the html "required" property instead?
If you want to do this with JS, you should give each variable a different name. In the code you posted you are continuously overwriting the same variable, and then, it evaluates val (which ended up being assigned to the (fill me7 value) to "", and if true, setting all the borders to red.
Set different variables, push the input values into an array when submit is triggered and loop through them if variables[i]==0, set getElementId(switch case[i] or another array with the name of the inputs[i]).bordercolor to red.
AGAIN, this sound VERY INEFFICIENT and I am not sure at all it would work. My guess is that it would take A LOT of time, and probably get timed out (except you are using some asych/try-catch kind of JS).
I would simply go for an HTML required property and then override the "required" property in CSS to make it look as you intend to. Simpler, easy and clean.
The main issue in your code is that you override the variable val each time you wrote var val = ....
Keeping your own your logic, you could write something like that.
var formModule = (function () {
var $fields = [
document.getElementById('fillMeIn'),
document.getElementById('fillMeIn2'),
document.getElementById('fillMeIn3'),
document.getElementById('fillMeIn4'),
document.getElementById('fillMeIn5'),
document.getElementById('fillMeIn6'),
document.getElementById('fillMeIn7')
];
function markInvalid($field) {
$field.style.borderColor = 'red';
}
function markValid($field) {
$field.style.borderColor = 'green';
}
return {
check: function () {
var isValid = true;
$fields.forEach(function ($f) {
if ($f.value === '') {
if (isValid) alert('Please fill in the missing fields');
isValid = false;
markInvalid($f);
}
else markValid($f);
});
return isValid;
}
};
})();
There are some extra concepts in this example which may be useful:
Working with the DOM is really slow, that's why you should
put your elements in a variable once for all and not everytime you
click on the submit button.
In my example i wrap the code with var formModule = (function () {...})();.
It's called module pattern. The goal is to prevent variables to leak in the rest of the application.
A better solution could be this one using the 'power' of html form validation:
HTML:
<form id="mbrForm" action="thanks.html" method="post">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
FIRST NAME:
<input id="fillMeIn" type="text" required class="form-control" placeholder="First Name">
</div>
<div class="col-md-4 vertical-gap">
LAST NAME:
<input id="fillMeIn2" type="text" required class="form-control" placeholder="Last Name">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8 vertical-gap">
ADDRESS:
<input id="fillMeIn3" type="text" required class="form-control vertical-gap" placeholder="First Line">
<input id="fillMeIn4" type="text" required class="form-control vertical-gap" placeholder="Second Line">
<input id="fillMeIn5" type="text" required class="form-control vertical-gap" placeholder="Town/City">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
POST CODE:
<input id="fillMeIn6" type="text" required class="form-control vertical-gap" placeholder="Postcode">
</div>
<div class="col-md-4 vertical-gap">
PHONE No:
<input type="number" class="form-control vertical-gap" placeholder="Tel no">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
EMAIL ADDRESS:
<input id="fillMeIn7" type="email" required class="form-control vertical-gap" placeholder="Email address">
</div>
<div class="col-md-2"></div>
</div>
<div class="row vertical-gap">
<div class="col-md-2"></div>
<div class="col-md-8">
DISCIPLINE:
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Cross Country"> CROSS COUNTRY
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Enduro"> ENDURO
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Downhill"> DOWNHILL
</label>
</div>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-10">
<input id="btnSubmit" type="submit" value="SUBMIT" class="btn btn-success btn-lg">
</div>
<div class="col-md-2"></div>
</div>
</form>
JS:
var formModule = (function () {
var $form = document.getElementById('mbrForm');
var $btn = document.getElementById('btnSubmit');
var $fields = [
document.getElementById('fillMeIn'),
document.getElementById('fillMeIn2'),
document.getElementById('fillMeIn3'),
document.getElementById('fillMeIn4'),
document.getElementById('fillMeIn5'),
document.getElementById('fillMeIn6'),
document.getElementById('fillMeIn7')
];
checkValidation();
$form.addEventListener('change', checkValidation);
$form.addEventListener('keyup', checkValidation);
$fields.forEach(function ($f) {
$f.addEventListener('change', function () {
markInput($f, $f.checkValidity());
});
});
function checkValidation() {
$btn.disabled = !$form.checkValidity();
}
function markInput($field, isValid) {
$field.style.borderColor = isValid ? 'green' : 'red';
}
})();
In this example, the button gets disabled until the form is valid and inputs are validated whenever they are changed.
I added required attribute in HTML inputs so they can be handled by native javascript function checkValidity(). Note that in this case inputs email and number are also correctly checked. You could also use attribute pattern to get a more powerfull validation:
<input type="text" pattern="-?[0-9]*(\.[0-9]+)?">
Hope it helps.
My HTML code is
<body>
<form name="contactus" id='contactus' action="test1.php" method="post" enctype="multipart/form-data">
<input type="hidden" value="2" name="Tab" id="Tab">
<div class="row underlinDv">
<div class="col-sm-4">
Your Email :
</div>
<div class="col-sm-8">
<input maxlength="100" type="email" class="form-control" placeholder="Enter Email" name="UEmailLogin" id="UEmailLogin" minlength="3">
</div>
</div>
<!--18-->
<div class="row underlinDv">
<div class="col-sm-8 col-md-offset-4">
<input type="submit" id="demo2GetTags" class="btn btn-primary btn-md" value="Submit" onclick='search()' />
</div>
</div>
</form>
<script>
function search() {
var Tab = document.getElementById("Tab").value;
alert(Tab);
var Eamillogin = document.getElementById("UEmailLogin").value;
if (Eamillogin == "") {
alert("please enter email");
Eamillogin.focus();
}
}
</script>
</body>
When I click on submit button, JavaScript alert shows "please enter email". It works fine. But Eamillogin.focus(); not working. After showing alert, the form automatically direct to test1.php page.Pointer not focus on Email. How to correct it?
Eamillogin variable contains the value of the #UEmailLogin element.
To set the focus on the element, use element.focus();
Here's updated code
var Eamillogin = document.getElementById("UEmailLogin"); // Removed .value from here
if (Eamillogin.value === "") { // Added .value here
alert("please enter email");
Eamillogin.focus(); // Focus element
}
function search() {
var Tab = document.getElementById("Tab").value;
var Eamillogin = document.getElementById("UEmailLogin");
if (Eamillogin.value === "") {
alert("please enter email");
Eamillogin.focus();
}
}
<form name="contactus" id='contactus' action="test1.php" method="post" enctype="multipart/form-data">
<input type="hidden" value="2" name="Tab" id="Tab">
<div class="row underlinDv">
<div class="col-sm-4">
Your Email :
</div>
<div class="col-sm-8">
<input maxlength="100" type="email" class="form-control" placeholder="Enter Email" name="UEmailLogin" id="UEmailLogin" minlength="3">
</div>
</div>
<!--18-->
<div class="row underlinDv">
<div class="col-sm-8 col-md-offset-4">
<input type="submit" id="demo2GetTags" class="btn btn-primary btn-md" value="Submit" onclick='search()' />
</div>
</div>
</form>
i have two radio buttons used in my form and follow to those two radio buttons i have another field.
I want to show that field if only a certain radio button is checked.otherwise by default it should be hidden.
My code
Payment Type
<div class="list">
<label class="item item-radio">
<input type="radio" name="group">
<div class="item-content">
Immediate Payment
</div>
<i class="radio-icon ion-checkmark"></i>
</label>
<label class="item item-radio">
<input type="radio" name="group">
<div class="item-content">
Scheduled Payment
</div>
<i class="radio-icon ion-checkmark"></i>
</label>
</div>
<label><h4><b>Effective Date*</b></h4></label>
<input type="date" >
Here i want to show effective date field only if the user checks the Scheduled Payment radio button. How can i do this?
$("input[name=group]").change(function () {
if ($(this).val() == 'scheduled' && $(this).is(":checked")) {
$("#effectiveWrapper").show();
} else {
$("#effectiveWrapper").hide();
}
});
http://jsfiddle.net/wdckktz7/
AngularJS Code
<div ng-show="payment == 'scheduled'">
<label>
<h4><b>Effective Date*</b></h4>
</label>
<input type="date" />
</div>
http://jsfiddle.net/orr1p1eg/
$("input:radio[name='group']").click(function() {
var value = $(this).val();
if (value == 'Scheduled Payment'){
$("#div").show();
}
else {
$("#div").hide();
}
});
and put your date input inside the div:
<div id="div">
<label><h4><b>Effective Date*</b></h4></label>
<input type="date" >
</div>
So I have a few columns in the database which I have configured as TINYINT. I have the same number of check boxes as well on the front end.
Here's my HTML,
<script type="text/x-handlebars" id="project">
<div class="row">
<div class="span6">
<div class="well well-small">
<p style="text-align: center">
You can create a new Project by filling this simple form.
</p>
<p style="text-align: center"> Project Name should be minimum 10 characters & There's no limit on
Project Description.
</p>
</div>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="projectname">Project Name: </label>
<div class="controls">
<input type="text" name="projectname" id="projectname" required
title="Project Name is Required!" pattern="[A-z ]{10,}"
placeholder="Enter Project Name"/>
</div>
</div>
<div class="control-group">
<label class="control-label" for="projectdesc">Project Description:</label>
<div class="controls">
<textarea rows="3" id="projectdesc" name="projectdesc" placeholder="Enter Project Desc"
required="Description Required"></textarea>
</div>
</div>
<div class="control-group">
<label class="control-label">Roles:</label>
<div class="controls">
<label class="checkbox">
<input type="checkbox" name="roles" id="script" value="false"> Script
</label>
<label class="checkbox">
<input type="checkbox" name="roles" id="design" value="false"> Design
</label>
<label class="checkbox">
<input type="checkbox" name="roles" id="writer" value="false"> Writer
</label>
<label class="checkbox">
<input type="checkbox" name="roles" id="storyboard" value="false"> Storyboard
</label>
<label class="checkbox">
<input type="checkbox" name="roles" id="workbook" value="false"> Workbook
</label>
<br>
<button class="btn"
{{action 'createNew'}}>Add Project</button>
</div>
</div>
</form>
</div>
</div>
</script>
And here's what I am doing,
function(event) {
$(":text, input[type='checkbox'], textarea").each(function() {
if ($(this).val() === "") {
alert("Empty Fields!");
event.preventDefault();
} else {
App.Project.createNew();
alert("Project Created");
event.preventDefault();
}
});
}
And the Ajax POST,
dataString = {
'projectname' : $("#projectname").val(),
'projectdesc' : $("#projectdesc").val(),
'script' : $('input.roles[type="checkbox"]:checked', this).val()
};
console.log('check');
$.ajax({
type : "POST",
url : "http://ankur.local/users/createNewProject",
data : dataString,
dataType : "json",
success : function(data) {
console.log('success');
alert('');
}
});
return false;
You can see from my code that I am trying to grab the checked value of the textbox which I want to store in the database as 0 or 1 or True or False perhaps? Moreover I want to have a condition that out of the given checkboxes, at least one should be checked.
'script' : $('input.roles[type="checkbox"]:checked', this).val()
How can I achieve my objective?
Condition for checking at least one checkbox is checked
if($('input[type="checkbox"]:checked').length > 0)
{
//do your work
}else
{
alert("Please check any checkbox");
return false;
}
do this check prior to posting your data.
Get the value for saving in database
//will give the value attribute of selected checkbox
// true/false in this case
var value = $('input[type="checkbox"]:checked').val();
//for getting value in 1 or 0 from the above variable.
var value1 = value ? 1 : 0;
For saving all check box values.
var all_values= "";
$('input[type="checkbox"]').each(function(){
var value = $(this).is(":checked") ;
all_values = all_values + "~" + value ;
});
send the value of all_values to your code, use split to get all the values.