Trouble getting count of negative number - javascript

I have several inputs in the same class and a function that returns false if any of these inputs are empty. What I am trying to do is return false if any of the inputs are negative numbers. I think there might be a way to do this using a regex but am unsure how to go about it.
This is what I have so far.
var $nonneg = $('.quantity').filter(function(){
return this.value < 0;
});
if ($nonneg.length != 0) {
return false;
}

Probably it should be return this.value =='';

The idea is to check if the value for 3 conditions:
equal === to empty string ""
If coercing the value to a Number results in NaN
If the number (when coerced) is less than zero.
You can use Array.prototype.some() to check your conditions and return the value. Here's an example of how it can work:
$(".check-inputs").on("click", function () {
console.log(anyInvalid());
});
function anyInvalid () {
return Array.prototype.some.bind($(".quantity"))(function (elem) {
return elem.value === "" || isNaN(Number(elem.value)) || Number(elem.value) < 0;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="quantity" value="1"/><br/>
<input type="text" class="quantity" value="2"/><br/>
<input type="text" class="quantity" value="3"/><br/>
<input type="text" class="quantity" value="-4"/><br/>
<input type="text" class="quantity" value=""/><br/>
<button class="check-inputs">Check Inputs</button>

I found a solution that works for me, it returns false if it finds a number less than zero. I was making it out to be more complex than it should have been.
var $nonneg = $('.quantity').filter(function(){
return this.value < 0;
});
if ($nonneg.length != 0) {
return false;
}

Use the Array.prototype.every() function to check that every input in the array passes a given test. First, get the inputs as an array using jQuery's .get(). Then run the elements through Array.prototype.every and it will return false if any elements fail the given test.
function arePositiveOrZero(selector){
return $(selector)
.get() // Convert to array
.every( node => parseInt(node.value) >= 0 ) // Check all elements are >= 0
}
// Tests that log to the console
console.log({hasNeg: arePositiveOrZero('.hasNeg')}) // false
console.log({hasBlank: arePositiveOrZero('.hasBlank')}) // false
console.log({hasZero: arePositiveOrZero('.hasZero')}) // true
console.log({allPos: arePositiveOrZero('.allPos')}) // true
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="hasNeg" type="text" value="1">
<input class="hasNeg" type="text" value="-1">
<input class="hasZero" type="text" value="0">
<input class="hasZero" type="text" value="1">
<input class="hasBlank" type="text" value="1">
<input class="hasBlank" type="text" value="">
<input class="allPos" type="text" value="2">
<input class="allPos" type="text" value="3">
If you don't want to include zero, just change the test function to node => node.value > 0

Related

User must enter a value if a checkbox is checked

I have the following input field and a checkbox:-
<input id="ClientManagerApproval_e565da24-d454-4537-b902-771a37689e9d_MultiChoiceOption_0" type="checkbox">
<input type="text" value="" id="ProjectManHoursUsed_becead30-410d-42de-872e-c12ad4c322b2_$NumberField" title="Man Hours Used" size="11" class="ms-input" style="ime-mode : inactive">
now what i am trying to do inside jQuery, if that if the checkbox is checked then the user must enter a value inside the input field, i tried this but it did not work (the alert will never show!)
if ($("[id^=ProjectManHoursUsed_]").value === "" && $("[id^=ClientManagerApproval_]").is(':checked'))
{
alert("Please enter Man Hour Used before setting the stage to Closure approval");
result = false;
}
JQuery has its own function for getting values. Replace
$("[id^=ProjectManHoursUsed_]").value
by
$("[id^=ProjectManHoursUsed_]").val()
See here:
$("button").on("click", function(){
if ($("[id^=ProjectManHoursUsed_]").val() === "" && $("[id^=ClientManagerApproval_]").is(':checked')){
alert("Please enter Man Hour Used before setting the stage to Closure approval");
result = false;
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="ClientManagerApproval_e565da24-d454-4537-b902-771a37689e9d_MultiChoiceOption_0" type="checkbox">
<input type="text" value="" id="ProjectManHoursUsed_becead30-410d-42de-872e-c12ad4c322b2_$NumberField" title="Man Hours Used" size="11" class="ms-input" style="ime-mode : inactive">
<button>submit</button>
You can achieve the result you're looking by using the following code snippet without needing any jQuery at all:
if (document.querySelector('.chkbx').checked) { // I'd recommend using class instead of id, here chkbx if the class attr of the checkbox input -> class="chkbx"
alert("Please enter Man Hour Used before setting the stage to Closure approval");
result = false;
}
You are trying to check if value is empty when value is undefined. If you want to make sure if there's any value, you can use ! operator. You should use === to make sure for empty string over null.
I just changed your code from $("[id^=ProjectManHoursUsed_]").value === "" to !$("[id^=ProjectManHoursUsed_]").value and it's working fine.
function testMe() {
let result = true
if (!$("[id^=ProjectManHoursUsed_]").val() && $("[id^=ClientManagerApproval_]").is(':checked'))
{
alert("Please enter Man Hour Used before setting the stage to Closure approval");
result = false;
}
return result
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onSubmit="return testMe();">
<input id="ClientManagerApproval_e565da24-d454-4537-b902-771a37689e9d_MultiChoiceOption_0" type="checkbox"/>
<input type="text" value="" id="ProjectManHoursUsed_becead30-410d-42de-872e-c12ad4c322b2_$NumberField" title="Man Hours Used" size="11" class="ms-input" style="ime-mode : inactive"/>
<input type='submit' value="Click"/>
</form>

How to sum up all dynamic inputs in js

How can I get all the sum of these inputs? Sometime they have a value from the database, sometimes no value and needs to be inputted. I'm using jquery for this.
Please see the code below:
$(document).ready(function(){
$('input[name=grade\\[\\]]').on('focus, keyup', function(){
var points = $('input[name=grade\\[\\]]');
var totals = points.get()
.map(function(sel){
return parseFloat(sel.value, 10);
})
.reduce(getSum, 0);
if(points.length == 1){
$('input[name=total]').val($(this).val());
} else if(points.length > 1 && totals < 100){
$('input[name=total]').val(totals);
}
});
function getSum(total, value){
return total + parseFloat(value, 10);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="grade[]" ><br><br>
<input type="text" name="grade[]" ><br><br>
<input type="text" name="grade[]" ><br><br>
<input type="text" name="grade[]" ><br><br>
<input type="text" name="grade[]" ><br><br><br>
Total<br>
<input type="text" name="total" readonly>
</form>
The problem is that parseFloat() returns NaN when the value can't be parsed as a number, and the result of adding up a list that includes some NaN values will be NaN. Which means your if/else that decides whether to display the total won't display it because NaN < 100 is false.
Given that your inputs are empty to start with those items are parsed as NaN.
The simplest fix is to change this line in your .map() function:
return parseFloat(sel.value, 10);
to be:
return parseFloat(sel.value) || 0;
...where the || operator will return the left-hand operand if it is a truthy value, i.e., a number, not NaN or 0, and otherwise return the right-hand operand 0. That is, blank or otherwise non-numeric values will be treated as if they were 0.
You don't need to call parseFloat() again in your getSum() function, because by then you already have numbers.
(Note also that parseFloat() doesn't take a second argument, you've mixed that up with parseInt().)
$(document).ready(function() {
$('input[name=grade\\[\\]]').on('focus, keyup', function() {
var points = $('input[name=grade\\[\\]]');
var totals = points.get()
.map(function(sel) {
return parseFloat(sel.value) || 0; // <-- this is the line that changed
})
.reduce(getSum, 0);
if (points.length == 1) {
$('input[name=total]').val($(this).val());
} else if (points.length > 1 && totals < 100) {
$('input[name=total]').val(totals);
}
});
function getSum(total, value) {
return total + value; // <-- no need for parseFloat() here
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="grade[]">
<input type="text" name="grade[]">
<input type="text" name="grade[]">
<input type="text" name="grade[]">
<input type="text" name="grade[]"><br><br><br> Total
<br>
<input type="text" name="total" readonly>
</form>
(I've removed most of the <br> elements just to avoid having to scroll down to see the total for demo purposes.)

JavaScript Set Default Value on Function Not Working?

Function in JS
function punch(){
var a,b,result;
a=document.getElementById('n1').value;
b=document.getElementById('n2').value;
var x=parseInt(a);
var y=parseInt(b);
result=x+y;
if (result===NaN)
result =0;
I know this condtition is false and it gives output of x+y. On empty fields it always return NaN value
when change it to
if (result!==NaN)
result=0;
Now it becomes true but it gives x+y also 0.
document.getElementById('n3').value=result;
}
HTML Code
<input type="text" id="n1" placeholder="Value 1"/>
<input type="text" id="n2" placeholder="Value 2"/>
<button type="button" onClick="punch()">Click For Answer</button>
<input type="text" id="n3" placeholder="Answer"/>
Nothing, including NaN, is ever === to NaN. In fact one way to test for NaN is to exploit that!
if (result !== result)
result = 0; // must have been NaN!
You can also use isNaN():
if (isNaN(result))
result = 0;

using one function for multiple entries javascript

im trying to take multiple inputs from a user with different element id's and run them through one if else function. here is my code:
Enter the grade and number of credits for course 1:
<input type="text" id="lettergrade1" onchange="lettergrade[0]=numgrade(this.value)";>
<input type="text" id="credithour1" onchange="credhour[0]";>
etc... this extends down to lettergrade 5. I have to run them through the function numgrade (without using a for loop). how do I run these through the same if else construct without making 5 different ones (how can I make one statement that will work for 5 diffferent id's)?
Iterate through the elements and bind them to the onchange callback:
var $ = document;
var lettergrade = [];
[].slice.call($.querySelectorAll('.lettergrade')).forEach(function(el, index) {
el.onchange = function() {
numgrade(index, this.value);
}
});
function numgrade(index, value) {
lettergrade[index] = value;
$.getElementById('output').innerText = JSON.stringify(lettergrade);
}
<input type="text" class="lettergrade" id="lettergrade1" placeholder="1">
<input type="text" class="lettergrade" id="lettergrade2" placeholder="2">
<input type="text" class="lettergrade" id="lettergrade3" placeholder="3">
<input type="text" class="lettergrade" id="lettergrade4" placeholder="4">
<input type="text" class="lettergrade" id="lettergrade5" placeholder="5">
<output id="output"></output>

Javascript validation for multiple textboxes

I am having some trouble figuring out how to validate my textboxes using js. I have 10 textboxes, the user can fill out any number 1-10, but cant fill out 0. Here is the js that I have written, but it only returns true if all 10 textboxes are filled, rather than just checking if one is filled.
function submitIt() {
if (document.isForm.Student_ID.value == null) {
alert ("You must enter a Colleague ID.");
return false;
} else {
return true;
}
}
And here is the form.....
<form name="isForm" onSubmit="return submitIt()">
<input name="Student_ID" type="text" id="idField1" />
<input name="Student_ID" type="text" id="idField2" />
<input name="Student_ID" type="text" id="idField3" />
<input name="Student_ID" type="text" id="idField4" />
<input name="Student_ID" type="text" id="idField5" />
<input name="Student_ID" type="text" id="idField6" />
<input name="Student_ID" type="text" id="idField7" />
<input name="Student_ID" type="text" id="idField8" />
<input name="Student_ID" type="text" id="idField9" />
<input name="Student_ID" type="text" id="idField10" />
<input name="SUBMIT" type="submit" />
</form>
I realize that I could change all of the names, and check each one, but I am trying to avoid that much clutter in my code, and am curious the best way to do this. Any help is appreciated, thanks!
You can get a collection of all these textboxes with document.getElementsByName. Then loop through them, and make sure at least one is filled in:
var allTbs = document.getElementsByName("Student_ID");
var valid = false;
for (var i = 0, max = allTbs.length; i < max; i++) {
if (allTbs[i].value) {
valid = true;
break;
}
}
DEMO
Function is iterating by all of the student text boxes and return true if some element is filled out. Protected against that if input contain only spaces :)
function submitIt() {
for( var i = 0, t = document.getElementsByName( "Student_ID" ), l = t.length; i < l; i++ )
if( t[i].value && !/^\s+$/.test( t[i].value ) )
return true;
return false
}
Demo on: http://jsfiddle.net/hhD2x/
you can use jquery.
add common class name for all your textboxes i.e.
<input name="Student_ID" type="text" id="idField1" class="student" />
now in js function
function submit()
{
$('.student').each(function() {
if($(this).val() == '' || $(this).val() == null)
{
// your error message
return false;
}
}
}
this function check all the elements with student class.
$('input[type="text"], select,
:input[type="date"],
:input[type="email"],
:input[type="radio"]').each(function () {
if ($.trim($(this).val()) == '' ) {
// your error message here
isValid = false;
}
});

Categories

Resources