I am facing problems in Conditional Statements With input Fields Of bootstrap - javascript

Here Is My Logic:
It Didn't Work :(
function ShowDropMenu(){
var numfiled = document.getElementById('numpeple'); //I Want Whenever Someone Enters a Number In Input Field It Should Display The Dropdown Menu?
if (numfiled < 0 ) {
document.getElementById('dropmock').style.display="block"
}
else{
alert('Please Add Atleast 1 Or More People to go ahead)
}
}
I Don't Know What's Went Wrong?

numfiled is an Element, so comparing it with a number won't do anything meaningful.
You want the value of the Element. Additionally, since the value is always a string, you want to parse it as a number. For example:
var numfiled = parseInt(document.getElementById('numpeple').value);
Note: This assumes #numpeple refers to an <input> element, inferred from the comment in the code: "Someone Enters a Number In Input Field"

Related

Validating C#'s Long Variable value in Javascript

I have a form wherein a user can enter a value associated with a nullable long property of my ViewModel. But because I have an 'onblur' event on that text box, I am trying to validate the entered value in my textbox.onblur() event and ensure that it does not exceed the C#'s, long.MaxValue. Here is my "blur" code on that text box.
var value = $(this).val();
console.log(value > 9223372036854775807);
if (value<= 1 || value > 9223372036854775807) {
$('#divValueError').text("Invalid Value!");
return false;
}
But Javascript is returning false on that console.log statement if I enter 9223372036854775808. How do I check if the number entered by the user falls within the limits of a C# long value?
I understand 64 bit numbers are not supported by Javascript. I also could not get my [Range] data annotation on that property to fire before this blur event is called, even though I tried
if (!$(this).valid()) {
return false;
}
Please let me know how I can throw a client side error if the value entered by the user falls outside the boundaries of a C#'s long data type value.
Thanks!
Perfect Answer :
I am Providing example that will solve your problem.
In this , you first have to convert your value in string and then in biginteger.
Reference link added for better guidance.
var valuecompare = BigInt("9223372036854775808");
var valuebase = BigInt("9223372036854775807");
console.log(valuecompare);
console.log(valuebase);
if (valuecompare > valuebase) {
console.log('greater value');
}
else{
console.log('less value');
}
Reference Link : https://www.smashingmagazine.com/2019/07/essential-guide-javascript-newest-data-type-bigint/

How to validate forms (which are generated dynamically)?

Can you please tell me how to do validation in a form which is generated dynamically? I am using one plugin dform.js which converts JSON to form. I am to do that validate of fields.
http://jsfiddle.net/Xe3FG/2/
I take help from this.
https://github.com/daffl/jquery.dform
In my demo, I take 2 number fields. If the user enters a string and go to next field, I need it to display an error in front of the field, "please enter only numbers." I need the same with second field.
Can we do only using drom.js or validation.js?
I am able to validate when user enters data in the field and then press enter.
So I used blur event. It is not a good practice to use blur event on every field. Can you give a different way and a good way to validate?
("#totalRetryCount").blur(function() {
// Number element type returns empty value when NaN
if ( $('#totalRetryCount').val() == '' )
alert('enter a number');
});
$("#totalRepeatCount").blur(function(event) {
// Number element type returns empty value when NaN
if ( $('#totalRepeatCount').val() == '' )
alert('enter a number');
I used these two blur events. I don't want to use these events. Can we do these validations another way?
I've already explained to you how to do this in your last question and provided you with a fully working example which you've seemed to completely ignore. In this case, you would just need to check if the value is an empty string, as that is the default value of a number type input field containing non-numeric data.
Fiddle demo
$("#testSuiteConfigurationform").validate(validateInputParameters());
function validateInputParameters() {
jQuery.validator.addMethod("onlyNumbers", function(value, element) {
return value != "";
}, " Please enter only numbers");
var validation = {
onfocusout : function(element) {
$(element).valid();
},
rules : {
totalRetryCount: { onlyNumbers: true }
},
};
return validation;
};

Javascript: no idea why this solution works

Okay, I'm doing an exercise to learn Javascript, where I need to make a simple Sudoku app. There's a function to create the Sudoku field, and each little square is in a div with an id identifying the row number and column number.
Now the idea is that if a user clicks on an open field, a prompt appears asking him/her to enter a number. If the number is between 1 and 9, that number is then displayed inside the field.
I first invoked the function like this:
node.onclick=function(){fillNumber(this.id);};
This had the unexpected side-effect of making the prompt box appear three times in a row whenever a click was performed. Yet, it was clear that the first input by the user was accepted, stored and added to the div just like it was supposed to. The input from the second and third prompt box is simply lost.
I solved the problem by using the following invocation:
node.onclick=function(){if (parseInt(this.id) > 0) fillNumber(this.id);};
Yet I've no idea why this works (this is copied from a fellow student who did it this way, but doesn't know why). The value of this.id is always something like this: "11", "12", "13", "21", "22", ... So I don't even see the point of first parsing it to an int or checking whether it's bigger than 0. It always is both an int and bigger than 0 as far as I can see. Regardless, the code of the method itself didn't change and the method is invoked with the exact same argument value.
Here's the method fillNumber:
function fillNumber(id){
var input = -1;
do{
input = parseInt(prompt("Enter a number between 1 and 9: ", ""));
}while(input < 1 || input > 10);
var i = parseInt(id/10), j = id%10;
numbers[i][j] = input;
var tekst = document.createTextNode(numbers[i][j]);
document.getElementById(tekst).appendChild(tekst);
}
Can anyone explain this to me?
I may suggest you to check whether there are elements upon each other - this might be the reason for three prompts in a row.
I guess the reason the other student wrote parseInt(this.id) is the same.
He tries to parse an id into an int to escape the other clicked elements, so he makes sure the id is a valid number.
Try to use next lines:
node.onclick=function(e){
if( e.stopPropagation ) e.stopPropagation();
if( e.preventDefault ) e.preventDefault();
else e.returValue = false;
fillNumber(+this.id);
}
Note the + at +this.id parses a string to an integer or a float.

JavaScript/jQuery - Validating based on length

I'm working on a simple form that I need to validate against UK postcodes. No problem there but I need to validate depending on the character length. The user can input only the first half of a postcode (i.e. SW1) or a full postcode (i.e. SW1 1AB).
I thought the best approach would be to check the length on KeyPress and validate against RegEx for either half a postcode or the whole thing. See below:
jQuery('.ValPostCode').keyup(
function(){
if (jQuery(this).length < 5){
jQuery.validator.addMethod("ValPostCode", function(value, element) {
return this.optional(element) || /([A-PR-UWYZa-pr-uwyz]([0-9]{1,2}|([A-HK-Ya-hk-y][0-9]|[A-HK-Ya-hk-y][0-9]([0-9]|[ABEHMNPRV-Yabehmnprv-y]))|[0-9][A-HJKS-UWa-hjks-uw]))/.test(value);
}, "Please enter a valid postcode");
} else if (jQuery('.ValPostCode').length > 4) {
jQuery.validator.addMethod("ValPostCode", function(value, element) {
return this.optional(element) || /^(GIR\\s{0,1}0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])\\s{0,1}[0-9][ABD-HJLNP-UW-Z]{2})$/.test(value);
}, "Please enter a valid postcode");
}
});
So, if the char length of .ValPostCode is less than 5 it validates only for the first half of a UK postcode, else it checks for a full and valid UK postcode.
At one point I was outputting the length of .ValPostCode but it always stopped at 1 (first keypress) and then didn't carry on any further (i.e. wouldn't count up with subsequent keypresses).
I hope I've explained myself clearly enough, please let me know if I'm not being clear.
I've searched for similar problems to try and fix this for myself but I couldn't find anything. Any help appreciated!
The length of $(selector).length (or jQuery(selector).length) will always be the number of elements on the screen that match the given selector. Try using $(selector).val().length to get the value of a form element and check its lenght instead.
It seems as though you are setting up validator rules on every keypress unnecessarily
When the page first loads, you should only need to call something like this:
jQuery.validator.addMethod("ValPostCode", function(value, element) {
if(value.length < 5) {
return (insert partial postcode check here);
} else {
return (insert whole postcode check here);
}
}, "Please enter a valid postcode");
And should only call it once. JQuery will pick up the error on submit/change depending on how it is configured.
So there is no need for a keyUp event.
The main problem you were having (as someone else has already pointed out) is that you were returning the length of the jQuery object rather than the length of its value attribute.

How can I stop isNaN from returning an error for a blank field?

EDIT:
Ok so I'm updating this question, to show what I've built as I've still not been able to fix this issue. Here is an image of what I've got. So as you can see,
When the user enters a value, the calculation (they are just percentage and total calculations are done "onkeyup". As you can see because of this they return "NaN". Is there a way for me to stop the field displaying a NaN and then subsequently only showing the total values?
I have thought about this and I could just get all the fields to calculate as soon as something is input into the final field? What do you think. Apologies to all those that had perviously answered my question, I am still trying to figure out the best approach, I'm just not as good with JavaScript as I am with HTML/CSS!!
You should try writing a checkNumber function that takes the entered value as its argument (rather than referring directly to each field inside the function). Something like this:
var checkNumber = function (testval) {
if ( isNaN(testval) ) {
alert('Bad!');
// clean up field? highlight in red? etc.
} else {
// call your calculation function
}
}
Then bind that function to the keyup event of each form field. There are a number of ways to do this. Look into addEventListener(), or the binding features of a framework like jQuery (.delegate() or .keyup(), e.g.).
Note that if you do bind the function to the event, you won't have to explicitly pass in the value argument. You should be able to work with a field's value within the function via this.value. So you'd have something like this:
var checkNumber = function () {
if ( isNaN( this.value ) ) {
alert('Bad!');
// clean up field? highlight in red? etc.
} else {
// call your calculation function
}
}
And then (with a naive binding approach by ID):
document.getElementById('id_of_a_field').addEventListener('keyup', checkNumber, true);
Can't you just initialize the text box with a default value, say 0?
Why don't you use 3 different functions or an argument to identify which of the inputs the user is pressing? If each of the inputs calls checkNumber(1), checkNumber(2) and checkNumber(3) you can only validate the input that the user is using instead of validating all 3 at the same time.
Alternatively you can use input validation and instead of an alert just return false to prevent the user from inputing invalid chars
How about use short-circuit evaluation with jsFiddle example
EDIT for parseFloat:
function checkNumber()
{
var sInput = parseFloat(document.getElementById('sInput').value || 0);
var dInput = parseFloat(document.getElementById('dInput').value || 0);
var pInput = parseFloat(document.getElementById('pInput').value || 0);
if (isNaN(sInput) || isNaN(dInput) || isNaN(pInput)) {
alert("You entered an invalid character. Please press 'Reset' and enter a number.");
}
}
So if pInput is undefined just use 0, but if the input has value then use that value.
SIDE NOTE: white space is actually a number, +' '; // 0

Categories