I have a Bootstrap form and I am basically trying to loop through all input fields, check if they have a required class and their value is null, if so add some CSS as an error indicator. For some reason the if statement is not working.
My code is:
$("#orderForm").on("submit", function(e) {
var formInputFields = $(".form-control")
formInputFields.each(function(i) {
if (formInputFields[i].hasClass("required") && formInputFields[i].val() === "null") {
e.preventDefault();
formInputFields.css("border", "2px solid #741e4f");
}
});
});
HTML is along these lines, but longer, same structure though, the form-group div is repeated:
<form class="form-horizontal" id="orderForm">
<div class="form-group">
<label for="" class="col-sm-4 control-label">Lorem</label>
<div class="col-sm-6">
<select name="" id="" class="form-control required">
<option value=""></option>
<option value="lorem">lorem</option>
<option value="ipsun">ipsun</option>
</select>
</div>
</div>
Your code threw error when you say formInputFields[i].hasClass because formInputFields was a jquery object but not formInputFields[i]. Since you were using $.each, the 2nd parameter would have given you current element and instead of formInputFields[i], you could just use that 2nd parameter. Also, when you say cur.val()==="null" it will be strong comparison between left and right i.e. both should match by value and type which always failed here. So just check the length of val and if it is 0 that will be invalid element. Below are the changes I've made. Check and it and let me know if you face any issues.
$("#orderForm").on("submit", function(e) {
var formInputFields = $(".form-control")
formInputFields.each(function(i, v) {
var cur = $(v);
if (cur.hasClass("required") && !(cur.val().length)) {
e.preventDefault();
cur.css("border", "2px solid #741e4f");
}
else
cur.css("border", "");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<form class="form-horizontal" id="orderForm">
<div class="form-group">
<label for="" class="col-sm-4 control-label">Lorem</label>
<div class="col-sm-6">
<select name="" id="" class="form-control required">
<option value=""></option>
<option value="lorem">lorem</option>
<option value="ipsun">ipsun</option>
</select>
</div>
</div>
<input class="btn btn-info" type="submit" value="Submit" />
</form>
Firstly, when an input is required add required as an attribute rather than a class.
<input type="text" id="foo" placeholder="bar" value="" required>
Then you will be able to get any required inputs currently missing values using:
var list_of_invalid_inputs = document.querySelectorAll('*:invalid');
or if you must use jquery like so.
The same selector works in css too:
input:invalid { border: 2px solid #741e4f; }
you can use $(this) instead of formInputFields[i].hasClass... as you need the object to verify if it has the "required" class or not and if it has value or not, for example:
$(document).ready(function(){
$("#orderForm").on("submit", function(e){
var formInputFields = $(".form-control");
formInputFields.each(function(i) {
if($(this).hasClass("required") && $.trim($(this).val()) === ""){
e.preventDefault();
$(this).css("border", "2px solid #741e4f");
}
});
return false;
});
});
JSFiddle
Related
The thing that I'd like to happen is that when the value of the status field is Paid the input field fines should be read-only.
How to achieve this?
This is my form:
This is my code:
<div class="form-group">
<label for="status" class="col-sm-3 control-label">Status</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="status" value = "Paid" name="status" readonly>
</div>
</div>
<div class="form-group">
<label for="fines" class="col-sm-3 control-label">Fines</label>
<div class="col-sm-9">
<input type="text"
class="form-control" id="fines" name="fines" required>
</div>
</div>
Javascript line of code:
<script type = "text/javascript">
$(document).ready (function(){
$('input[type=text][name=status]').change(function() {
if (this.value == "Paid") {
$("#fines").prop("readonly",true);
}
else{
$("#fines").prop("readonly",false);
}
});
});
</script>
Seeing as you're status field is set to readonly on load, I'd imagine you want to trigger a change event instantly.
$(document).ready (function(){
// setup a variable for multi-use
var $statusField = $('input[type=text][name=status]');
// watch for changes to the statusField
$statusField.change(function() {
// simpler check for paid status
$('#fines').prop('readonly', this.value === 'Paid');
});
// trigger a change on ready
$statusField.change();
});
This way you have access to trigger the change programatically but also have the ability to watch the status field. I've also cleaned up your code a little bit!
try like this
if ($(this).val() == "Paid") {
$("#fines").attr("readonly",true);
}
else{
$("#fines").attr("readonly",false);
}
I have a simple input params that are required. I want to disable my submit button until all the required fields are satisfied. Granted I am new to django, and the particular code I am working on is very old. As a result, post like this or this are not helping.
Current code that I am trying from one of the posts linked and including my own template
<script type="text/javascript">
$(document).ready(function() {
validate();
$('input').on('keyup', validate);
});
function validate() {
var inputsWithValues = 0;
// get all input fields except for type='submit'
var myInputs = $("input:not([type='submit'])");
myInputs.each(function(e) {
// if it has a value, increment the counter
if ($(this).val()) {
inputsWithValues += 1;
}
});
if (inputsWithValues == myInputs.length) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
$('#submit').on('click', function() {
var zip = $('#zip').val();
var email = $('#email').val();
var name = $('#name').val();
//if inputs are valid, take inputs and do something
});
<form class="form-horizontal" action="" method="get" id="dataform">
<div class="form-group">
<div class="container">
<div class="row">
<div class="col-md-offset-2 col-md-3">
<input class="col-md-12" id="zip" type="text" placeholder="Enter zip code" aria-required="true">
</div>
<div class="col-md-3">
<input class="col-md-12" id="name" type="text" placeholder="Enter last name" aria-required="true">
</div>
<div class="col-md-3">
<input class="col-md-12" id="email" type="email" placeholder="Enter email address" aria-required="true">
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="btn btn-primary" id="submit" type="submit">Submit</div>
</div>
</div>
</form>
any help on disabling my submit button until input fields are not validated/filled is much appreciated. Again, new to django and I am unable to use existing threads on said topic
From your current code, looks like your selector for the submit input is not actually getting the submit "button". Currently, your template defines the submit as a div and not an input, thus your selectors should be $("div[type=submit]") not $("input[type=submit]")
Better yet, just select by div id $('#submit')
Instead of targeting attributes, I was targeting props. Below is the fix for my particular issue.
if (inputsWithValues === 3) {
$("div[type=submit]").attr("disabled", false);
} else {
$("div[type=submit]").attr("disabled", 'disabled');
}
I have a form with a price calculator and while I am able to set all text fields and such using a jQuery script, I can't figure out how to simply set a variable in that jQuery script that is used in a price calculator in another Javascript on the page.
There is a text field with an id of #price_draftarticles that I set a value to - that works but I also have a variable called price_draftarticles that is being added to other variables to create a total. I referenced my Form_Calculator() function but it's still not updating the total.
Relevant form code
<div class="col-sm-8">
<div class="radio">
<label>
<input class="structype" type="radio" name="CorpStructure" id="price_structureop3" value="I want to provide my own structure" onClick="checkRadioCS(); Form_Calculator();"><strong>I want to provide my own structure</strong>
</label>
</div>
</div>
<div class="row">
<div class="col-sm-8">
<div class="checkbox">
<label>
<input name="DraftArticles" type="checkbox" id="DraftArticles" onClick="checkRadioTF(); Form_Calculator();" value="Yes">DETAILS
</label>
</div>
</div>
<div class="col-xs-4 col-sm-2">
<input name="price_draftarticles" type="text" class="form-control fcalc" id="price_draftarticles" value="" readonly>
</div>
</div>
My jquery function
<script>
$(function () {
$('.structype').change(function () {
if ($(this).val() === 'I want to provide my own structure')
{
$("#DraftArticles").prop("checked", true);
$("#price_draftarticles").val('$25.00');
$("price_draftarticles").val('25.00');
$('#CustomStructureDetail').show('500');
}
if ($(this).val() == 'Standard structure template one class of shares') {
$('#CustomStructureDetail').hide('500');
}
if ($(this).val() == 'Two classes of shares') {
$('#CustomStructureDetail').hide('500');
}
});
checkRadioTF();
checkCheckBox();
Form_Calculator();
checkeFileJur();
});
</script>
Looks like you forgot the '#' character in
$("price_draftarticles").val('25.00');
This should be
$("#price_draftarticles").val('25.00');
As what #BYates said the selector missed '#' for price_draftarticles.
$("#price_draftarticles").val('25.00');
But if you're trying to get/set value of the input using it's name. The selector should be like this:
$('input[name="price_draftarticles"]').val('25.00')
I am trying to fill a textbox when a value is selected from a dropdown list.
I am able to do that, but in the process of doing so, I am unable to pick the value appearing in the textbox in my python script.
Now in my database I am getting a none value for the UserID. And the actual user ID is appearing in the Name column, as you can see in the screenshot.
This is the HTML:
<div class="col-xs-6 col-sm-6 col-md-6 col-lg-6" style="margin:0px 0px 0px 50px"><label for="form_lastname" class="control-label">Name</label>
<select name="username" id="username" required class="form-control">
<option value=""></option>
<option value="maahir10">Dadlani, Maahir</option>
</select>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" style="width:145px
<label for="form_lastname" class="control-label">User ID</label>
<textarea type="text" id="userid" style="height:35px;width:120px;font-family:Raleway" disabled="yes" required></textarea>
</div>
The JS:
<script type="text/javascript">
var mytextbox = document.getElementById('userid');
var mydropdown = document.getElementById('username');
mydropdown.onchange = function(){
mytextbox.innerHTML = this.value;
}
</script>
So, how do i fix this error and get both the values in my DB. Please advise. Thank you.
You should use .value option for input field not .innerHTML
<script type="text/javascript">
var mytextbox = document.getElementById('userid');
var mydropdown = document.getElementById('username');
mydropdown.onchange = function(){
mytextbox.value = this.value;
}
</script>
also you used disabled on your textarea, and that prevents the value to be sent via POST, use readonly instead.
I'm trying to create a form where, if the user selects 'yes' from a dropdown, two extra fields appear. Both of these fields are required, and one of them needs to be validated according to an array of 'codes' - the user must input one of the codes in the array for the form to submit correctly. However, if the user selects 'no' from the dropdown, these fields do not appear and are not required, and the array validation does not occur and the form can be submitted.
I have some code for this, however I can't get the fields to appear. An earlier issue I encountered with this (minus the array validation - including that broke the code and stopped the extra fields appearing) was that if the user selected 'yes', and then went back to change their mind and selected 'no', then the form would not submit, clearly still requiring the fields to be filled in/correct array value inputted.
If anyone could help me in making this work I would greatly appreciate it.
HTML:
<form id="form" method="post" action="action.php">
<div class="form-group">
<label class="control-label">Defect?</label>
<select onclick='checkIfYes()' class="select form-control" id="defect" name="defect">
<option id="No" value="No">No</option>
<option id="Yes" value="Yes">Yes</option>
</select>
</div>
<div id="extra" name="extra" style="display: none">
<label class="control-label" for="desc">Description</label>
<input class="form-control" type="text" id="desc" name="desc" required disabled>
<label class="control-label" for="auth_by">Authorised By</label>
<input class="form-control" type="text" id="auth_code_input" name="auth_by" required disabled>
</div>
<hr>
<div class="form-group">
<button class="btn btn-info" id="submit" name="submit" type="submit">Submit
</button>
</div>
</form>
JavaScript:
$(document).ready(function() {
checkIfYes = function checkIfYes() {
if (document.getElementById('defect').value == 'Yes') {
// show extra fields & make them required
document.getElementById('extra').style.display = '';
document.getElementById('auth_code_input').disabled = false;
document.getElementById('desc').disabled = false;
// show user if their input is one of the codes in the array when leaving field
$('#auth_code_input').blur(function() {
if (!ValidateInput()) {
e.preventDefault();
}
});
// prevent form submission if input is not one of the codes in the array
$('#auth_form').on('submit', function(e) {
if (!ValidateInput()) {
e.preventDefault();
}
});
function ValidateInput() {
var codes = ['Foo', 'Bar']; // user must enter one of these
var IsValid = false;
var input = $('#auth_code_input').val()
if (codes.indexOf(input) > -1) { // if input equals one of the codes in the array
$('#iconBad').removeClass('glyphicon-remove').addClass('glyphicon-ok');
IsValid = true;
} else {
$('#iconBad').removeClass('glyphicon-ok').addClass('glyphicon-remove');
IsValid = false;
}
return IsValid;
}
} else { // hide and disable extra fields so form can submit
document.getElementById('extra').style.display = 'none';
document.getElementById('auth_code_input').disabled = true;
document.getElementById('desc').disabled = true;
}
}
});
JSFiddle
It's a glitch in the way you define the function -- by calling checkIfYes() it's looking for it on the global (window's) scope. By changing the line:
function checkIfYes() {...
to this:
checkIfYes = function() {...
then you've got it on the global scope. Which is, by the way, bad practice. You'd be better to create a click handler in your script itself, than to hard- code the function call in your HTML. But that's just me.
A few changes made, some pretty significant -- first, I removed the hard-coded reference to checkIfYes and simply put the event in your javascript. Second (and pretty darn significant), I moved the event handlers to the root of your javascript, rather than defining them in your checkIfYes function. This way, they don't depend on that being called each time. Try it, it works.
$(document).ready(function() {
/**
* Define some custom events to handle...
**/
$("#defect").on("change", checkIfYes );
// show user if their input is one of the codes in the array when leaving field
$('#auth_code_input').blur(function() {
if (!ValidateInput()) {
console.log("Input is wrong!");
}
});
// prevent form submission if input is not one of the codes in the array
$('#auth_form').on('submit', function(e) {
e.preventDefault();
console.log("This is where I would be checking...");
if (ValidateInput()) {
$("#auth_form").submit();
}
});
// Utility Functions.
function checkIfYes() {
if (document.getElementById('defect').value == 'Yes') {
// show extra fields & make them required
document.getElementById('extra').style.display = '';
document.getElementById('auth_code_input').disabled = false;
document.getElementById('desc').disabled = false;
} else { // hide and disable extra fields so form can submit
document.getElementById('extra').style.display = 'none';
document.getElementById('auth_code_input').disabled = true;
document.getElementById('desc').disabled = true;
}
}
function ValidateInput() {
var codes = ['Foo', 'Bar']; // user must enter one of these
var IsValid = false;
var input = $('#auth_code_input').val()
if (codes.indexOf(input) > -1) { // if input equals one of the codes in the array
$('#iconBad').removeClass('glyphicon-remove').addClass('glyphicon-ok');
IsValid = true;
} else {
$('#iconBad').removeClass('glyphicon-ok').addClass('glyphicon-remove');
IsValid = false;
}
return IsValid;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form" method="post" action="action.php">
<div class="form-group">
<label class="control-label">Defect?</label>
<select class="select form-control" id="defect" name="defect">
<option id="No" value="No">No</option>
<option id="Yes" value="Yes">Yes</option>
</select>
</div>
<div id="extra" name="extra" style="display: none">
<label class="control-label" for="desc">Description</label>
<input class="form-control" type="text" id="desc" name="desc" required disabled>
<label class="control-label" for="auth_by">Authorised By</label>
<input class="form-control" type="text" id="auth_code_input" name="auth_by" required disabled>
</div>
<hr>
<div class="form-group">
<button class="btn btn-info" id="submit" name="submit" type="submit">Submit
</button>
</div>
</form>