Yii2: Calculation using JQuery based on condition - javascript

I have a form with fields with ID like
#opdtestbill-health_card_number
#opdtestbill-test_charges
#opdtestbill-discount
#opdtestbill-total_charges
Now what I am trying to do is when the health_card_number is not empty calculate discount on test charges. That is the discount field and total_charges field is filled automatically.
The test_charges field is getting the data through ajax and is not filled manually.
I have tried this code, but I am getting NaN in both discount and total_charges.
This is my code:
<?php
$this->registerJs("$('#opdtestbill-health_card_number').blur(function(){
if( $(this).val() ) {
var test_charges = parseInt($('#opdtestbill-test_charges').val());
var discount = (test_charges*5)/100;
var totalAmount = test_charges - discount;
$('#opdtestbill-discount').val(discount);
$('#opdtestbill-total_charges').val(totalAmount);
}else{
$('#opdtestbill-discount').val()=0;
}
});");
?>
I have not much idea about using JQuery, any help will be greatly appreciated.
I have also tried to do this using only php, but it works only on update, not on new record.
The php code I am using is like
in my Model
public function getHealthCardDiscount(){
$discount=0;
if (!empty($this->health_card_number)){
$discount = ($this->test_charges *5)/100;
}
return $discount;
}
and in _form.php
$model->discount=$model->healthCardDiscount;
$model->total_charges=$model->test_charges - $model->healthCardDiscount;
Thanks.
HTML for relevant section is like this:
<div class="form-group field-opdtestbill-health_card_number">
<label class="control-label" for="opdtestbill-health_card_number">Health Crd. No.</label>
<input type="text" id="opdtestbill-health_card_number" class="form-control" name="OpdTestBill[health_card_number]" maxlength="15">
<div class="form-group field-opdtestbill-test_charges">
<label class="control-label" for="opdtestbill-test_charges">Test Charges</label>
<input type="text" id="opdtestbill-test_charges" class="form-control" name="OpdTestBill[test_charges]" maxlength="10">
<div class="form-group field-opdtestbill-discount">
<label class="control-label" for="opdtestbill-discount">Disct.</label>
<input type="text" id="opdtestbill-discount" class="form-control" name="OpdTestBill[discount]" maxlength="10">
<div class="form-group field-opdtestbill-total_charges">
<label class="control-label" for="opdtestbill-total_charges">Total Charges</label>
<input type="text" id="opdtestbill-total_charges" class="form-control" name="OpdTestBill[total_charges]" value="0" maxlength="10">
Rendered Jquery
<script type="text/javascript">jQuery(document).ready(function () {
$('#opdtestbill-health_card_number').blur(function(){
if( $(this).val() ) {
var test_charges = parseInt($('#opdtestbill-test_charges').val());
var discount = (test_charges*5)/100;
var totalAmount = test_charges - discount;
$('#opdtestbill-discount').val(discount);
$('#opdtestbill-total_charges').val(totalAmount);
}else{
$('#opdtestbill-discount').val()=0;
}
});

If you want convert string to integer, you may use like that:
var test = "10";
test = test - 0;
And you make error in this
$('#opdtestbill-discount').val()=0;
I change your js code see http://jsfiddle.net/vitalik74/upLbpnmk/

Related

How will i show my data output inside an input element using Jquery

Here is my Javascript code:
$('#sb_add_ctrl').click(function() {
var value = $('#sel_control_num').val();
for (var i = 1; i <= 5; i++) {
value = value.replace(/(\d+)$/, function(match, n) {
const nextValue = ++match;
return ('0' + nextValue).slice(1);
});
$('#parent')[0].innerHTML += '<br>' + value;
}
})
Here is my HTML code:
<div><label> Control Number </label>
<input name="get_control_num" style="text-transform:uppercase"
class="form-control" id="sel_control_num" readonly>
</div>
<div class="form-group">
<label> Quantity </label>
<input class="form-control" name="quantity" type="number"
/>
<br>
<button type="button" id="sb_add_ctrl" class="btn btn-primary"> Add
Control Number </button>
</div>
<div class="form-group" id="parent"></div>
What I want to do is get the existing class of the input and show the data that is in innerHTML into an input element .I can't think of a proper solution cause I am still a beginner in javascript/jquery, I tried the other methods in jquery but still it doesn't work thanks for the help

Add off option value in JS and html

I want to add off option value in my page
For example, you come in my shop page and choose a package, I want to add an option field for the Discount and when you enter a text that is available on s.txt you receive a discount offer.
For example, you enter a StackOverflow code and in s.txt:
stackoverflow--20
Then the price will be reduced by %20 and displayed.
My source code follows.
JavaScript:
$("#payBtn").click(function() {
$("#count").html($("#member").val());
var price = $("#member").val();
price = price * 5;
location.href = 'https://zarinp.al/levicoder/' + price;
});
$("#name").keyup(function() {
$("#payerName").html($("#name").val());
});
$("#channelInput").keyup(function() {
$("#channel").html($("#channelInput").val());
});
$("#discount").keyup(function() {
$("#disdis").html($("#discount").val());
});
$("#member").click(function() {
$("#count").html($("#member").val());
var price = $("#member").val();
price = price * 5;
$("#amount").html(price);
});
Html:
<div class="box shadow_box purchase_cm_box" >
<h4>Order</h4>
<hr>
<input type="text" class="form-control" id="name" placeholder="Your name"><br>
<input type="text" class="form-control" id="channelInput" placeholder="Your Id"><br>
<input type="text" class="form-control" id="discount" placeholder="discount code"><br>
<div class="form-group">
<select class="form-control" id="member">
<option value="9000">9000 Value</option>
<option value="2000">2000 Value</option>
</select>
<br>
</div>
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12 pull-left" id="leftmenu">
<div class="box shadow_box purchase_cm_box" >
<h4>Factor</h4>
<hr>
Your Name : <label id="payerName">don't entered</label><br>
Your id : <label id="channel"></label><br>
discount code : <label id="disdis"></label><br>
Pay Count
<label id="amount">7,000</label>
$
<br><br>
<button class="getBtn" id="payBtn">Pay</button><br>
<p id="payStatus"></p>
</div>
</div>
I tried not to officially answer this question because I am unsure what LeVi needs. But as a result of our conversation in the comments, I was asked to provide code.
Here's my best guess of what LeVi is asking:
let inputCode = "stackoverflow";
let savedCode = "stackoverflow--20"; // derived from file s.txt
let splitSavedCode = savedCode.split('--'); // this will return ['stackoverflow', '20']
if( inputCode == splitSavedCode[0] ) {
// edited after further discussion in comments
let discountPercentage = splitSavedCode[1] / 100;
let discountAmount = price * discountPercentage;
$('#discount').val(discountAmount);
}

Javascript: Update price when quantity changes

I am new to javascript and I have been working on this for 4 days now and I haven't made any progress. I have tried a bunch of different options. I saw an example like mine that worked...but it isn't working for me. :( I am trying to have the price adjust as the quantity of tickets changes. Below is the javascript and below that is the html. Any assistance is much appreciated! Thank you!
document.getElementById("totalTicketCost").value = 0 + "." + 00;
function ticketCost()
{
var ticketCost = 5.5;
var inputTicketQuantity = document.getElementById("inputTicketQuantity").value;
var totalTicketCost = parseFloat(ticketCost) * inputTicketQuantity;
if (!isNaN(totalTicketCost))
document.getElementById("totalTicketCost").innerHTML = totalTicketCost;
}
<form onsubmit="" ="return alertDetails()" id="formPurchaseTickets" enctype="text/plain" method="post" action="mailto:cmst388#xyz.com">
<h1>Ticket Purchasing Form</h1>
<p class="alert">Act fast! This transaction must be completed in <span id="timer"></span> minutes.</p>
<div class="field">
<label class="required">How many tickets would you like to purchase?</label>
<input id="inputTicketQuantity" tabindex="1" required type="number" value="0" name="ticket-quantity" min="1" max="3" step="1" title="You can only buy between 1 and 3 tickets">
$<span id="totalTicketCost">0.00</span>
</div>
<div id="contactInfo" style="display:none;">
<div class="field">
<label class="required">Name:</label>
<input required name="name" tabindex="2" type="text" placeholder="Enter name" pattern="[a-zA-Z\s]+" title="Enter only letters. e.g. Smith">
</div>
<div class="field">
<label class="required">E-mail:</label>
<input id="inputEmail" tabindex="3" required name="email" type="email" placeholder="Enter e-mail address" onblur="validateEmail()">
</div>
</div>
<hr>
<input type="submit" tabindex="4" value="Purchase Tickets"> <input type="reset">
</form>
<script src="event_registration.js"></script>
</body>
Going with only ES5 here (assuming you're not transpiling at this stage), I did a quick refactor.
var ticketInput = document.getElementById("totalTicketCost");
var inputTicketQuantity = document.getElementById("inputTicketQuantity");
var ticketCost = 5.5;
// Handle the precision up to >= $100
function changeCost( num ) {
var cost = new Number( parseFloat( num ) * ticketCost );
var precision = cost.toString().length === 3 ? 3 : 4;
return cost.toPrecision( precision );
}
inputTicketQuantity.addEventListener('input', function( event ) {
var value = event.target.value;
if ( !isNaN( value ) ) {
ticketInput.innerHTML = changeCost( value );
}
});
You definitely want to separate out the JS from the HTML as much as possible, avoid the hard to read inline stuff like <form onsubmit="" ="return alertDetails()", should at least be <form onsubmit="return alertDetails()" to fix it.
Add an event listener to you quantity field, and recalculate price.
document.querySelector("#inputTicketQuantity").addEventListener("input", function() {
let count = this.value;
calculatePrice(count);
});
Your question is not very specific on what you're trying to achieve, but here is functionality to update your total cost as the user adds tickets -
In JS:
function updateCost(count)
{
var ticketCost = 5.5;
document.getElementById("totalTicketCost").innerHTML = count * ticketCost;
}
In HTML
<input id="inputTicketQuantity" tabindex="1" required type="number" value="0" name="ticket-quantity" onchange="updateCost(this.value)" min="1" max="3" step="1" title="You can only buy between 1 and 3 tickets">
You have to call function ticketCost() on value change event of input quantity textbox
<input id="inputTicketQuantity" onkeydown="ticketCost()" tabindex="1" required type="number" value="0" name="ticket-quantity" min="1" max="3" step="1" title="You can only buy between 1 and 3 tickets">
Or you can add listener in JavaScript as
document.getElementById("inputTicketQuantity").addEventListener("onkeydown", ticketCost);
Add it outside your JavaScript function ticketCost()

select option display input block and enter value that count and display another inptut value auto

I have a HTML form that is for payment status in my panel. In this form if i select payment status Advance Paid Then displays The another input box that i can enter for the advanced paid price. There is another input box is available that is remaining price if i entered the value of advance paid the remaining price should be display the remaining value using java script. If I choose payment status is Null then display total price in remaining price input box and if i choose Paid then display 0 in remaining price input box...all things run good ...but only one thing is not working that is if i enter the value of advance price the remaining price is not displyed. Here is my HTML Code
<div class="col-md-6">
<div class="form-group">
<label>Final Total</label>
<input type="text" value="100" name="total" id="Ftotal" class="form-control" >
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="paymentstatus">Payment Status</label>
<select class="form-control" name="paymentstatus" style="height: 40px;" onchange="yesnoCheck(this);">
<option value=""> ---Select Payment Status---</option>
<option>Advance</option>
<option>Null</option>
<option>Paid</option>
</select>
</div>
</div>
<div class="col-md-6" id="ifYes" style="display: none;">
<div class="form-group">
<label for="advancepaid">Advanced Paid</label>
<input type="text" name="advancedPiad" id="advancedPiad" onKeyUp="remaining()" class="form-control">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="remainingammount">Remaining Ammount</label>
<input type="text" name="remaining" id="remaining" class="form-control remaining" >
</div>
</div>
this is my javascript
function yesnoCheck(that) {
if (that.value == "Advance") {
document.getElementById("ifYes").style.display = "block";
} else {
document.getElementById("ifYes").style.display = "none";
}
if (that.value == "Null") {
a = Number(document.getElementById('Ftotal').value);
document.getElementById('remaining').value = a;
}
if (that.value == "Paid") {
a = 0;
document.getElementById('remaining').value = a;
}
}
function remaining()
{
a = Number(document.getElementById('Ftotal').value);
b = Number(document.getElementById('advancedPiad').value);
c = a - b;
document.getElementsByClassName("remaining").value = c;
}
Try
document.getElementsByClassName("remaining")[0].value = c;
document.getElementsByClassName gives you the array of the elements with the class name specified. In your case just set the value of first element.
Try to use js parseInt() method to convert it into integer
function remaining()
{
a=parseInt(document.getElementById('Ftotal').value);
b = parseInt(document.getElementById('advancedPiad').value);
c = a - b;
document.getElementsByClassName("remaining").value = c;
}

How to perform multiplication in JavaScript for dynamically added field on HTML?

Here is HTML source code for one pair of dynamically added elements unit_price and qty.
<label class="decimal required control-label" for="order_order_items_attributes_1413563163040_unit_price">
<input id="order_order_items_attributes_1413563163040_unit_price" class="numeric decimal required span5 span5" type="number" step="any" name="order[order_items_attributes][1413563163040][unit_price]">
</div>
<div class="input integer required order_order_items_qty">
<label class="integer required control-label" for="order_order_items_attributes_1413563163040_qty">
<input id="order_order_items_attributes_1413563163040_qty" class="numeric integer required span5 span5" type="number" step="1" name="order[order_items_attributes][1413563163040][qty]">
</div>
Whenever there is change in any unit_price, then we can do:
// find ids that match this pattern: order_order_items_attributes_xxxxxxxxxxxxx_unit_price
var orderItemRegex = /^order_order_items_\d+_unit_price$/;
$("[id^='order_order_items_']").filter(function(index) {
return orderItemRegex.test(this.id);
}).change(function() {
//here is what needs to be done. There may be more than one pair of unit price and qty on the form.
For each pair of unit price & qty do {
total += unit_price * qty
}
//update total
$('order_total').val(total);
});
The same process could be repeated again for qty whenever there is qty change in any qty field.
We are looking for solution which iterates through the list and retrieves each of the id of unit price and qty.
Suggestions:
Build an array containing the numeric portions of the ids from the price/qty fields. Your regex approach was close, but needed to be tweaked slightly to extract just that portion of the id.
Build a function to loop through those numbers, use them to fetch the price/qty pairs from the form, and then calculate the subtotal.
Call that function as soon as the page loads (only necessary if the form is prepopulated).
Call that function whenever a price or quantity changes.
Working Example:
Note: I added values to the form fields for convenience. Change them to see the subtotal update. And you'll have to add more code or field validation rules to account for negative numbers, etc.
$(document).ready(function () {
// find ids that match this pattern: order_order_items_attributes_xxxxxxxxxxxxx_unit_price
var orderItemRegex = /^order_order_items_attributes_(\d+)_unit_price$/;
var $editableFields = $("input[id$='_unit_price'], input[id$='_qty']");
var fieldNumbers = (function() {
var results = [];
$("[id$='_unit_price']").each(function () {
var numericId = orderItemRegex.exec(this.id)[1];
results.push(numericId);
});
console.log(results);
return results;
})();
function updateSubtotal() {
var subtotal = 0;
$.each(fieldNumbers, function (index, fieldNumber) {
var priceString = $('#order_order_items_attributes_' + fieldNumber + '_unit_price').val();
var priceAmount = priceString ? parseFloat(priceString.replace(/\$\,/g, '')) : 0;
var quantityString = $('#order_order_items_attributes_' + fieldNumber + '_qty').val();
var quantityAmount = quantityString ? parseFloat(quantityString.replace(/\,/g, '')) : 0;
subtotal += (priceAmount * quantityAmount);
});
$('#subtotal').text('$' + subtotal.toFixed(2));
}
updateSubtotal();
$editableFields.change(updateSubtotal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label class="decimal required control-label" for="order_order_items_attributes_1413563163040_unit_price">Price</label>
<input id="order_order_items_attributes_1413563163040_unit_price" class="numeric decimal required span5 span5" type="number" step="any" name="order[order_items_attributes][1413563163040][unit_price]" value="5.95"/>
</div>
<div class="input integer required order_order_items_qty">
<label class="integer required control-label" for="order_order_items_attributes_1413563163040_qty">Quantity</label>
<input id="order_order_items_attributes_1413563163040_qty" class="numeric integer required span5 span5" type="number" step="1" name="order[order_items_attributes][1413563163040][qty]" value="1"/>
</div>
<label class="decimal required control-label" for="order_order_items_attributes_1413563163052_unit_price">Price</label>
<input id="order_order_items_attributes_1413563163052_unit_price" class="numeric decimal required span5 span5" type="number" step="any" name="order[order_items_attributes][1413563163052][unit_price]" value="0.78"/>
</div>
<div class="input integer required order_order_items_qty">
<label class="integer required control-label" for="order_order_items_attributes_1413563163052_qty">Quantity</label>
<input id="order_order_items_attributes_1413563163052_qty" class="numeric integer required span5 span5" type="number" step="1" name="order[order_items_attributes][1413563163052][qty]" value="3"/>
</div>
<div>
<label>Subtotal:</label>
<span id="subtotal"></span>
</div>

Categories