issue in disabling submit button using jquery - javascript

i am iterating a list , and displaying its values in textboxes.
there is two textboxes with name checkquantity & quantity whose values i am iterating from a list.
Now users have to enter the quantity values, if they enter the quantity values more then the allocated quantity. Then i have to disable the submit button.
This is my problem:
From my below code , submit button is diasabling for first time only. i.e. if i enter invalid values for first time then my code is working fine but if again i enter valid values in another text-box then my button is enabling. But it should not enable since in first textbox invalid values are entered.
Note: Users can only enter values in textbox name quantity and this textbox will be validated from the textbox checkquantity.
Please check my below code and suggest me a solution for this.
$('input[name="quantity"]').keyup(function() {
var $tr = $(this).closest("tr");
var q = +$tr.find('input[name^="quantity"]').val();
var cq = +$tr.find('input[name^="checkquantity"]').val();
if (q > cq) {
$('#submtbtnId').attr('disabled', 'disabled');
}
else {
$('#submtbtnId').removeAttr('disabled');
}
});
----------------------------------- in
while loop my list is iterating
{
<tr>
<td width = "10%">
<input type = "text" name = "quantity"values = "" id = "quantity" / >
<input type = "text" name = "checkquantity" disable = "disable"
values = "random values coming from my list
eg. 5 or 9 ..." / > < /td>
</tr >
}
-------------------------
< input type = "submit" id = "submtbtnId" / >​

If that's the case every time in the keyup event check all the textboxes by iterating over them..
UPDATE
Looks like the issue is with the attribute named values .
If you are trying to access the value using .val() then it is supposed to be value.
Added the return false; condition to make sure it breaks out of the loop when the condition fails.
Secondly there was one more issue.. Lets say the input is empty .. So when you convert that to a number then it is 0 and the comparison always fails..
So i have added a check condition if the field is not empty , only then convert to the number
$('input[name="quantity"]').on('keyup', function() {
var check = false;
$('tbody tr').each(function() {
var $tr = $(this);
var q = $tr.find('input[name^="quantity"]').val();
if(q != ''){
q = +q;
}
var cq = +$tr.find('input[name^="checkquantity"]').val();
if (q !== '' && q > cq) {
check = true;
return false;
}
});
if (check) {
$('#submtbtnId').prop('disabled', true);
}
else {
$('#submtbtnId').removeAttr('disabled');
}
});​
Check Fiddle

Related

JS->Form validation on inputs. Using for loop to get all the inputs index

I have a form with 4 inputs and I want to show an alert on submit. What I have done is that I have already created the warnings that goes under every input with display:none; in CSS.
After this I have created a for loop in JS to get the index of every input and apply my if statement of showing the the alert if === null || === ""
using a variable to make the querySelector("THE CLASS").style.display="block";
Also on my form I have this line
<form method="post" class="q-form" name="form" onsubmit="return validate()">
My problem is when I submit my form the only alert that is shown is the one under the Username and after it appears it also disappears because I think that the for loop goes to the next input.
Let me know if there is something more to clarify.
Here you have all the code: https://jsbin.com/kazopahuga/1/edit?html,js,output
If you want to see the alert showing press Run with JS
Thank You!
I suggest a few modifications to your validare() function:
Add a flag indicating whether the whole form is valid, assume it's true until you find an input that is invalid. Return the value of this flag.
var isValid = true;
Capture your validation messages too so you can access them by index like your inputs:
messages = document.getElementsByClassName(' alert alert-danger custom');
When you find an invalid input, display the associated message and update the valid flag to false.
if (currentInputValue == null || currentInputValue === "") {
messages[index].style.display = "block";
isValid = false;
}
Here is the updated function:
function validare() {
var inputs, messages, index;
var isValid = true;
inputs = document.getElementsByTagName('input');
messages = document.getElementsByClassName(' alert alert-danger custom');
for (index = 0; index < inputs.length; ++index) {
var currentInputValue = inputs[index].value;
if (currentInputValue == null || currentInputValue === "") {
messages[index].style.display = "block";
isValid = false;
}
}
return isValid;
}
Updated jsbin here
Here is an updated solution: jsbin
You used querySelector which return only the first element it finds with the same class, you should have used querySelectorAll which return all the selectors.

Comparing the value in JavaScript

I am using Javascript/Jquery and I have a dropdownlist. My first index is: "Please select an id". I want to submit the page (return true will submit it) if something is selected, else do not submit it.
<script type="text/javascript">
function Type() {
var id = $("[id$='ddl1']").val();
alert(id); // If something is selected i get the value else I get "Please select an id"
var valid = false;
if (id < 0) {
$("#Type-span").text("*"); //A Span to represent the * if page not submitted
}
else {
valid = true;
$("#Type-span").text("");
}
alert(valid);
}
</script>
It always returns true here, even if i select "Please select an id"
Please, try the below
var id = parseInt($("[id$='ddl1']").val(), 10);
To handle the NaN situation, you need to evaluate that too
if(id != id || id < 0)
and you should have value of element 'Please select an answer' as a blank.
Your issue is that the value attribute of is a string, so, if you are trying to compare it to 0, I'm assuming that it is a number and you will need to convert it to one, before doing the compare.
Change this:
var id = $("[id$='ddl1']").val();
. . . to this:
var id = parseInt($("[id$='ddl1']").val(), 10);
And, if the values of the <options> are not all numbers (with the default being < 0), then you need to make sure that they are. :)

Simple two button counter html jquery javascript

I am new to Jquery and Javascript. I've only done the intros for codeacademy and I have what I remembered from my python days.
I saw this tutorial:
http://www.codecademy.com/courses/a-simple-counter/0/1
I completed the tutorial and thought: "I should learn how to do this with Jquery".
So I've been trying to use what I understand to do so. My issue is that I don't know how to pass an argument for a variable from HTML to Jquery(javascript).
Here is my code:
HTML
<body>
<label for="qty">Quantity</label>
<input id="qty" type = "number" value = 0 />
<button class = "botton">-1</button>
<button class = "botton">+1</button>
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="test.js"></script>
</body>
Jquery/Javascript:
//create a function that adds or subtracts based on the button pressed
function modify_qty(x) {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var qty = $('#qty').val();
var new_qty = qty + x;
//i don't want to go below 0
if (new_qty < 0) {
new_qty = 0;
}
//put new value into input box id-'qty'
$('#qty').html(new_qty)
})
};
$(document).ready(modify_qty);
How do I pass an argument of 1 or -1 to the function? I was using onClick() but that seemed redundant because of the $('.botton').click(function(){}).
Thank you
If you use data attributes on your buttons you can get the value you want.
HTML:
<button class = "botton" data-value="-1">-1</button>
<button class = "botton" data-value="1">+1</button>
JS:
function modify_qty() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var qty = parseInt($('#qty').val());
var new_qty = qty + parseInt($(this).data('value'));
//i don't want to go below 0
if (new_qty < 0) {
new_qty = 0;
}
//put new value into input box id-'qty'
$('#qty').val(new_qty)
})
};
$(document).ready(modify_qty);
More compact JS:
$(function() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var $qty = $('#qty'),
currentValue = parseInt($qty.val());
$qty.val(Math.max(0, currentValue + parseInt($(this).data('value'))));
})
});
Update:
Realized you could do this without the data attributes if want to since your button text is the same as your value.
$(function() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var $qty = $('#qty'),
currentValue = parseInt($qty.val()),
newValue = currentValue + parseInt($(this).text());
$qty.val(Math.max(0, newValue));
})
});
Here's a fiddle to help you grasp the what's going on. Basically, the reference to the element that triggered the event is $(this) or event.target. Things get a bit more complicated with self refence depending on the context you are in, however for $('selector').on('event',function(event){ console.log($(this)) //is the reference to $('selector') });. .attr() -> list of the element's attributes.

Text Box validation through onkeyup event Jquery without using alert

I have the following text box in my html page .
The code which I am using so far is .
<input type="text" id = "points" onkeyup="Validate()">
function Validate(){
var text_value = document.getElementById("points").value;
alert(text_value);
if (!text_value.match(/^[56789]$/) && document.getElementById(called_id).value !="")
{
document.getElementById("points").value="";
// document.getElementById("points").focus();
alert("Please Enter only between 5 and 10 ");
}
}
Accepted values are 5 , 6 , 7 , 8 , 9 and 10 .
I have found the way based on onkeyup event to accept only 5 , 6 , 7 , 8 and 9 .. I want to know how to include 10 there .
Also I want to know the onkeyup event validation for the same using jquery .
If the user gives any other value apart from these it should be given to the right of the text box as "The value should be between 5 and 10 " (not as an alert) .
If the first entered value is 1 , it should wait for the next key pressed . Accept if it is 0 or raise the same error message as in previous case .
Working Jsfiddle
I would prefer without regex:
function validate() {
var num = document.getElementById("points2").value;
var num = parseInt(num, 10);
alert(num);
if (num < 5 || num > 10) {
document.getElementById("points2").value = "";
alert("Please Enter only between 5 and 10 ");
}
}
change your regex to :
/^([5-9]|10)$/
you should use onchange event:
<input type="text" id = "points" onchange="Validate()">
function Validate(){
var text_value = document.getElementById("points").value;
alert(text_value);
if (!text_value.match(/^([5-9]|10)$/) && document.getElementById(called_id).value !="")
{
document.getElementById("points").value="";
// document.getElementById("points").focus();
alert("Please Enter only between 5 and 10 ");
}
}
$('#textbox').keyup(function() {
var value = $('#textbox').val();
if(value != ''){
if(!value.match(/^[5678910]$/))
textboxError();
else{
var length = value.length;
if(value.charAt(length-1) == 0 && value.charAt(length-2) != 1)
textboxError();
}
}
};
$('#textbox').change(function() {
var value = $('#textbox').val();
if(value != '')
textboxError();
}
};
function textboxError(){
$('#textbox').val('');
$('#textbox').focus();
alert("Please Enter only between 5 and 10 ");
}
What we are doing is,
Check if value is empty (If empty don't perform anything)
If not empty check if the value matches to defined set
If it match, now we do check for 10. What we do is if last entered item of field is 0, than the previous field must be 1 so it makes a 10. If not we throw error.
But here is a problem, the user might enter 1 and leave the field without entering another char. So, u can extend this by onchange field.
Onchange, now we check for count of 1 and that should match count of 10. It fixes our problem. You don't have to worry of 0 because we already check it in keyup block.
I Didn't check the code. So if any typos or errors, u can replace them.
As Zaheer Ahmed stated, /^([5-9]|10)$/ will catch 10 as well. For the event listener, you can use
$('#textbox')[0].addEventListener('input', function(event) {
var value = $(event.target).val();
// we already have a reference to the element through the event object,
// crawling the DOM again is expensive.
if(value != '') textboxError();
});
This bypasses jQuery, which may be frowned upon by some, but the 'input' event fires immediately and also works if the text was pasted in or entered by some other method.

Focus on first invalid text field after form validation

I have a pretty standard HTML form in which I collect user input. I have a submit button that will run a JavaScript function (onClick) that in turn validate the data entered by the users.
The function looks like this:
function validateForm()
{
var isValid = true;
var txtFirstname = document.getElementById("firstName").value;
var txtLastname = document.getElementById("lastName").value;
(etc...)
/*Validate First Name*/
if(txtFirstname.length <= 0){
document.getElementById("lblFirstName").innerHTML=" *";
isValid = false;
}
else{
document.getElementById("lblFirstName").innerHTML="";
document.getElementById("firstName").value = txtFirstname;
}
/*Validate last Name*/
if(txtLastname.length <= 0){
document.getElementById("lblLastName").innerHTML=" *";
isValid = false;
}
else{
document.getElementById("lblLastName").innerHTML="";
document.getElementById("lastName").value = txtLastname;
}
(etc...)
if(isValid){
document.formX.submit();
}
else{
return false
}
}
My question is: how can I set the focus on the first "invalid" textbox after the function has validated the form?
Thanks,
Eric
i search 4 it & find a better popular solution :
`$("#"+document.querySelectorAll(":invalid")[1].id).focus();`
it's work for me. note that index of first invalid input in Firefox is 1 not 0. because of in FF the form is invalid and count, when an invalid input exist.
It would be cleaner if you functionally decomposed your validation. Then you could have a variable called "firstInvalidField" which is initially set to null. Upon invalidation of a field, check to see if firstInvalidField is null, if it is, set it to the textBox in question. If it is not null, skip over the code.
After the validation is complete, if the firstInvalidField variable is not null, call .focus() on it.

Categories