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. :)
Related
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.
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.
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
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.
I have this javascript which is working great -
var employeename = $("#employeename");
var employeenameInfo = $("#employeenameInfo");
employeename.blur(validateEmployeename);
function validateEmployeename(){
//if it's NOT valid
if(employeename.val().length < 4){
employeename.addClass("error");
employeenameInfo.text("We want names with more than 3 letters!");
employeenameInfo.addClass("error");
return false;
}
//if it's valid
else{
employeename.removeClass("error");
employeenameInfo.text("Full Name.");
employeenameInfo.removeClass("error");
return true;
}
}
However instead of having a big list of this functions for all my different fields I want to pass a field in e.g.
function validateGeneric(field){
However whatever I try just gives me errors and I'm really stuck. Any help appreciated. This also brings up another problem with the info field, any way I can store the orginal text and just restore that instead of a new string?
You can get the field that triggered the event using $(this). also you should put the info field as a sibling with an info class
$('input.to_be_validated').blur(validateInput);
function validateInput(e){
var input = $(this)
var info = input.parent.find('.info')
//if it's NOT valid
if(input.val().length < 4){
input.addClass("error");
info.text("We want names with more than 3 letters!");
info.addClass("error");
return false;
}
//if it's valid
else{
input.removeClass("error");
info.text("Full Name.");
info.removeClass("error");
return true;
}
}
Edit: forgot about the info field
All you need to do is to reference the field var you'd pass into your function, therefore your code becomes:
function validateEmployeename(field, fieldinfo){
//if it's NOT valid
if(field.val().length < 4){
field.addClass("error");
fieldinfo.text("We want names with more than 3 letters!");
fieldinfo.addClass("error");
return false;
}
//if it's valid
else{
field.removeClass("error");
fieldinfo.text("Full Name.");
fieldinfo.removeClass("error");
return true;
}
}
You may also use multiple selectors:
$("input[name='employeename'], input[name='employeename2']").blur(function() {
// put your validation routine for fields that should contain names
$(this).next("#employeenameInfo").html("info here"); // note that you don't have unique id here, better to find element you want to put your error message by tagname/class, like "span.error"
});
$("input[name='employeemail'], input[name='employeemail2']").blur(function() {
// put your validation routine for fields that should contain email addresses
$(this).next("#emailInfo").html("info here"); // note that you don't have unique id here, better to find element you want to put your error message by tagname/class, like "span.error"
});
That way you don't need to pass anything to validation functions, everything will be resolved around $(this), providing you've got proper elements to fill your error messages nearby:
<input type="text" name="employeename" />
<span class="error" />