How to Validate Text box on depend of another Text box? - javascript

I am Performing Calculation of Student fee Details,There are Two Text boxes,one which is automatically fixed(disabled)as Rs.5000,If i enter value below Rs.5000 value on another Text box then it will calculate subtraction and show balance in result text box.If i enter value above Rs.5000 it should not take that value in second text box.I want to validate text box depending on first text box value.
Here is my body part
my script part
$(".maxmin").each(function () {
var thisJ = $(this);
var max = thisJ.attr("max") * 1;
var min = thisJ.attr("min") * 1;
var intOnly = String(thisJ.attr("intOnly")).toLowerCase() == "true";
var test = function (str) {
return str == "" || /* (!intOnly && str == ".") || */
($.isNumeric(str) && str * 1 <= max && str * 1 >= min &&
(!intOnly || str.indexOf(".") == -1) && str.match(/^0\d/) == null);
// commented out code would allow entries like ".7"
};
thisJ.keydown(function () {
var str = thisJ.val();
if (test(str)) thisJ.data("dwnval", str);
});
thisJ.keyup(function () {
var str = thisJ.val();
if (!test(str)) thisJ.val(thisJ.data("dwnval"));
})
});

You can do on textchanged something like this
$(textbox1).on('change', function () {
if(textbox1.val()==5000){
//do your code
}
else if(textbox1.val()<5000){
//do your code
}
});

Look into the onchange (https://api.jquery.com/change/) or keyup events (https://api.jquery.com/keyup/). Get the values and perform your calculations.

Related

how to prevent a key input from appearing in input field?

I am trying to validate user input in a text input field.
I have written a javascript function for the same purpose which fires on onkeyup event.
The goal is to only allow user input if it's a numeric value less than 100 and with at most 1 decimal place.
The function is working fine but if a enter an invalid character ,say 'a', it will flash in the input box before being removed.
What I want is that if the entered character violates the defined condition it should not appear in the input box (as it is flashing right now for a split second).
Here's my code:
function validatePercent(event) {
var txt = $("#tds_input").val();
// alert(event.source);
if (!parseInt(txt)) {
$("#tds_input").val('');
}
if (isNaN(txt / 1)) {
txt = txt.substr(0, txt.length - 1);
$("#tds_input").val(txt);
}
if (txt > 100) {
//alert(2);
txt = txt.toString();
txt = txt.substr(0, txt.length - 1);
$("#tds_input").val(txt);
}
txt = txt.toString();
if (txt.indexOf('.') > -1) {
if (txt.substr(txt.indexOf('.') + 1, txt.length).length > 1) {
txt = txt.substr(0, txt.length - 1);
$("#tds_input").val(txt);
}
}
}
Using type=number (and not text) can help
function validatePercent(event)
{
var txt=$("#tds_input").val();
if(!parseInt(txt))
{
$("#tds_input").val('');
}
if(isNaN(txt/1))
{
txt=txt.substr(0,txt.length-1);
$("#tds_input").val(txt);
}
if(txt>100)
{
txt=txt.toString();
txt=txt.substr(0,txt.length-1);
$("#tds_input").val(txt);
}
txt=txt.toString();
if(txt.indexOf('.')>-1)
{
if(txt.substr(txt.indexOf('.')+1,txt.length).length>1){
txt=txt.substr(0,txt.length-1);
$("#tds_input").val(txt);
}
}
}
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id = "tds_input" onkeyup="validatePercent()">
UPDATED
You could store the value of the when the focus is in the input.
When the user enters a valid percentage (integer only), replace the value stored. When inputs is incorrect, just replace with the old value.
var decimalSeparator = 1.1.toLocaleString().replace(/\d/g, ''),
pattern1 = "^(\\d{1,3})?([",
pattern2 = "]?\\d{1})?$",
regex = new RegExp(pattern1+decimalSeparator+pattern2),
resetContent = function () {
$('#tds_input').val($('#tds_input').data('val'));
},
matchRegex = function (value) {
return value.match(regex);
};
$('#tds_input').bind('focusin', (e) => {
$('#tds_input').data('val', $('#tds_input').val());
});
// handle input (keys, paste)
$('#tds_input').bind('input', (e) => {
let txtValue = $('#tds_input').val();
// input is empty
if (txtValue === "") {
$('#tds_input').data('val', "");
return;
}
// value does not match regex
if (!matchRegex(txtValue)) {
// maybe it ends with the decimal character?
if (txtValue[txtValue.length - 1] === "." && txtValue !== "100.") {
// simulate the user enters a decimal next
if (matchRegex(txtValue + "1")) {
$('#tds_input').data('val', txtValue);
return;
}
}
resetContent();
return;
}
// check between 0 and 100
let value = parseFloat(txtValue);
if (value >= 0 && value <= 100) {
// store new valid number
$('#tds_input').data('val', value);
// put the value as an integer in the input
$('#tds_input').val(value);
return;
} else resetContent();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="tds_input"/>

Input removing leading 0

I have a form input field.
<input style="text-align:right;" type="text" name="DiversionCalc_Diversion_Rate" id="calc_dr" value="0.25%" />
I am attempting to format it based on focusout using jQuery 1.7.2
$('#calc_dr').focusout(function () {
var value = $.trim($(this).val()).toString();
if (value.indexOf("0.") === -1) {
var $t = ("0" + value).toString();
alert($t);
$(this).val($t);
}
if (value != '' && value.indexOf("%") === -1) {
$(this).val(value + '%');
}
});
While this mostly is working, the alert pops up the correct 0.25 when I enter .25 in the field, however, the $(this).val only ever shows .25
How can I get it to show what it's showing me in the alert???
Make $t a global variable (pull it out of the if loop) and assign it instead of value.
$('#calc_dr').focusout(function () {
var value = $.trim($(this).val()).toString();
var $t = value;
if (value.indexOf("0.") === -1) {
$t = ("0" + value).toString();
alert($t);
$(this).val($t);
}
if ($t != '' && $t.indexOf("%") === -1) {
$(this).val($t + '%');
}
});
The basic idea is to grab the value, manipulate the value, then update the UI. The key being there is only one update at the end.
// Get the new value (strip everything but numbers and period)
var v= parseFloat($(this).val().toString().replace(/[^0-9\.]+/g, ""));
// Basic data type validation
if (isNaN(v)) v= 0;
if (v< 0) v= 0;
if (v> 100) v= 100;
// other validation updates v as needed...
doCheckDiversionRate(v);
// update UI (btw toFixed() will add a leading zero)
$(this).val(v.toFixed(2) + '%');

JS can't get my true/false function to display the false output only the true output

I need to write a good that will validate if a number is in between a range of two numbers I can only get the number is valid output no matter what i input in my text box.
function validInputRange(min, max, textbox) {
if (textbox >= min && textbox <= max) {
return true;
} else {
return false;
}
}
function btnValidate_onclick() {
// assign textbox elements to variables for easier access
var numberTextbox = document.getElementById("txtNumber");
var input = parseFloat(numberTextbox.value);
var output = validInputRange(1, 49, numberTextbox.value);
if (output = true) {
var answer = "valid";
numberTextbox.style.backgroundColor = "#00ff00";
} else {
answer = "false";
numberTextbox.style.backgroundColor = "#ff0000";
}
numberTextbox.value = answer;
}
Instead of
if (output = true)
Just do
if (output)
or
if (output == true)
= is used for assignment, while == or === for comparing.

How to get the text between two special symbols(%) in a textarea?

How can i get the text between two % symbols in a textarea ??? I tried using jquery .keypress() event and got the result upto a certain level. But the keypress event will not get triggered if i delete or press backspace. If i go with .keyup() or .keydown(), how to detect the "%" character ... Here is what i tried out
var flag = false,
string = '';
$("#target").keypress(function(event) {
// console.log(event,String.fromCharCode(event.keyCode));
if ( event.which == 37 ) {
if(flag === true){
flag = false;
alert("REsult: "+ string.slice(1));
}
flag= true;
}
// console.log(flag, event.which);
if(flag === true){
string = string + String.fromCharCode(event.which);
}
console.log(string);
});
Here is the bin
Am i going in the right path or is there any other better way... Please help me with your suggestions
try this,
var test_str = "text to get % Other text.... migh have % s ...";
var start_pos = test_str.indexOf('%') + 1;
var end_pos = test_str.indexOf('%',start_pos);
var text_to_get = test_str.substring(start_pos,end_pos)
alert(text_to_get);
How can i get the text between two % symbols in a textarea ???
var matches = /%([^%]*)%/.exec($("#target").val());
var result = matches ? matches[1] : null;

live form results using javascript

I am trying to provide a message below the fields of a form. The message will depend on what is entered in both fields.
How would I go about making it so it calculates in real time using both the fields and passing it through a calculation?
Here is the fiddle http://jsfiddle.net/6qSeH/
I am using this to get the document values
var input1 = document.getElementById("input-mini");
var input2 = document.getElementById("input-mini2");
and this at the end to run the function
yearCalculator();
There are many missing pieces in your code.
Firstly you have written code entirely using javascript and trying to use jQuery syntax. So how would you expect it to work.
jQuery to set HTML --- msg.html(value);
javascriptto set HTML --- msg.html = value;
Second When you are checking for Not a Number
It is supposed to look like
val1 === NaN // It is not a string
Also this will never work as NaN is never equal to NaN
Use isNaN() method instead
Third
<div class="message"></div>
supposed to be
<div id="message"></div>
Next you need to assign events to your input. Otherwise it would only work when the page loads for the first time..
input1.addEventListener('change', yearCalculator);
input2.addEventListener('change', yearCalculator);
Otherwise it will only work the first time your script loads.
Cleaned up code
var input1 = document.getElementById("input-mini");
var input2 = document.getElementById("input-mini2");
var msg = document.getElementById('message');
input1.addEventListener('change', yearCalculator);
input2.addEventListener('change', yearCalculator);
function yearCalculator() {
var yearOne = input1.value;
var yearTwo = input2.value;
val1 = parseInt(yearOne);
val2 = parseInt(yearTwo);
if (isNaN(val1) || isNaN(val2)) {
msg.innerHTML = "Please enter a valid year !!";
return;
}
var value1 = yearOne - yearTwo + 18;
if (yearOne == yearTwo) {
msg.innerHTML = "Both years are the same";
}
if (yearOne < yearTwo) {
if (yearTwo < value1) {
msg.innerHTML = "This is a good result";
} else if (yearTwo > value1) {
msg.innerHTML = "This is a bad result";
} else {
msg.innerHTML = "This is neither good or bad";
}
}
else {
msg.innerHTML ="Year 1 is greater than Year 2";
}
};
yearCalculator();
Check Fiddle
You can use onchange="yearCalculator()" in both input fileds
First change the class='message' to id='message'. Then try this code:
var input1 = document.getElementById("input-mini");
var input2 = document.getElementById("input-mini2");
var yearOne = input1.value;
var yearTwo = input2.value;
var msg = document.getElementById('message');
function yearCalculator(value1, value2) {
msg.innerHTML='';
val1 = parseInt(value1);
val2 = parseInt(value2);
if (val1 === "NAN" || val2 === "NAN") return;
var value1 = val1 - val2 + 18;
if (val1 == val2) {
msg.innerHTML="Both years are the same";
}
if (val1 < val2) {
if (val2 < value1) {
msg.innerHTML = "This is a good result";
} else if (val2 > value1) {
msg.innerHTML = "This is a bad result";
} else {
msg.innerHTML = "This is neither good or bad";
}
}
};
yearCalculator(yearOne,yearTwo);
input1.onkeyup=function() {
yearCalculator(this.value,document.getElementById("input-mini2").value);
};
input2.onkeyup=function() {
yearCalculator(document.getElementById("input-mini").value,this.value);
};

Categories

Resources