I have been trying to make an if argument that will check if several inputs(that have the same class) have a value of negative number on several.
If one of them have, I want to have an error message.
I have been trying to do so, and I got the error message that I wanted but it continues to the next step eventhough I wrote return and event.preventDefault.
My Fiddle
My code below:
$("#inventoryForm").submit(function (event) {
$(".inventoryInput").each(function(){
if($(this).val() < 0) {
event.preventDefault();
$("#inventoryError").slideDown().text("blablabla");
;
return;
}
});
});
Your problem comes from the rest of your code. event.preventDefault() will not return out of the submit handler, it will just prevent the default form submit behavior.
Here's what you can do:
$("#inventoryForm").submit(function (event) {
var error = false;
//You seem to always want to prevent the default behavior
event.preventDefault();
$(".inventoryInput").each(function(){
if($(this).val() < 0) {
error = true; //Indicate there was an error
$("#inventoryError").slideDown().text("blablabla");
return false; //This stops the iteration
}
});
//Stop processing if there was an error
if (error) return;
$("#inventorySubmit").hide();
$("#inventoryChange").show();
$("#withdraw").show();
$(".inventoryInput").attr('disabled','disabled');
sum = 0;
/* var money = table.find("td:nth-child(2)");
for (var i = 0; i<money.length; i++) {
}
*/
});
Btw the code is even more consise without jQuery:
var inputs = [].slice.call(document.querySelectorAll('.inventoryInput'));
if (inputs.some(haveValueUnderZero)) {
//error
}
function haveValueUnderZero(input) { return input.value < 0; }
Try this:
<script>
$(".inventoryInput").each(function(){
var el = $(this)
$("#inventoryForm").on("submit", function (event) {
if(el.val() < 0) {
$("#inventoryError").slideDown().text("blablabla");
return false;
}
})
});
try a hidden verify function:
window.verify = function() {
var valid = true;
$('input').each(function() {
if ($(this).val() == "" || $(this).val() < 0) {
valid = false;
}
});
if (valid) {
$('#submit').click();
} else {
alert("Please complete all fields.");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="inventoryForm">
<input type="text" placeholder="Product Id" name="prod_id" id="prod_id" />
<input type="number" placeholder="Quantity" name="quantity" id="quantity" />
<button type="button" onclick="verify()">Submit</button>
<button id="submit" type="submit" style="display:none"></button>
</form>
You can use a filter function to return only elements that do not match your condition.
var hasErrorElements = $('.inventoryInput').filter(function() {
return parseInt($(this).val()) < 0;
}).length > 0;
if (hasErrorElements) {
alert('Error!');
event.preventDefault();
return false;
}
Try this:
$("#inventoryForm").submit(function (event) {
event.preventDefault();
$(".inventoryInput").each(function () {
if ($(this).val() < 0) {
$("#inventoryError").slideDown().text("blablabla");
return false;
} else {
$("#inventorySubmit").hide();
$("#withdraw").show();
return true;
}
});
});
Also, you need to insert other functions like $("#withdraw").show(); inside the else statement.
JSFiddle Demo
Related
I'm creating my own validation code. I need to separate the if statements per input box for the error to show at the same time. I noticed that if it's on same if block, only the first error will show. Any way to simplify my code?
flag = 0;
//first if
if (first_name.length == 0) {
flag = 0;
$("label[for='firstname'").text('This field is required').css("display", "inline-block");
} else if (!first_name.match(name_regex)) {
flag = 0;
$("label[for='firstname'").text('Firstname must be composed of letters only').css("display", "inline-block");
} else if (first_name.length < 3) {
flag = 0;
$("label[for='firstname'").text('3 letters are required for lastname').css("display", "inline-block");
} else {
flag = +1;
$("label[for='firstname'").hide();
}
//second if
if (last_name.length == 0) {
flag = 0;
$("label[for='lastname'").text('This field is required').css("display", "inline-block");
} else if (!last_name.match(name_regex)) {
flag = 0;
$("label[for='lastname'").text('Lastname must be composed of letters only').css("display", "inline-block");
} else if (last_name.length < 2) {
flag = 0;
$("label[for='lastname'").text('2 letters are required for lastname').css("display", "inline-block");
} else {
$("label[for='lastname'").hide();
flag += 1;
}
//third if
if (validateEmail(email)) {
if (data.result) {
$("input#userEmail").css("border-color", "#ac2925");
$("label[for='email'").text('Email exists').css("display", "inline-block");
} else {
$("input#userEmail").css("border-color", "#e3e3e3");
$("label[for='email'").hide();
flag += 1;
}
} else {
$("input#userEmail").css("border-color", "#ac2925");
$("label[for='email'").text('Please input a valid email address').css("display", "inline-block");;
}
//fourth if on verification success
if (flag == 3) {
alert("All validation succeded!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Just extract it into a function:
function validate(inputName, labelName, minLetters, regex){
const el = $(inputName);
const label = $(labelName);
if(!el || !!label) throw "validate: el not found";
if(!el.val()){
label.text("You need to fill in this!");
return false;
}
if(regex && !el.val().test(regex)){
label.text("The input contains invalid chars!");
return false;
}
if(minLetters && el.val().length < minLetters){
label.text("to short!");
rerurn false;
}
return true;
}
I would suggest to make the validation routine more generic. Please see following solution (note: untested):
function validate(funcName, minLength) {
if (this[funcName].length == 0) {
$("label[for='"+funcName+"'").text('This field is required').css("display", "inline-block");
} else if (!this[funcName].match(name_regex)) {
flag = 0;
$("label[for='"+funcName+"'").text(funcName +' must be composed of letters only').css("display", "inline-block");
} else if (this[funcName].length < minLength) {
$("label[for='"+funcName+"'").text(minLength + ' letters are required for ' + funcName).css("display", "inline-block");
} else {
$("label[for='"+funcName+"'").hide();
return true;
}
return false;
}
if (validate("firstname", 2)
&& validate("lastname", 3)
&& validateEmail(email)
) {
// everything seems to be OK.
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My approaches will be :
Have individual If blocks for each validations by which all the validations will be checked. And build/append the validation error message on each check.
Write if else blocks within a function. That function can be called for each fields being validated. And the function will return validation error message for each invokation which can be appended into a single string.
I have a long form which is broken into sections, and I want to trigger validation via JavaScript only for a particular section. Either I would like to specify the div containing a set of required inputs to validate, or if that's not possible, then loop through a set of known inputs and validate each one in turn. I'm using Bootstrap v3 validation.
Any ideas on how to do this?
you can use this
<?php echo form_open("placead/addCredentials",array("name"=>'form1',"id"=>'formElement','content')); ?>
<div class="halfForm">
<label>First Name</label> <input type="text" name="fname" id="fname" class="formtextBox" value="<?php echo set_value('fname'); ?>">
<span><?php echo form_error('fname'); ?></span>
</div><!--halfForm-->
var errors = false;
$( "#formElement" ).on("submit",function(e) {
$('#formElement .my input, #formElement .my select').each(
function(index){
var input = $(this);
if( (input.attr('type')=='text'|| input.attr('type')=='password') && input.attr('name')!='website' ){
if(input.val()==''){
$(this).parent('.halfForm').find('label').addClass('error');
input.focus();
errors = true;
return false;
}
else{
$(this).parent('.halfForm').find('label').removeClass('error');
errors = false;
}
}
if(input.attr('type')=='email'){
if(!ValidateEmail(input.val())){
$(this).parent('.halfForm').find('label').addClass('error');
input.focus();
errors = true;
return false;
}else{
$(this).parent('.halfForm').find('label').removeClass('error');
errors = false;
}
}
if(input.attr('type')=='tel'){
if(input.val()==''){
$(this).parent('.halfForm').find('label').addClass('error');
input.focus();
errors = true;
return false;
}else{
$(this).parent('.halfForm').find('label').removeClass('error');
errors = false;
}
}
});
if(errors){
e.preventDefault();
return false;
}
});
function ValidateEmail(mail)
{
if(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(mail))
{
return (true)
}
return (false)
}
I've implemented the following in the absence of a Bootstrap Validation solution:
function ValidateAllRequiredFieldsInDiv(divName) {
var valid = true;
var required = $('#' + divName + " :input").filter('[required]');
required.each(function (index, obj) {
var control = $(this);
if (IsControlValid(control)) {
control.removeClass('invalid');
} else {
control.addClass('invalid');
valid = false;
}
});
return valid;
}
function IsControlValid(control) {
var value = control.val();
if (control.is('input') || control.is('textarea')) {
return value != null && value != '';
} else if (control.is('select')) {
return value != null && value != '' && value > 0;
} else {
return true;
}
}
I want to do form.submit() but only if all form items with the required attribute are full.
I was thinking on simpy iterating through the form children in search for the attribute, but I'm not sure how to do it since there might be nested elements and such. And probably there is an easier way to do it.
this.form_is_full = function(form){
for (var i = 0; i < form.elements.length; i++){
if(form.elements[i].getAttribute("required") && form.elements[i].value=="")
{
// If has attribute required and is blank return false
}
}
return true;
}
How can I do this?
function Validate()
{
// create array containing textbox elements
//for example:
var inputs = [document.getElementById('fname'),
document.getElementById('lname'), document.getElementById('email'),
document.getElementById('messagetxt')];
var error;
for(var i = 0; i<inputs.length; i++)
// loop through each element to see if value is empty
{
if(inputs[i].value == '')
{
error = 'Please complete all fields.';
alert(error);
return false;
}
}
}
Try this:
$('#YourFormId').submit(function(e) {
if ($.trim($("#YourFormId input").val()) === "") {
e.preventDefault();
alert('you did not fill out one of the fields');
}
});
This is what I did:
this.validate_form = function(form){
for (var i = 0; i < form.elements.length; i++){
if(form.elements[i].value == "" && form.elements[i].getAttribute("name") && form.elements[i].hasAttribute("required"))
{
return false;
}
}
return true;
}
I have a jquery chat with script
var name = "Guest";
name = name.replace(/(<([^>]+)>)/ig,"");
var chat = new Chat();
$(function() {
chat.getState();
$("#sendie").keydown(function(event) {
var key = event.which;
if (key >= 33) {
var maxLength = $(this).attr("maxlength");
var length = this.value.length;
if (length >= maxLength) {
event.preventDefault();
}
}
});
$('#sendie').keyup(function(e) {
if (e.keyCode == 13) {
var text = $(this).val();
var maxLength = $(this).attr("maxlength");
var length = text.length;
if (length <= maxLength + 1) {
chat.send("testtext", name);
$(this).val("");
} else {
$(this).val(text.substring(0, maxLength));
}
}
});
});
the html structure is;
<body onload="setInterval('chat.update()', 1000)">
<div id="page-wrap">
<h2>jQuery/PHP Chat</h2>
<p id="name-area"></p>
<div id="chat-wrap"><div id="chat-area"></div></div>
<form id="send-message-area">
<p>Your message: </p>
<textarea id="sendie" maxlength = '100' ></textarea>
<button id="submit">submit</button>
</form>
</div>
</body>
This send (or save to file) message when i hit ENTER key after my message. I have replaced text area data with testtext. I want to send data when i click the submit button.
How can i do this??
I am trying to modify this example.. If anybody got a solution, please let me know.. I am trying to add a button instead of default enter key hit.
Thanks in advance...:)
blasteralfred
Use jQuery's ajax() or post(). For example:
$('#submit').click(function() {
$.ajax({
url: myUrl,
cache: false,
dataType: "json",
data: { 'message' : $('#sendie').val() },
success: function(data){
//...
},
error: function(e, xhr){
//...
}
});
});
Just take the code from $('#sendie').keyup(), create a function and call it from $('#sendie').keyup() and $('#send-message-area').submit()
something like this
var name = "Guest";
name = name.replace(/(<([^>]+)>)/ig,"");
var chat = new Chat();
$(function() {
chat.getState();
$("#sendie").keydown(function(event) {
var key = event.which;
if (key >= 33) {
var maxLength = $(this).attr("maxlength");
var length = this.value.length;
if (length >= maxLength) {
event.preventDefault();
}
}
});
$('#sendie').keyup(function(e) {
if (e.keyCode == 13) {
doSend();
return (false);
}
});
$('#send-message-area').submit(function(e) {
doSend();
return (false);
});
});
function doSend(){
var text = $('#sendie').val();
var maxLength = $('#sendie').attr("maxlength");
var length = text.length;
if (length <= maxLength + 1) {
chat.send("testtext", name);
$('#sendie').val("");
} else {
$('#sendie').val(text.substring(0, maxLength));
}
}
You could try to fire event when submiting a form:
$('#sendie').keyup(function(e, extra) {
if (e.keyCode == 13 || extra.keyCode == 13) {
var text = $(this).val();
var maxLength = $(this).attr("maxlength");
var length = text.length;
if (length <= maxLength + 1) {
chat.send("testtext", name);
$(this).val("");
} else {
$(this).val(text.substring(0, maxLength));
}
}
});
...
$("#send-message-area").submit(){
$('#sendie').trigger('keyup', [{keyCode: 13}]);
return false;
}
the line return false is needed to prevent from reloading Your page.
After update Added a new parameter to keyup function named extra, which will hold the keyCode for event fired "manually".
I solved it by removing chat send from main group and included it in trigger click function as below;
$('#trigger').click(function() {
chat.send("testtext", name);
$(this).val("");
});
Thanks to #Kon, #Piotr Salaciak and #Dutchie432 for their support... :)
I have number of checkboxes and another checkbox for "Select All"
I want to check if the user has selected at least one checkbox. Need modification in javascript
<script language="Javascript">
function doSubmit(){
function check_checkboxes()
{
checked=false;
var c = document.getElementsByTagName('INPUT');
for (var i = 1; i < c.length; i++)
{
if (c[i].type == 'checkbox')
{
if (c[i].checked) {
return true}
else {alert("Please identify what warehouses comply:"); }
}
} //if I place my struts action here..its not working?
}
document.holiDay.command.value= 'addingApp'; //My Struts action if something checked.
document.holiDay.submit();
}
var all=document.getElementById('holiDay');
In HTML IDs should be unique, so getElementById will only return 1 element. Perhaps you could try getElementsByTagName - http://msdn.microsoft.com/en-us/library/ms536439(VS.85).aspx ?
Something like...
function check_checkboxes()
{
var c = document.getElementsByTagName('input');
for (var i = 0; i < c.length; i++)
{
if (c[i].type == 'checkbox')
{
if (c[i].checked) {return true}
}
}
return false;
}
and change your Validate function to...
function Validate()
{
if(!check_checkboxes())
{
alert("Please identify what warehouses comply:");
return false;
}
return true;
}
Select at least one check box using jqQery. Try the following code.
$('input[type="checkbox"][name="class"]').on('change', function () {
var getArrVal = $('input[type="checkbox"][name="class"]:checked').map(function () {
return this.value;
}).toArray();
if (getArrVal.length) {
//execute the code
} else {
$(this).prop("checked", true);
alert("Select at least one column");
return false;
}
;
});
(function() {
for(x in $ = document.getElementsByTagName("input"))
with($[x])
return (type == "checkbox" ? checked == true : 0)
})