Set max value of an input box based on another input box - javascript

How can I set the max value of amount input box based on balance input box? For example, if the value of balance input box is 500 so the max value of amount input box is 500. So when the user enters a number in amount input box greater than the value of balance input box, it will show an error message. How can I do that? I'm using angularjs to validate but it seems it's not working on my code.
This what I did: https://jsfiddle.net/mbnxdvpw/
This is how I retrieve the balance data. When the user clicks the payment icon it will show a modal and when it is success the balance data from the database will be retrieved in balance input.
function view_payment(payment_sales_id) {
var modal = $('#payment-sales-modal');
$.ajax({
type: 'POST',
url: url + 'GetPaymentDetailsById',
data: { payment_sales_id : payment_sales_id },
dataType: 'json',
success: function (data) {
modal.modal({ backdrop: 'static', keyboard: false});
modal.find($('#payment_sales_id')).val(payment_sales_id);
modal.find($('#payment_net_amount')).val(data.sales_net_amount);
modal.find($('#payment_balance')).val(data.sales_balance);
}
});
}
HTML
<div class="form-group">
<label for="">Balance <small>*</small></label>
<input type="text" id="payment_balance" name="payment_balance" placeholder="Balance" class="form-control" ng-model="payment_balance" readonly>
</div>
<div class="form-group">
<label for="">Amount <small>*</small></label>
<input type="text" id="payment_amount" name="payment_amount" placeholder="Amount" class="form-control" ng-model="payment_amount" ng-pattern="/^[0-9]+\.?[0-9]*$/" max="payment_balance.value">
<span ng-messages="formPayment.payment_amount.$error" ng-if="formPayment.payment_amount.$dirty">
<strong ng-message="pattern" class="text-danger">Please type numbers only.</strong>
<strong ng-message="max" class="text-danger">Please enter a value less than or equal according to balance.</strong>
</span>
</div>

First of all, you are injecting the value directly on the input payment_balance, that's not the most cleanest angular way to do it. You should use $scope (check my js example below) so you could change it on the fly without need to find the input over and over again (probably not a problem on this particullary code, but one thing to have in mind).
Second, you should use a <form> to check for properties like $error or $dirty. That being said, I did an small example (not focusing the retrieved data).
Happy coding =}

Related

Input Form OnChange Function Not Displaying Data?

So I made this codepen here https://codepen.io/shodoro/pen/xxYqXqv?editors=1111
I am trying to get whatever I type into my input form to display in my console, but everytime I type something it just shows " "
Right now I understand that I set my data to be " ", but I don't know how to make what I type to display
heres the html
<form>
<input type="text" placeholder="Street" id="street" onchange="updateInfo()">
<input type="text" placeholder="City" id="city" onchange="updateInfo()">
<input type="text" placeholder="Zipcode" id="zipcode" onchange="updateInfo()">
</form>
Here's the javascript
function updateInfo() {
const url = ""
const data = {
Street: '',
City: '',
Zipcode: '',
}
document.getElementById('street').value = data.Street
console.log('hi', data.Street)
}
Note eventually I will want to integrate this with a backend API, so whatever I type will update into the API data, but for now I just want to confirm my inputs work first
You are not getting the data you are typing as you are not looking for it.
Forms are submitted on button clicks unless the type of the form button is specifically not submit type. You need to prevent your form from submitting using the preventDefault method.
Add to that, you are assigning the empty field of the Data object into the input field's value. I think what you are trying to achieve is
data.Street = document.getElementById('street').value;
Change this
document.getElementById('street').value = data.Street
to
data.Street = document.getElementById('street').value

cleaning DOM of JS, because of livewire

i have a project that have combination of: php(laravel) in backend AND front end of javascript+css+html.
my strategy:
I have an input for inserting password(input type: password).
I have an icon for show, password digits, when user click on that icon.
handle that process, by "onclick" event inside "icon" element:
when user clicks on "eye icon", javascript changes the property of input tag, the type="password" to type="text",(user can see her/his inserted password digits ).
MY PROBLEM:
but, because of livewire property inside input tag ,after of showing password digits,
by typing more password digits, password numbers being convert to * again!
livewire property that used inside input tag: wire:model.debounce.700ms="password" .
I think, it is because of that:
the livewire, reloads the input tag.
Anyone knows the solution?
the div, that contains input password and eye icon(for clicking by user for show password digits):
<div class="o-form__field-frame o-form__field-frame--password #error('password') has-error #enderror">
<input type="password" wire:model.debounce.700ms="password" id="password" value="{{$password}}" placeholder="PLEASE INSERT YOUR PASSWORD" class="o-form__field">
<i class='fa fa-eye hSh_eye_show_pass' onclick='showPass()'></i>
</div>
the function that handle that:
//for show pass:
function showPass(){
document.getElementById('password').type="text";
}
Since livewire changes the input stuff you could have a second input of type text hidden and if the user clicks the other input is shown instead:
// used for being able to apply the inputs values correctly..
// u can omit that this is only for making code snippet working..
let pwHidden = true
function togglePassVisibility() {
const passVisible = document.getElementById('password-visible')
const passHidden = document.getElementById('password-hidden')
// toggle the .hidden class on both..
passVisible.classList.toggle('hidden')
passHidden.classList.toggle('hidden')
// make this code snippet work since I cannot access {{$password}}
// you can omit this..
if(pwHidden) {
passVisible.value = passHidden.value
} else {
passHidden.value = passVisible.value
}
pwHidden = !pwHidden
}
.hidden {
display: none;
}
<!-- you need ofc to pass {{$password}} as value to make it work in your environment. -->
<input type="text" class="hidden" id="password-visible"></input>
<input type="password" id="password-hidden"></input>
<button onClick="togglePassVisibility()">toggle</button>

access a specific input in an input array

<td><input type="text" name="product_code[]" id="product_code1" class="form-control input-sm" /></td>
I have been creating an invoice system ... how can I access a specific input to get its text ( product code ) and load the description from the database???
I know how to access all the elements but cannot access the specific one the user is typing text :(
using the below code trying to get the value returns all the values of the product code text inputs and only works for the first one
$('[name="product_code[]"]').keyup(function() {
var values = $("input[name='product_code[]']")
.map(function(){return $(this).val();}).get();
alert(values);
});
#AlexisGarcia lets say user types product code I want to access the db and retrieve product description for that product code ... how do I get through javascript or jquery the value of the specific input the user is typing???
You have to use AJAX to get that from Database.
First you need to get what the user has typed (input value), and then send it to AJAX. Here is an example:
$('#product_code1').keyup(function(){
var user_text = $(this).val();
$.ajax({
method: 'post',
url: 'link_to_your_controller',
data: {text: user_text},
dataType: 'json',
complete: function(data) {
//..DO SOMETHING WITH RESULT FROM DB
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td>
<input type="text" name="product_code[]" id="product_code1" class="form- control input-sm" />
</td>
You need to learn about AJAX to do what you need.
You can start by reading https://www.w3schools.com/xml/ajax_intro.asp
$('.input-sm').keyup(function() {
var values = $(this).val();
alert(values);
});
Try this code, you will get what you want

Jquery serializeArray break then continue

I'm really new to using serializeArray in jQuery so please forgive me if i'm not asking the correct question.
I have a form which on click add the data to fields within a div ID which works fine, it keeps adding data each time i click which is great, however is it possible to split each form's results? For example, you type in a name and phone number, click add, then in the div ID #results it adds the data then i want the next time you add data, it add's it to the same div ID but seperated by a box
$("#saveAndAdd").click(function(){
addTrip();
var x = $(".cool-test").serializeArray();
$.each(x, function(i, field){
$("#results").append(field.value + " " );
});
});
function addTrip() {
var providerName = $("#providerName").val();
var providerPhone = $("#providerPhone").val();
$("#providerTypeValue").html(providerType);
$("#providerNameValue").html(providerName);
$("#providerPhoneValue").html(providerPhone);
<label class="uikit-text-input__label" for="Input field">Name</label>
<input class="uikit-text-input input-half" name="Input field" id="providerName" type="text" value="" aria-required="true">
<label class="uikit-text-input__label" for="Input field">Phone</label>
<input class="uikit-text-input input-half" name="Input field" id="providerPhone" type="text" value="" aria-required="true">

Javascript keyup function throwing wrong alert message

With the following script, i am trying to validate whether the refund amount wlt_ln_refund_amt is greater than the balance amount wlt_ln_bal using keyup function.
In my html read only field wlt_ln_bal (field type = number) i have a an amount 222.00
the other field wlt_ln_refund_amt (field type = number)
The testcase
for the value 3 the system is throwing an error message like "Refund amount Rs.3 is greater than Balance Rs.222.
for the values 1, 2 or 2000 the system is not throwing any errors
Here is my html code:
<form id="lnrefund" name="lnrefund"
method="post" role="form"
class="form-horizontal"
action="<?php echo $_SERVER['PHP_SELF']; ?>"
onsubmit="return (checkform() && confirm_update())">
<div class="form-group">
<label class="col-md-2 col-xs-12 control-label">Loan Balance</label>
<div class="col-md-3 col-xs-12">
<input id="wlt_ln_bal" Name="wlt_ln_bal"
type="number"value ="<?php echo $bal ?>"
class="form-control required" readonly/>
<span class="help-block">Required</span>
</div>
</div>
<label class="col-md-2 col-xs-12 control-label">Refund Amount</label>
<div class="col-md-3 col-xs-12">
<input id="wlt_ln_refund_amt"
Name="wlt_ln_refund_amt"type="number" step="0.01"
class="form-control" required/>
<span class="help-block">Required</span>
</div>
</form>
And this is the javascript
<script type="text/javascript">
$(function(){
$("#wlt_ln_refund_amt").keyup(function () {
var ref = document.lnrefund.wlt_ln_refund_amt.value;
var bal = document.lnrefund.wlt_ln_bal.value;
if (ref>bal)
{
alert('Refund amount Rs.'+ref+ '\nis greater than Available Balance Rs.'+bal)
return true;
}
});
});
</script>
It looks like the variables are being compared as strings (i.e. alphabetically) you should try something like
var ref = parseInt(document.lnrefund.wlt_ln_refund_amt.value);
var bal = parseInt(document.lnrefund.wlt_ln_bal.value);
or maybe
var ref = parseFloat(document.lnrefund.wlt_ln_refund_amt.value);
var bal = parseFloat(document.lnrefund.wlt_ln_bal.value);
if you're expectiong decimals
Since you asked for suggestions... :P
I'd use jQuery to get the values of the two inputs. You're already using jQuery for the document ready function, so why not use:
var $refund = $('#wlt_ln_refund_amt'),
$balance = $('#wlt_ln_bal.value');
What you're doing works fine - as long as the structure of your HTML never changes. Using jQuery like this means you don't have to worry about ever wrapping your inputs in a containing DIV or changing the form to a popup dialog later on.
Next, I wouldn't use the keyup event, I'd use the blur event. Perhaps your use case requires the check after every keystroke, but that usually annoys users. If you bind to the blur instead of the keyup, your user will have an opportunity to correct a mistake during typing before getting yelled at by your function.
$refund.on('blur', function(){
var refAmount = parseInt($refund.val()),
balAmount = $balance.val() * 1;
if (refAmount > balAmount)
{
alert('Refund amount Rs.' +
refAmount +
'\nis greater than Available Balance Rs.' +
balAmount);
$refund.focus();
}
});
As someone else suggested, make sure the values you're comparing are numeric. You can use the parseInt as suggested (the preferred way) or force type conversion by multiplying the value by 1. Either way will result in a NaN (not a number) if the user enters something other than numbers.
After the alert, I'd return focus back to the refund amount to give the user another shot at the entry.
As a final suggestion, I'd recommend using readable variable names. Perhaps you shortened them just for this question, but descriptive variable names are much easier to deal with than obscure abbreviations.
Good luck!

Categories