Troubleshooting JS conditional - javascript

I've been troubleshooting a form that allows for users to select an amount or select other amount. The other amount when clicked changes the amount to $5. I'm trying to get get it so that if say the user tries to enter a number such as 10, 15 or 20 as examples it will allow them to type it. Currently it is converting anything less than 5 for the starting number to 5 which makes it impossible.
$("#donrAmountInput").on("input", function() {
setDonrAmount("Other");
});
function setDonrAmount(id) {
var amt;
$('#donrAmountButtons .active').removeClass('active');
if (id == "Other") {
amt = $("#donrAmountInput").val() > 5 ? $("#donrAmountInput").val() : 5;
$('#otherAmount button').addClass('active');
}
else {
amt = id.substring(10);
$('#donrAmount' + amt).addClass('active');
}
$('input#donrAmountInput').val(amt);
$('input#donrAmountInput').change();
$('#donrReviewAmount').html(amt);
}
For reference here's the actual form. Help would be greatly appreciated. https://secure.pva.org/site/c.ajIRK9NJLcJ2E/b.9381225/k.8668/FY2016_March_Congressional/apps/ka/sd/donorcustom.asp

You can set your input type to number specify min,max,required attributes and then check the validity of it via javascript/jQuery.
function myFunction() {
var inpObj = $("#id1")[0];
if (inpObj.checkValidity() === false) {
$("#demo").html(inpObj.validationMessage);
} else {
$("#demo").html(inpObj.value);
}
}
$('button').on('click',function(){
myFunction();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="id1" type="number" min="5" max="300" required>
<button>OK</button>
<p id="demo"></p>

Related

Very new to Javascript. Can't seem to get 1 function to work in my code (berekenBedrag). Needs to calculate the total

I'm struggling with the same code for days now and it's becoming frustrating.
I checked youtube, google, read in Flanagan but I can't seem to find the answer.
Now, I believe I came to the end of my code but one function I don't get to work.
I need to have 1 input text were the user puts in an amount, presses enter and the total needs to go to input text 2.
After each input, the input from text 1 needs to get emptied.
Everything works except for calculating the total in input text 2.
Thanks for reading and appreciate the help.
This is my code:
<!DOCTYPE html>
<html>
<body>
<input type="text" id="input1"><br><br>
<input type="text" id="input2">
<script>
document.getElementById("input1").addEventListener("keyup", function(e) {
if ( e.keyCode === 13) {
myFunction();
}
});
function myFunction() {
var bedrag = leesInvoer("input1");
document.getElementById("input1").value="";
document.getElementById("input2").value = berekenBedrag(bedrag).toFixed(2) +
" euro";
}
function berekenBedrag(pBedrag) {
var input = document.getElementById("input2");
pBedrag = pBedrag+input;
//This function is wrong but I don't know how to calculate the total from input 1 and 2 together.
return pBedrag;
}
function leesInvoer(invoerId) {
var invoer = document.getElementById(invoerId);
var getal = +invoer.value;
return getal;
}
</script>
</body>
</html>
Put the " euro" outside the input
Parse the number
Disable the other field from accepting input
Use "change" in case they use another input method (tab off, hit "enter" or some other way (click off) etc.
Reset the input value where you got it (I used null but that is a style choice)
document.getElementById("input1")
.addEventListener("change", function(e) {
//if (e.keyCode === 13) {
myFunction();
//}
});
function myFunction() {
var bedrag = leesInvoer("input1");
document.getElementById("input2").value = berekenBedrag(bedrag).toFixed(2);
}
function berekenBedrag(pBedrag) {
let input = document.getElementById("input2");
pBedrag = pBedrag + (input.value * 1);
return pBedrag;
}
function leesInvoer(invoerId) {
let invoer = document.getElementById(invoerId);
let getal = !isNaN(parseFloat(invoer.value)) && isFinite(invoer.value) ? parseFloat(invoer.value) : 0;
invoer.value = null;
return getal;
}
<div><input type="text" id="input1"></div>
<div>
<input type="text" id="input2" disabled><span> euro</span></div>
You can use a global variable to store the total (which starts at 0) and add the value of the input after converting to a number (using the unary plus operator) each time.
document.getElementById("input1").addEventListener("keyup", function(e) {
if (e.keyCode === 13) {
myFunction();
}
});
let total = 0;
function myFunction() {
var bedrag = +document.getElementById("input1").value;
total += bedrag;
document.getElementById("input1").value = "";
document.getElementById("input2").value = total.toFixed(2) +
" euro";
}
<input type="text" id="input1"><br><br>
<input type="text" id="input2">

javascript function retrieve input[type=number] and filter them based on the value

I have several input fields of type number, which users have to fill in. I need a script that will display a new page only once users have at least one non-zero value for these fields. So I need a function that checks that at least one input of type number is larger than zero.
Below is the function, in the script, that I wrote to attempt to implement this conditional page-switching (it calls another function which works and I am not showing here). The issue is with var filledValue. It returns undefined. I would like it to get all input elements of type number that have a raw value larger than 0 and return the id of that element. If the resulting variable is non-empty, then move on.
function NextTrial() {
var filledValue = $("input[type=number].val()>0",
"#page" + order[currentTrial]).id;
if (filledValue) {
$("#page" + order[currentTrial]).hide();
currentTrial++;
ShowTrial(currentTrial);
} else {
alert('Please answer the question before moving on!');
}
}
A sufficient excerpt of the HTML is:
<div id="answercol1">
<p><big>Government:</big></p>
<div class="fieldEntry"><label for="gvt">federal (USA)</label> <input id="fedgvt" min="0" name="fedgvt" size="4" type="number" value="0"></div>
<div class="fieldEntry"><label for="gvt">state or local</label> <input id="stategvt" min="0" name="stategvt" size="4" type="number" value="0"></div>
<div class="fieldEntry"><label for="tribalgvt">tribal</label> <input id="tribalgvt" min="0" name="tribalgvt" type="number" value="0"></div>
</div>
The function that I ended up using is:
function NextTrial() {
var answers = 0;
$("input[type=number]").each(function(){
if ($(this).val()>0) {
answers++
}
})
if (answers>0){
$("#page" + order[currentTrial]).hide();
currentTrial++;
ShowTrial(currentTrial);
} else {
alert('Please answer the question before moving on!');
}
}
You have an invalid code and it's not clear what you're trying to achieve,I'm not sure if that really what you want but try the following :
function NextTrial() {
//"#page" + order[currentTrial]).id; //Not sure what this line is used for
var currentTrial = 0;
$("input[type=number]").each(function(){
if ($(this).val()>0) {
$("#page" + order[currentTrial]).hide();
currentTrial++;
ShowTrial(currentTrial);
} else {
alert('Please answer the question before moving on!');
}
})
}
That will loop through all the fields with type number and check if the value of everyone is >0.
Hope this helps.
var ids = ['fedgvt', 'stategvt', 'tribalgvt'];
function GetValidInputs(inputIds){
//ids to return
var rets = [];
//loop through given inputs
inputIds.each(function(id){
//get input value of each based on their id
var val = ("#"+id).val() > 0;
//ternary: if value is > 0 push it to array GetValidInputs returns
//else do nothing
val > 0 ? rets.push(val) : 0;
};
//return desired ids
return rets;
};
//call it and see if it works
GetValidInputs(ids);
Something like the above would work if i'm understanding your question.
edit: added comments for clarity

Add another condition to Show/Hide Divs

I have the follow script on a form.
jQuery(document).ready(function($) {
$('#bizloctype').on('change',function() {
$('#packages div').show().not(".package-" + this.value).hide();
});
});
</script>
Basically, depending on the value of the select box #bizloctype (value="1","2","3" or "4") the corresponding div shows and the rest are hidden (div class="package-1","package-2","package-3", or "package-4"). Works perfectly.
BUT, I need to add an additional condition. I need the text box #annualsales to be another condition determining which div shows (if the value is less than 35000 then it should show package-1 only, and no other packages.
I think the below script works fine when independent of the other script but I need to find out how to marry them.
<script>
$("#annualsales").change(function(){
$(".package-1,.package-2,.package-3,.package-4").hide();
var myValue = $(this).val();
if(myValue <= 35000){
$(".package-1").show();
}
else
{
$(".package-2").show();
}
});
</script>
Help please?
I would remove the logic from the anonymous functions and do something like this:
// handle display
function displayPackage( fieldID ) {
var packageType = getPackageType(fieldID);
$('#packages div').show().not(".package-" + packageType).hide();
}
// getting the correct value (1,2,3 or 4)
function getPackageType( fieldID ) {
// default displayed type
var v = 1;
switch(fieldID) {
case 'bizloctype':
// first check it annualsales is 1
v = (getPackageType('annualsales') == 1) ?
1 : $('#' + fieldID).val();
break;
case 'annualsales':
v = (parseInt($('#' + fieldID).val(),10) <= 35000) ? 1 : 2;
break;
}
return v;
}
jQuery(document).ready(function($) {
$('#bizloctype,#annualsales').on('change',function() {
displayPackage($(this).attr('id'));
});
});
If I understand your question properly, try this code out. It first adds an onChange listener to #annualsales which is the code you originally had. Then, for the onChange listener for #bizloctype, it simply checks the value of #annualsales before displaying the other packages.
jQuery(document).ready(function($) {
// Check value of #annualsales on change
$("#annualsales").change(function(){
$(".package-1,.package-2,.package-3,.package-4").hide();
var myValue = $(this).val();
if(myValue <= 35000){
$(".package-1").show();
}
// Only show other packages if value is > 35000
$('#bizloctype').on('change',function() {
$(".package-1,.package-2,.package-3,.package-4").hide();
if ($('#annualsales').val() <= 35000) {
$(".package-1").show();
} else {
$('#packages div').show().not(".package-" + this.value).hide();
}
});
});
Since you already use JQuery you can use the data() function to create a simple but dynamic condition system. For example, you could annotate each element with the required conditions and then attach change listeners to other elements to make the condition active or inactive for the elements.
For example, with this HTML:
<div id="conditions">
Condition 1: <input type="checkbox" id="check1" /> <= check this<br/>
Condition 2: <input type="checkbox" id="check2" /><br/>
Condition 3: <input type="text" id="value1" /> <= introduce 1001 or greater<br/>
Condition 4: <input type="text" id="value2" /><br/>
</div>
<p id="thing" data-show-conditions="check1 value1-gt-1000"
style="display: none;">
The thing to show.
</p>
And this Javascript:
function setShowCondition(el, condition, active) {
var conditions = $(el).data('conditions') || {};
conditions[condition] = active;
$(el).data('conditions', conditions);
var required = ($(el).data('show-conditions') || "").split(" ");
var visible = required.every(function (c) {
return conditions[c];
});
if (visible) {
$(el).show();
} else {
$(el).hide();
}
}
$("#conditions input[type='checkbox'").change(function () {
setShowCondition('#thing',
$(this).attr('id'),
$(this).is(':checked'));
});
$("#value1").change(function () {
var number = parseInt($(this).val());
setShowCondition('#thing', 'value1-gt-1000', number > 1000);
});
You can maintain conditions easily without having to nest and combine several if statements.
I've prepared a sample to show this in https://jsfiddle.net/2L5brd80/.

if input field is not a number OR not empty replace with a number

I have an input field that I am monitoring for changes using an .on('input') function as this covers .change and .keyup.
There is no submit button yet I just want to change the behaviour of the input field depending on what is entered.
I will validate server side later and I'm using html5 type='number'.
I only want the field to be able to hold a number, or it can be empty. The user might want to empty the contents to type the number 15 for example.
However I don't want any other characters to be accepted - if they are entered, a prompt should show notifying the user of this and the field is defaulted back to it's starting value of 1.
HTML
<input type="number" class="input-field" placeholder="" value="1" min="1">
JS
$(document).ready(function ($) {
var num = $('input[type="number"]').val();
$('input[type="number"]').on('input', function () {
var num = $(this).val();
if (num < 1 || isNaN(num) || num !== '') {
alert(num + ' is not a number or is less than 1');
$(this).val(1);
}
});
});
I have tried with the above code and it doesn't allow for an empty field. I've also tried if (num < 1 || isNAN(num) || num.length != 0) {
do I need to use .replace() with a Regexr. I've been looking at a few questions on here like here but I'm not sure thats what I'm looking for considering I'm testing for an empty string.
JSFIDDLE
You can use the constraint validation API:
$('input[type="number"]').on('input', function () {
if (!this.validity.valid) {
alert(this.value + ' is not a number or is less than 1');
this.value = 1;
}
});
$('input[type="number"]').on('input', function () {
if (!this.validity.valid) {
alert(this.value + ' is not a number or is less than 1');
this.value = 1;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" class="input-field" placeholder="" value="1" min="1">
However, note that this behavior is obtrusive. If an user types the wrong key, you will annoy him with a modal dialog and will clear the number.
Consider doing nothing. HTML5 browsers won't send the form if the input is not valid.
The HTML5 answer is definitely more elegant.
But if you want to offer more support, this is usually the route I take when trying to verify numbers.
Note that I am using data-min attribute but if you want to switch you can always use $.attr() to grab your min="" attribute.
$(document).ready(function ($) {
$('input[type="number"]').on('change', function () {
var min = parseInt(this.dataset.min),
num = isNaN(parseInt(this.value)) ? 0 : parseInt(this.value),
clamped = Math.max(num, min);
if(num != clamped) {
alert(num + ' is less than 1');
this.value = clamped;
}
});
});
jsfiddle

Comparing two input fields

I have this function which i am using to compare two input fields. If the user enters the same number in both the text field. On submit there will be an error. Now i would like to know if there is a way to allow same number but not higher than or lower the value of the previous text box by 1. For example if user enters 5 in previous text box, the user can only input either 4, 5 or 6 in the other input field.Please give me some suggestions.
<script type="text/javascript">
function Validate(objForm) {
var arrNames=new Array("text1", "text2");
var arrValues=new Array();
for (var i=0; i<arrNames.length; i++) {
var curValue = objForm.elements[arrNames[i]].value;
if (arrValues[curValue + 2]) {
alert("can't have duplicate!");
return false;
}
arrValues[curValue] = arrNames[i];
}
return true;
}
</script>
<form onsubmit="return Validate(this);">
<input type="text" name="text1" /><input type="text" name="text2" /><button type="submit">Submit</button>
</form>
A tidy way to do it which is easy to read:
var firstInput = document.getElementById("first").value;
var secondInput = document.getElementById("second").value;
if (firstInput === secondInput) {
// do something here if inputs are same
} else if (firstInput > secondInput) {
// do something if the first input is greater than the second
} else {
// do something if the first input is less than the second
}
This allows you to use the values again after comparison as variables (firstInput), (secondInput).
Here's a suggestion/hint
if (Math.abs(v1 - v2) <= 1) {
alert("can't have duplicate!");
return false;
}
And here's the jsfiddle link, if you want to see the answer
Give them both IDs.
Then use the
if(document.getElementById("first").value == document.getElementById("second").value){
//they are the same, do stuff for the same
}else if(document.getElementById("first").value >= document.getElementById("second").value
//first is more than second
}
and so on.

Categories

Resources