Vue jS: input auto filled - javascript

In my Vue JS code below i have input total price and two inputs paid and percentage, i wanted to do an algorithm that what ever user wrote inside paid input an auto percentage should be filled in percentage input and ofc this percentage is from total price input, also when user write in percentage input the paid should be auto filled and so on.
Is there a way to do this in Vue js?
P.S: I wrote v-model=instpaid and v-model=instprice that posts data to API
<input type="number" v-model="instPrice" class="price-input mt-3" placeholder=" total price" required />
<br />
<input type="number" v-model="instPaid" class="price-input mt-3" placeholder=" paid " required />
<input type="number" class="price-input mt-3" placeholder=" percenatge" required />

Maybe something like following snippet:
new Vue({
el: "#demo",
data() {
return {
instPrice: 0,
instPaid: 0,
pct: 0
}
},
methods: {
calc(pct) {
pct === true ?
this.instPaid = (this.instPrice / 100 * this.pct).toFixed(2)
:
this.pct = (this.instPaid / this.instPrice * 100).toFixed(2)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<input type="number" v-model="instPrice" placeholder=" total price" required />
<br />
<input type="number" v-model="instPaid" placeholder=" paid" #keyup="calc(false)" required />
<input type="number" placeholder=" percenatge" #keyup="calc(true)" v-model="pct" required />
</div>

Related

How to change value inside textfield HTML

How can I change the value inside my Revenue textfield by subtracting the Cost of Good value from the Sales Price value? I have attached an image of what it looks like currently, but I want to change whats displayed inside my Revenue field after I edit the previous 2 text fields. I have also attached my code.
See attached image
<div class="product-section">
<h3>
<b>{{ product.productLabel }}</b>
</h3>
<label for="sales-price">Sales Price: </label>
<br>
<input
type="text"
[(ngModel)]="product.salesPrice"
name="sales-label"
placeholder="Enter Sales Price"
/>
<p></p>
<label for="cogs">Cost of Good: </label>
<br>
<input
type="text"
[(ngModel)]="product.cogs"
name="cogs-label"
placeholder="Enter Cogs"
/>
<p></p>
<label for="rev">Revenue: </label>
<br>
<input
type="text"
[(ngModel)]="product.rev"
name="rev-label"
readonly
/>
</div>
Add (keyup)="getRev()" to your Sales Price and Cost of Goods inputs.
<div class="product-section">
<h3>
<b>{{ product.productLabel }}</b>
</h3>
<label for="sales-price">Sales Price: </label>
<br>
<input
type="text"
[(ngModel)]="product.salesPrice"
(keyup)="getRev()"
name="sales-label"
placeholder="Enter Sales Price"
/>
<p></p>
<label for="cogs">Cost of Good: </label>
<br>
<input
type="text"
[(ngModel)]="product.cogs"
(keyup)="getRev()"
name="cogs-label"
placeholder="Enter Cogs"
/>
<p></p>
<label for="rev">Revenue: </label>
<br>
<input
type="text"
[(ngModel)]="product.rev"
name="rev-label"
readonly
/>
</div>
Then add a function to your component's typescript file to handle the revenue calculation.
getRev() {
this.product.rev = this.product.cogs - this.product.salesPrice;
}
Can you post the body of getRev()? And, take the quotes away from getRev() so that it calls the function instead of sets the value as the literal string 'getRev()'
Edit:
Is there a way to just subtract the cogs value from my sales value?
Yes, you could use an onchange handler. Here is an example, assuming you set the ID of the three elements as 'cogs', 'sales', and 'revs':
const cogs = document.getElementById('cogs');
const sales = document.getElementById('sales');
const revs = document.getElementById('revs');
cogs.addEventListener('input', (event) => {
const salesNumber = Number(sales.value);
const cogsNumber = Number(cogs.value);
const difference = salesNumber - cogsNumber;
revs.value = difference;
});

How to limit the input based on the value of another input using javascript

Html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-2">
Paid Balance</strong>: <input type="text" name="paidbalance" id="paidbalance" class="form-control" />
</div>
<div class="col-md-2" >
Balance</strong>: <input type="text" name="balance" id="balance" class="form-control" value="200" readonly/>
</div>
Hello, Can anyone help me with this problem. How to limit the input based on the value of another input using javascript .
For Example the Value of Balance Input is 200 so that the possible input in PaidBalance is within 0-200 only.
Sorry, I'm just a student. Thanks :):)
Something like this?
$("#paidbalance").keyup(()=>{
const balance = parseFloat($("#balance").val())
const paidBalance = parseFloat($("#paidbalance").val())
if( paidBalance > balance)
$("#paidbalance").val(balance)
else if(paidBalance < 0)
$("#paidbalance").val(0)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Paid Balance
</strong>: <input type="text" name="paidbalance" id="paidbalance" class="form-control" />
Balance
</strong>: <input type="text" name="balance" id="balance" class="form-control" value="200" readonly/>
This is with pure javascript without jquery. Also, note that the accepted answer doesn't work if user paste some value with mouse right-click: paste option.
function f1()
{
var max = Number(document.getElementById("balance").value);
var paid = document.getElementById("paidbalance");
var v = Number(paid.value);
//if(isNaN(v)) {...} //input is not a number
if(v>max) {
paid.focus(); //to keep focus on input
paid.value=max; //you may comment out this line to don't override value
}
}
<div class="col-md-2">
Paid Balance</strong>: <input type="text" name="paidbalance" id="paidbalance" class="form-control" oninput="f1()" />
</div>
<div class="col-md-2" >
Balance</strong>: <input type="text" name="balance" id="balance" class="form-control" value="200" />
</div>
You might wanna change the type to number in this case and add max property in input. If the value of balance Input is different every time. You might considering assign it to a variable and pass it to the max property
Paid Balance</strong>:
<input type="number" name="paidbalance" id="paidbalance" max="200" class="form-control" />
Change the input to type="number" and add jQuery like this:
var balance = $('#balance')
var paidBalance = $('#paidbalance')
paidBalance[0].setAttribute('max', balance.val())
Example:
https://jsfiddle.net/Daniel_Knights/t4hb0z7p/8/

Vue - dynamically registered models?

Inside a Vue-component, I'm making a list, but the number of entries in the list varies.
So it could be like this:
<form>
<input type="number" value="15" />
<input type="number" value="10" />
<input type="number" value="5" />
<input name="total" :value="summedTotal" /> <!-- (calculated dynamically) -->
</form>
Or like this:
<form>
<input type="number" value="15" />
<input type="number" value="10" />
<input type="number" value="5" />
<input type="number" value="17" />
<input type="number" value="20" />
<input name="total" :value="summedTotal" /> <!-- (calculated dynamically) -->
</form>
If I had a fixed set of input fields, then I would have solved it using v-model. But now the number of 'models' are dynamic.
Can I somehow still use v-model to solve this?
Currently I'm adding an #keypress-event, finding the input ( document.getElementById( '....' ) and finding the value from that. But I need to set a delay for it to work. I could use keyup or some other event-watcher, but it all becomes really hacky, really quick.
The actual code is (an advanced version of) this:
<form>
<input
type="number"
v-for="(entry, index) in list"
name="entry.id"
value="entry.initial_value"
:id="'entry-id__' + entry.id" #keypress="calculateSum()"
/>
<input name="total" :value="summedTotal" /> <!-- (calculated dynamically) -->
</form>
You should be able to use a v-model that will allow your input fields to change the value in the list :
<input
type="number"
v-for="(entry, index) in list"
:key="'input-field-'+entry.id"
name="entry.id"
v-model="entry.initial_value"
:id="'entry-id__' + entry.id"
/>
When a new value is set by the user, it should modify this precise value in your list object.
Then keep your last line as is:
<input name="total" :value="summedTotal" />
with summedTotal being a computed value summing the values of your list.
If you don't want to change your original list, you can make a deep copy first and then use copiedList for your v-model:
data {
copiedList : JSON.parse(JSON.stringify(this.list))
}
Here is a Snippet that works:
new Vue({
el: '#app',
data: {
list: [{
id: 1,
initial_value: 3
},
{
id: 2,
initial_value: 1
},
{
id: 3,
initial_value: 7
},
{
id: 4,
initial_value: 2
},
]
},
computed: {
summedValued() {
return this.list.reduce((acc, c) => {
return acc + parseInt(c.initial_value || 0);
}, 0)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="(entry, index) in list" :key="'input-field-'+entry.id">
ID {{entry.id}}: <input type="number" name="entry.id" v-model="entry.initial_value" :id="'entry-id__' + entry.id" />
</div>
TOTAL :{{summedValued}}
</div>

Change $(this) input field color based on class effecting all classes in div

I have this HTML that occurs multiple times on a page:
<div class="canteen-item">
<div class="col-l">
<h4>Chicken Sandwich</h4>
<p>$<span class="canteen-price">3.50</span></p>
</div>
<div class="col-r">
<div class="qty-days">
<input name="Mon" class="qty-input" value="0" maxlength="2" />
<input name="Tue" class="qty-input" value="0" maxlength="2" />
<input name="Wed" class="qty-input" value="0" maxlength="2" />
<input name="Thu" class="qty-input" value="0" maxlength="2" />
<input name="Fri" class="qty-input" value="0" maxlength="2" />
</div>
</div>
</div>
I have this JQuery to detect when the input field is changed and if the value is greater than 0, change the color to red.
$(".qty-input").change(function(){
var qty = parseInt($(this).val());
if(qty > 0){
$(this).css('color','red');
}
else{
$(this).css('color','black');
}
});
It is behaving very unpredictably. When I change the value of the first input field (Monday), it makes all 5 inputs red. Then sometimes it is changing the colors back to black in completely different rows sets of days. Seems like a simple problem to fix, but having trouble figuring it out.
The problem is that this code:
var qty = $(this).val();
Returns a string. And this code compares that string to a Number
if(qty > 0){
Try changing the first line of code to:
if ($(this).val()) {
var qty = parseInt($(this).val(), 10);
}
And it should start to work more consistently but you will also want to validate that the input is all numbers.
Thanks for all the responses. It prompted me to dig deeper at which point I discovered another piece of code in a different JS file that was trying (incorrectly!) to do the same thing. The code I have above is in fact sound and works perfectly. I apologize for wasting anyone's time here. I didn't realize that my client had a developer who had already attempted to do this (and who also put the code in the wrong file).
Use change event target to get to the element
$(document).ready(function() {
$(".qty-input").change(function(e) {
var target = e.target;
var qty = $(target).val();
if (qty > 0) {
$(target).css('color', 'red');
} else {
$(target).css('color', 'black');
}
alert("value is " + qty)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="canteen-item">
<div class="col-l">
<h4>Chicken Sandwich</h4>
<p>$<span class="canteen-price">3.50</span>
</p>
</div>
<div class="col-r">
<div class="qty-days">
<input type="text" name="Mon" class="qty-input" value="0" maxlength="2" />
<input type="text" name="Tue" class="qty-input" value="0" maxlength="2" />
<input type="text" name="Wed" class="qty-input" value="0" maxlength="2" />
<input type="text" name="Thu" class="qty-input" value="0" maxlength="2" />
<input type="text" name="Fri" class="qty-input" value="0" maxlength="2" />
</div>
</div>
</div>

maxlength=5 not working if input type=number

This is frustrating!
When the input type is text and I gave maxlength as 5, it is not allowing me to enter more than 5 characters
<input type="text" maxlength="5" />
If I gave input type as number and I gave maxlength as 5, it is allowing more than 5 digits?
<input type="number" maxlength="5" pattern="[0-9]*" />
Am I missing something?
PS: This is for mobile responsive site!
Instead of maxlength use max
<input type="number" min="1" max="10000" />
Update
Small jQuery plugin
(function ($) {
$.fn.maxlength = function (length) {
return this.on('keydown', function () {
var maxlength = length || parseInt($(this).attr('maxlength'), 10) ;
if (maxlength && $(this).val().length >= maxlength) {
$(this).val($(this).val().slice(0, maxlength - 1));
}
});
};
}($));
Example
try using max...
<input type="number" max="99999" />
EDIT: Showing Validation
<form id='FormValidation'>
<input id="myNum" type="number" min="1" max="99999" />
<input type="text" maxlength="5" />
<input type="submit" />
</form>
Try adding a number greater than 99999 and hitting submit, check the updated fiddle.
This jquery could help too...
$('#myNum').keyup( function(e){
var max = $('#myNum').attr('max').length;
if ($(this).val().length >= max) {
$(this).val($(this).val().substr(0, max));
}
});
replace maxlength with max
// Max Length = 5
<input type="number" max="99999" />
// length between 1 to 5
<input type="number" min="1" max="99999" />
Updated Answer. It's so simple!
<input type="number" id="nbr"/>
<input type="text" maxlength="5" />
$(document).on('keypress','#nbr', function(e){
if($(this).val().length >= 5)
{
e.preventDefault();
}
});
And you can add a max attribute that will specify the highest possible number that you may insert
<input type="number" max="999" />
if you add both a max and a min value you can specify the range of allowed values:
<input type="number" min="1" max="999" />

Categories

Resources