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.
Related
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
Can you please take a look at this Demo and let me know why I am not able to do the calculation check using the each iterator?
As you can see I tried to use :
if (!parseInt($(this).val()) === ((parseInt($(this).closest('div').find('.upper').text())) - parseInt($(this).closest('div').find('.lower').text()))) {}
Which it didnt work then I used this :
if (!parseInt($(this).val()) === ((parseInt($(this).prev('.upper').text())) - parseInt($(this).prev('.lower').text()))) {
but still not validating the input?
I'm not sure if that what you want to achieve, take a look at following example :
$('#test').on('click', function (e) {
$("input").each(function () {
if ($(this).val().length === 0)
{
$(this).addClass('input-error');
} else {
var upper = parseInt($(this).prev().prev().text());
var lower = parseInt($(this).prev().text());
var current_value = parseInt($(this).val());
if (current_value != (upper-lower)){
$(this).addClass('input-error');
}else{
$(this).removeClass('input-error');
}
}
});
});
.input-error {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="upper">5</div>
<div class="lower">2</div>
<input type="text" id="txt1">
<hr />
<div class="upper">7</div>
<div class="lower">3</div>
<input type="text" id="txt2">
<hr />
<div class="upper">200</div>
<div class="lower">66</div>
<input type="text" id="txt3">
<hr />
<br />
<button type='button' id="test">Test</button>
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/
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
}
};
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....