how to disable a send button if fields empty bootstrap - javascript

i am using Bootstrap to make a webpage. I have a simple code with 1 input and 1 button. when you press the button, which contains the input is stored in the database. but if the input is empty also saves it to the database. I can do the validation with javascript but i want to know if bootstrap have an option to validate this. For example forms in bootstrap validate it, but i dont want to use a form.
<div class="row">
<div class="col-md-4 col-md-offset-1">
<div class="input-group input-group-lg"> <span class="input-group-addon"><span class="glyphicon glyphicon-fire"></span> </span>
<input type="text" class="form-control" placeholder="Nombre Marca" id="marca" required>
</div>
</div>
</div>
<div class="row">
<br />
<div class="col-md-3 col-md-offset-1" align="center" onClick="guardar_marca()"> Guardar Marca
</div>
</div>

I'm not sure if you just copied a small portion of your HTML, but in your snippet you have an extra closing </div>. You can use jQuery to test if the input value is empty:
$('.btn').click(function(e) {
if ($('input').val() === '') {
e.preventDefault();
alert('input is empty');
}
});
Bootply

I would use something like this:
$("MYINPUT").on("change",function(){
($(this).val() === "") ? false : $("MYBUTTON").prop("disabled",false);
}

The following code let's you write your click event as well as stop empty values.
$('.btn').click(function(){
if($('#marca').val() === ''){
alert('Empty field');
return false;
}
//The rest of the logic you want to execute
})

If you're looking for a vanilla JavaScript solution, here is something i made for my to-do:
window.onkeyup = function(e) {
var inputs = document.getElementsByClassName("c1"), inputsVal;
for (i = 0; i < inputs.length; i++) {
inputsVal = inputs[i].value;
if (!inputsVal || inputsVal == "" || inputsVal == " ") {
return false//if the inputsVal has 0 data, it will return false.
}
}
if (event.which == 13) {
Uilogic.saveitem();//function to actually send value to database
}
};

Related

sources input failing validation

I have this logic that is in a form that some users are able to process without selecting a source. Is there a better way to do this logic so it will not fail I am unable to get it to fail so I am very limited.
html
<div id="sources">
<label id="lblSources" class="control-label">* Source</label>
<label id="lblSourcesError" class="pl-4 text-danger" style="display:none">At least one 'Source' must be selected</label>
<input type="checkbox" value=#item.Value name="chkProduct" />
</div>
Js
var checked_sourcecheckboxes = $("#sources input[type=checkbox]:checked");
if (checked_sourcecheckboxes.length == 0) {
$("#lblSourcesError").show();
additionalValidation = true
}
else {
$("#lblSourcesError").hide();
}
Consider the following example.
$(function() {
var checked_sourcecheckboxes = $("#sources input[type=checkbox]");
if (checked_sourcecheckboxes.filter(":checked").length == 0) {
$("#lblSourcesError").show();
additionalValidation = true
} else {
$("#lblSourcesError").hide();
}
checked_sourcecheckboxes.change(function() {
if (checked_sourcecheckboxes.filter(":checked").length == 0) {
$("#lblSourcesError").show();
additionalValidation = true
} else {
$("#lblSourcesError").hide();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="sources">
<label id="lblSources" class="control-label">* Source</label>
<label id="lblSourcesError" class="pl-4 text-danger" style="display:none">At least one 'Source' must be selected</label>
<input type="checkbox" value=#item.Value name="chkProduct" />
</div>
This checks the status when the page loads and whenever the checkbox is changed.

How to pass a value to a function and cont execute

I have a form and I'm validating the fields "onblur". what I trying to do is that when the user clicks submit make that any field is empty.
What I was trying to do is to pass the value to a function and run that function when the user click "submit" but I'm having a problem in doing that.
can somebody point me in the right direction on how to fix my problem.
HTML:
<form method="post" name="registerForms" >
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
JS:
function validateForm(id)
{
var value = document.getElementById(id).value;
var ok = true;
if(value === "" || value == null)
{
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
ok = false
yesNo(ok);
}
else
{
document.getElementById(id+'Err').innerHTML = "* ";
}
}
var button = document.getElementById('#registerButton');
button.onclick = function yesNo(ok)
{
alert("There's something wrong with your information!")
if(ok == false)
{
alert("There's something wrong with your information!")
return false;
}
}
If you want to attach the validation on the click event for your submit button I would suggest you to repeat the validation for each input field like you do on blur event.
Moreover, I would suggest you to save the ok value as an attribute of each input field. Set those attributes at dom ready to false and change it to true/false in validateForm function.
When submitting it's a good idea to run your valodator function and test for false fields.
You can use addEventListener in order to register a event handler, querySelectorAll for selecting elements.
The snippet:
function validateForm(id) {
var value = document.getElementById(id).value;
if (value === "" || value == null) {
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
document.getElementById(id).setAttribute('yesNo', 'false');
} else {
document.getElementById(id+'Err').innerHTML = "* ";
document.getElementById(id).setAttribute('yesNo', 'true');
}
}
document.addEventListener('DOMContentLoaded', function(e) {
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
ele.setAttribute('yesNo', 'false');
});
document.getElementById('registerButton').addEventListener('click', function(e) {
var ok = true;
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
validateForm(ele.id);
if (ele.getAttribute('yesNo') == 'false') {
ok = false;
}
});
if (ok == false) {
console.log("There's something wrong with your information!")
e.preventDefault();
}
});
});
<form method="post" name="registerForms" action="http://www.google.com">
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
You were trying to define var button with this
var button = document.getElementById('#registerButton');
but it needs to be this with regular javascript
var button = document.getElementById('registerButton');
That seemed to solve the problem

Client-side validation fire according to empty textboxes on button click

I have 4 text boxes. I want to validate according to bewlow criteria:-
1). IF first textbox value not blank and anotherthree are blank than addclass error on that blank textbox.
2). If second textbox value not blank and 1st, 3rd and 4th textbox valueare blank than addclass error on that blank textbox.
3). If first two textbox value are not blank and another textox value are blank than addClass error on that blank textbox.
4). If First and third textbox value are not blank and 2nd and 4th textbox value are blank than addclass error on that blank textbox.
5).If 3 textboxs value are not blank and one textbox value blank than addclass error on that blank textbox.
This is My jquery validation code:-
$(".submit_data").click(function(){
input1 = $("#data1").val();
input2 = $("#data2").val();
input3= $("#data3").val();
input4= $("#data4").val();
if(input1 == "" && input2 == "" && input3 == "" && input3 == "")
{
$(".data-form").addClass('required');
$(".data-form").addClass('error');
$(".new-data-form").addClass('required');
$(".new-data-form").addClass('error');
}
if( input1 != "" && input2 == "" && input3 == "" && input3 == "" )
{
$("#data2").addClass("error");
$("#data3").addClass("error");
$("#data4").addClass("error");
return false;
}
});
HTML:-
<div id="painting_form" class="painting-form-wrap">
<div class="form-group">
<label class="col-sm-2 control-label">Input 1</label>
<div class="col-sm-10">
<input type="text" name="data1" value="" id="data1" class="form-control painting-form1">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Input 2</label>
<div class="col-sm-10">
<input type="text" name="data2" value="data2" id="input-ceilheight" class="form-control painting-form1">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Input 3</label>
<div class="col-sm-10">
<input type="text" name="data3" value="" id="data3" class="form-control painting-form1">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Input 4</label>
<div class="col-sm-10">
<input type="text" name="data4" value="" id="data4" class="form-control painting-form1">
</div>
</div>
</div>
You can loop through all input boxes and check if any of the input field is filled with value the add error class to all other empty input boxes.
Try this:
$(document).ready(function() {
$(".submit_data").click(function(){
flag = 0; // check if eny input box is filled with value or not
$("input[type=text]").each(function() {
if($(this).val() != '') {
flag = 1; // set flag one if any of the inputbox has value entered
}
});
if(flag == 0) { // if flag is 0 means all input are empty then remove error class from all inputs
$("input[type=text]").each(function() {
$(this).removeClass('required');
$(this).removeClass('error');
});
}
if(flag == 1) { // if any of the input box is filled with value
$("input[type=text]").each(function() {
if($(this).val() == '') {
$(this).addClass('required'); // add error class to empty inputboxes
$(this).addClass('error');
} else {
$(this).removeClass('error'); // remove error class if inputbox has value
}
});
}
return false;
});
});
Use jquery validation plugin for this.
It's quickly and easy to implement.
Will be something like this
$(form).validate()
If you want to add some rules, like minlength/maxlength and so on .
// Try this
$(form).validate(rules:{
inputname: {
minlength: 8
}
})

JQuery File input validation and hiding div

I have a couple of inputs
<div class="row">
<div class="col-md-6 col-sm-offset-3 file-input">
<div class="input-group">
<input type="text" class="form-control" id="fileOneContainer" readonly>
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Browse… <input type="file" id="fileOne" name="fileOne" class="fileGroup">
</span>
</span>
</div>
</div>
<div class="col-md-6 col-sm-offset-3 file-input">
<div class="input-group">
<input type="text" class="form-control" id="fileTwoContainer" readonly>
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Browse… <input type="file" id="fileTwo" name="fileTwo" class="fileGroup">
</span>
</span>
</div>
</div>
</div>
Now I have to do my own custom validation for this within Javascript. Concentrating only on the first input for now, the rules are:
Cant be empty
Cant be larger than 2MB
Must be one of a certain file type
To handle all this, I came up with the following
var fileOne = $("#fileOne").val();
if(fileOne.length == 0) {
$(this).addClass('error');
errors.push("- Please upload a document");
} else if($("#fileOne")[0].files[0].size > 2097152) {
errors.push("- Please upload a file smaller than 2MB");
} else if( $("#fileOne")[0].files[0].type != 'image/bmp' &&
$("#fileOne")[0].files[0].type != 'image/jpeg' &&
$("#fileOne")[0].files[0].type != 'image/pjpeg' &&
$("#fileOne")[0].files[0].type != 'image/png' &&
$("#fileOne")[0].files[0].type != 'image/tiff' &&
$("#fileOne")[0].files[0].type != 'application/pdf') {
errors.push("- Please upload one of the valid document types");
}
This seems to work, although I imagine it could be improved.
Anyways, I need to now work on the second input. Initially, this input should be hidden, and only displayed when an add more button is clicked. Now I do not really want to hide it via css because this can be altered using developers tools.
The rules for the second input are pretty much the same as above, but this input is not required. This input should only have a value if the first input has a value. So you shouldnt be able to upload a file to the second input unless you have already uploaded one to the first.
What would be the best way to handle this second input to achieve the affect I am after?
Any advice appreciated.
Thanks
UPDATE
So I now have this
var fileInputs = document.querySelectorAll('.fileGroup');
for (var i = 0; i < fileInputs.length; i++) {
fileInputs[i].addEventListener('change', function(event){
error = validateFile(event);
errors.push(error);
});
};
function validateFile(event) {
var input = event.target;
var fileLength = input.files[0].length;
var fileSize = input.files[0].size;
var fileType = input.files[0].type;
if(fileLength == 0) {
$(this).addClass('error');
return("- Please upload a document");
} else if(fileSize > 2097152) {
return("- Please upload a file smaller than 2MB");
} else if( fileType != 'image/bmp' &&
fileType != 'image/jpeg' &&
fileType != 'image/pjpeg' &&
fileType != 'image/png' &&
fileType != 'image/tiff' &&
fileType != 'application/pdf') {
return("- Please upload one of the valid document types");
}
}
The problem is that I need the errors to display once the form has been submitted, not when the fileinput changes. Is there any way to do this without the change event?
Thanks
Try using accept attribute set to ".bmp,.jpeg,.jpg,.pjpeg,.png,.tiff,.pdf" , adding disabled to second input , setting disabled to false at change event handler of first input
var errors = [];
$(document).on("change", "#fileOne, #fileTwo:not(:disabled)", function() {
console.log(this.files);
if (this.files[0].size > 2097152) {
errors.push("- Please upload a file smaller than 2MB");
};
if (this.files.length) {
$("#fileTwo").prop("disabled", false)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-6 col-sm-offset-3 file-input">
<div class="input-group">
<input type="text" class="form-control" id="fileOneContainer" readonly>
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Browse… <input type="file" id="fileOne" name="fileOne" class="fileGroup" accept=".bmp,.jpeg,.jpg,.pjpeg,.png,.tiff,.pdf">
</span>
</span>
</div>
</div>
<div class="col-md-6 col-sm-offset-3 file-input">
<div class="input-group">
<input type="text" class="form-control" id="fileTwoContainer" readonly>
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Browse… <input type="file" id="fileTwo" name="fileTwo" class="fileGroup" accept=".bmp,.jpeg,.jpg,.pjpeg,.png,.tiff,.pdf" disabled="true">
</span>
</span>
</div>
</div>
</div>
I recommend looping through your inputs and binding an on change event listener to validate the file. That way you don't have to repeat logic and you can grab the context via the event.
function validateFile(event) {
var input = event.target;
var fileSize = input.files[0].size;
// rest of validation logic here.
}
var fileInputs = document.querySelectorAll('.fileGroup')
for (var i = 0; i < fileInputs.length; i++) {
fileInputs[i].addEventListener('change', function(event){
validateFile(event);
});
};
The above starter code should put you in the right direction.
EDIT: If you'd like to do it on submit you can write some code like this:
document.forms[index].onsubmit = function() {
validateFile();
}
The index is the index of the form on the page. If there is only one form it most likely is 0.
Here is a fiddle:
http://jsfiddle.net/dgautsch/cep7cggr/

Show div on radio button check

I would like to hide a div until the leased radio button is selected. This div contains input fields only relative to the leased radio selection, so hiding them when the owned radio button is selected is preferred. However, the code I have is not working.
HTML
<div id="surv_radio4">
<p>
Merchant Site Property is
</p>
<input type="radio" id="owned" value="owned" name="merchant_property"/>
<label for="owned">Owned</label>
<input type="radio" id="leased" value="leased" name="merchant_property"/>
<label for="leased">Leased</label>
</div>
<div id="surv_5">
<label for="landlord_name" class="test">Landlord Name</label>
<input type="text" id="landlord_name" placeholder="Landlord Name"/>
<label for="landlord_phone">Phone Number</label>
<input type="text" id="landlord_phone" placeholder="XXX-XXX-XXXX"/>
</div>
CSS
#surv_5 {
display: none;
}
Javascript
<script>
$(document).ready.(function() {
$("input[name$='merchant_property']").click(function() {
var value = $(this).val();
if (value == 'leased') {
$("#surv_5").show();
} else if (value == 'owned') {
$("#surv_5").hide();
}
});
});
</script>
Your document.ready function has a syntax error (extra period):
$(document).ready(function () {
http://jsfiddle.net/isherwood/tW3D5/
Try this:
$("input[name$='merchant_property']").change(function () {
var value = $(this).val();
if (value == 'leased') {
$("#surv_5").show();
} else {
$("#surv_5").hide();
}
});
Fiddle here.
On your original code, you also had an error on your else statement.. See fiddle here
Relevant bits below:
if (value == 'leased') {
$("#surv_5").show();
} else if(value == 'owned'){
$("#surv_5").hide();
}
UPDATE
Too late, looks like #Hiral has an answer for you....

Categories