jQuery only run function for element that gets clicked - javascript

I got a small problem that i have no clue how to solve. This HTML/PHP code bellow gets different values from a database and outputs them into the different input fields.
The HTML/PHP bellow is one element, and multiple of them are made with different values from the database. Then i got a small javascript that calulates some different values from the values that are inputted. The problem is that i got lets say 5 elements, and only wants to calculate for one of them, but if i press the "btn-oppdater" button it calculates for all the different elements.
How do i make it only calculate for the element where the button is?
Script
$('.btn-oppdater').click(function(){
$(".kval_spill").each(function(){
var fieldShow = $(this).next('.kval_spill_inner');
var b_value_kval_1 = fieldShow.find('.b_value_kval_1')[0].value;
var b_odds_kval_1 = fieldShow.find('.b_odds_kval_1')[0].value;
var e_odds_kval_1 = fieldShow.find('.e_odds_kval_1')[0].value;
var gebyr_kval = '0.02'
var q_value = ((b_odds_kval_1 / (e_odds_kval_1 - gebyr_kval)) * b_value_kval_1);
var q_tap = (b_odds_kval_1 - 1) * b_value_kval_1 - (e_odds_kval_1 - 1) * q_value;
var q_value_fixed = q_value.toFixed(2);
var q_tap_fixed = q_tap.toFixed(2);
fieldShow.find('.q_value_1')[0].value = q_value_fixed;
fieldShow.find('.q_tap_1')[0].value = q_tap_fixed;
});
});
HTML/PHP
<?php while ($row = mysqli_fetch_assoc($result2)) { echo '
<form style="margin-top: 10px;" action="" method="post" class="">
<input type="hidden" class="kval_spill">
<div class="kval_spill_inner">
<input class="" type="hidden" name="id" value="'.$row['id'].'">
<div class="form-row">
<div class="form-group col-md-4">
<input type="text" class="form-control kval_kamp_1" name="kval_kamp_1" value ="'.$row['kval_kamp_1'].'" placeholder="Kamp">
</div>
<div class="form-group col-md-3">
<div class="input-group">
<input type="text"class="form-control b_value_kval_1" name="b_value_kval_1" value ="'.$row['b_value_kval_1'].'" placeholder="Spill verdi">
<div class="input-group-append">
<span class="input-group-text">Kr</span>
</div>
</div>
</div>
<div class="form-group col-md-2">
<input type="text" class="form-control b_odds_kval_1" name="b_odds_kval_1" value ="'.$row['b_odds_kval_1'].'" placeholder="Odds">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<input type="text" class="form-control kval_marked_1" name="kval_marked_1" value ="'.$row['kval_marked_1'].'" placeholder="Type marked">
</div>
<div class="form-group col-md-3">
<div class="input-group">
<input type="text"class="form-control text-info q_value_1" name="q_value_1" value ="'.$row['q_value_1'].'" placeholder="Lay verdi">
<div class="input-group-append">
<span class="input-group-text">Kr</span>
</div>
</div>
</div>
<div class="form-group col-md-2">
<input type="text" class="form-control e_odds_kval_1" name="e_odds_kval_1" value ="'.$row['e_odds_kval_1'].'" placeholder="Odds">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-2">
<div class="input-group">
<div class="input-group-append">
<span class="input-group-text">Tap</span>
</div>
<input type="text" class="form-control text-danger q_tap_1" name="q_tap_1" value ="'.$row['q_tap_1'].'" placeholder
="0.00" readonly>
<div class="input-group-append">
<span class="input-group-text">Kr</span>
</div>
</div>
</div>
<div class="col-auto">
<button type="button" class="btn btn-outline-secondary btn-oppdater">Regn ut</button>
</div>
</div>
</div>
</form>
<br>
'; }?>

Replace $(".kval_spill") with $(this).closest("form").find(".kval_spill").
But it looks like there's only one kval_spill and kvall_spill_inner in each form, so there's no need to use .each(). You can get rid of the .each() loop and just use:
var fieldShow = $(this).closest("form").find('.kval_spill_inner');
And instead of
fieldShow.find('.q_value_1')[0].value = q_value_fixed;
fieldShow.find('.q_tap_1')[0].value = q_tap_fixed;
you can write:
fieldShow.find('.q_value_1').val(q_value_fixed);
fieldShow.find('.q_tap_1').val(q_tap_fixed);

Related

How to show total value of two text box in another box - Javascript

I am new to javascript, I want to get two fees in text boxes and show sum of those two fees in another text box (which is disabled, so can't edit it, just for showing purpose) below is my html form.. result should show when entering in fee1 or fee2 not in submit button. How to do it?
<div class="row">
<div class="col-xl-4">
<div class="form-group">
<label class="gr"><b>Consulation Fees:</b><span class="text-danger">*</span></label><input type="number" class="form-control" id="fee1" name="fee1" required min="0">
</div>
</div>
<div class="col-xl-4">
<div class="form-group">
<label class="gr"><b>Other Charges:</b></label><input type="number" class="form-control" id="fee2" name="fee2" min="0">
</div>
</div>
<div class="col-xl-4">
<div class="form-group">
<label class="gr"><b>Total Fee:</b></label><input type="number" disabled class="form-control" id ="total_fee" name="total_fee" >
</div>
</div>
use input event on fee1 and fee2 and then sum their values and put as value of total_fee.
e.g.
const fee1 = document.getElementById("fee1");
const fee2 = document.getElementById("fee2");
const total_fee = document.getElementById("total_fee");
fee1.addEventListener("input", sum);
fee2.addEventListener("input", sum);
function sum() {
total_fee.value = Number(fee1.value)+Number(fee2.value);
}
see in action
https://jsbin.com/lizunojadi/edit?html,js,output
Basically you listen to input event on both of the controls, summing the values into the other input.
document.querySelectorAll("#fee1, #fee2").forEach(function(elem) {
elem.addEventListener("input", do_sum)
})
function do_sum() {
var total = 0
document.querySelectorAll("#fee1, #fee2").forEach(function(elem) {
total += +elem.value;
})
document.querySelector("#total_fee").value = total
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" rel="stylesheet">
<div class="container">
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label class="gr"><b>Consulation Fees:</b><span class="text-danger">*</span></label><input type="number" class="form-control" id="fee1" name="fee1" required min="0">
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label class="gr"><b>Other Charges:</b></label><input type="number" class="form-control" id="fee2" name="fee2" min="0">
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label class="gr"><b>Total Fee:</b></label><input type="number" disabled class="form-control" id="total_fee" name="total_fee">
</div>
</div>
</div>
</div>
Here is the simple solution for your code,
<div class="row">
<div class="col-xl-4">
<div class="form-group">
<label class="gr"><b>Consulation Fees:</b><span class="text-danger">*</span></label><input type="number" class="form-control" id="fee1" name="fee1" required min="0" value="0">
</div>
</div>
<div class="col-xl-4">
<div class="form-group">
<label class="gr"><b>Other Charges:</b></label><input type="number" class="form-control" id="fee2" name="fee2" min="0" value="0">
</div>
</div>
<div class="col-xl-4">
<div class="form-group">
<label class="gr"><b>Total Fee:</b></label><input type="number" disabled class="form-control" id ="total_fee" name="total_fee" >
</div>
</div>
Here in the HTML code default value="0",
Now in Javascript,
const fee1 = document.getElementById('fee1');
const fee2 = document.getElementById('fee2');
const totalFee = document.getElementById('total_fee');
function doSum() {
const fee1Value = parseInt(fee1.value);
const fee2Value = parseInt(fee2.value);
const totalFeeValue = fee1Value + fee2Value;
totalFee.value = totalFeeValue;
}
fee1.addEventListener('input', doSum);
fee2.addEventListener('input', doSum);
doSum() function is executing oninput

Select2 function is not working in angular js dynamic form

hi every one I am working on angular js project. But here is a little problem i am using dynamic form for multiple fields and using select2 function for search but first time it is working then after making new field it is not working for search can you please help me??
here is my controller code for making dynamic field
$scope.choices = [{id: 1,purchaser_account:'',price:0,weight:0}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':newItemNo,purchaser_account:'',price:0,weight:0});
};
here is code of view
<div data-ng-repeat="choice in choices">
<div class="row">
<div class="col-md-3">
<div class="form-group label-floating">
<label class="control-label urdu-lable"> خریدار کھاتہ</label>
<select ng-model="choice.purchaser_account" name="account{{choice.id}}" class="form-control select2" required>
<option ng-repeat="x in purchaserAccount" value="{{x.id}}">{{x.name}}</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group label-floating">
<label class="control-label urdu-lable" > وزن</label>
<input type="text" id="weight" ng-model="choice.weight" class="form-control" required="required">
</div>
</div>
<div class="col-md-2">
<div class="form-group label-floating">
<label class="control-label urdu-lable"> ریٹ</label>
<input type="text" id="price" ng-model="choice.price" class="form-control" required="required">
</div>
</div>
<div class="col-md-2">
<div class="form-group label-floating">
<label class="control-label urdu-lable"> ٹوٹل</label>
<div>{{((choice.price*(choice.weight/40))+((choice.price*(choice.weight/40))*.016)).toFixed(2)}}
</div>
</div>
</div>
<div class="col-md-1">
<div class="form-group label-floating">
<button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>
</div>
</div>
</div>
</div>
<button class="btn btn-info" ng-click="addNewChoice()">Add fields</button>
can you please help me to solve out this problem
Initialize select on your angular add function.
$scope.choices = [{id: 1,purchaser_account:'',price:0,weight:0}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':newItemNo,purchaser_account:'',price:0,weight:0});
$(".select2").select2();
};
same initialize it where your are add first option in choice array.

Form validation with multiple highlighted fields

I have a registration form that I would like to have multiple field validation. What I mean by this is if more than one field is not filled in it will be highlighted red. I have some code already written but instead of highlighting the field not filled in, it's highlighting all of them. I realise it is quite long winded but I'm fairly new to this. My JS code is as follows:
`function formCheck() {
var val = document.getElementById("fillMeIn").value;
var val = document.getElementById("fillMeIn2").value;
var val = document.getElementById("fillMeIn3").value;
var val = document.getElementById("fillMeIn4").value;
var val = document.getElementById("fillMeIn5").value;
var val = document.getElementById("fillMeIn6").value;
var val = document.getElementById("fillMeIn7").value;
if (val == "") {
alert("Please fill in the missing fields");
document.getElementById("fillMeIn").style.borderColor = "red";
document.getElementById("fillMeIn2").style.borderColor = "red";
document.getElementById("fillMeIn3").style.borderColor = "red";
document.getElementById("fillMeIn4").style.borderColor = "red";
document.getElementById("fillMeIn5").style.borderColor = "red";
document.getElementById("fillMeIn6").style.borderColor = "red";
document.getElementById("fillMeIn7").style.borderColor = "red";
return false;
}
else {
document.getElementById("fillMeIn").style.borderColor = "green";
document.getElementById("fillMeIn2").style.borderColor = "green";
document.getElementById("fillMeIn3").style.borderColor = "green";
document.getElementById("fillMeIn4").style.borderColor = "green";
document.getElementById("fillMeIn5").style.borderColor = "green";
document.getElementById("fillMeIn6").style.borderColor = "green";
document.getElementById("fillMeIn7").style.borderColor = "green";
}
}`
My HTML is as follows:
'<form id="mbrForm" onsubmit="return formCheck();" action="thanks.html" method="post">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
FIRST NAME:
<input id="fillMeIn" type="text" class="form-control" placeholder="First Name" >
</div>
<div class="col-md-4 vertical-gap">
LAST NAME:
<input id="fillMeIn2" type="text" class="form-control" placeholder="Last Name" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8 vertical-gap">
ADDRESS:
<input id="fillMeIn3" type="text" class="form-control vertical-gap" placeholder="First Line" >
<input id="fillMeIn4" type="text" class="form-control vertical-gap" placeholder="Second Line" >
<input id="fillMeIn5" type="text" class="form-control vertical-gap" placeholder="Town/City" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
POST CODE:
<input id="fillMeIn6" type="text" class="form-control vertical-gap" placeholder="Postcode" >
</div>
<div class="col-md-4 vertical-gap">
PHONE No:
<input type="number" class="form-control vertical-gap" placeholder="Tel no">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
EMAIL ADDRESS:
<input id="fillMeIn7" type="email" class="form-control vertical-gap" placeholder="Email address" >
</div>
<div class="col-md-2"></div>
</div>
<div class="row vertical-gap">
<div class="col-md-2"></div>
<div class="col-md-8">
DISCIPLINE:
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Cross Country"> CROSS COUNTRY
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Enduro"> ENDURO
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Downhill"> DOWNHILL
</label>
</div>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-10">
<!--<button type="button" input type="hidden" class="btn btn-success" name="redirect" value="thanks.html">SUBMIT</button>-->
<input type="submit" value="SUBMIT" class="btn btn-success btn-lg">
</div>
<div class="col-md-2"></div>
</div>
</form>'
Thanks!
You could have the ids in an Array, iterate through its values, and execute the repeatable code in a function that groups all the logic inside.
example :
["fillMeIn1", "fillMeIn2", "fillMeIn3", "fillMeIn4"].each(function(id){
// do things with id
})
Why not use the html "required" property instead?
If you want to do this with JS, you should give each variable a different name. In the code you posted you are continuously overwriting the same variable, and then, it evaluates val (which ended up being assigned to the (fill me7 value) to "", and if true, setting all the borders to red.
Set different variables, push the input values into an array when submit is triggered and loop through them if variables[i]==0, set getElementId(switch case[i] or another array with the name of the inputs[i]).bordercolor to red.
AGAIN, this sound VERY INEFFICIENT and I am not sure at all it would work. My guess is that it would take A LOT of time, and probably get timed out (except you are using some asych/try-catch kind of JS).
I would simply go for an HTML required property and then override the "required" property in CSS to make it look as you intend to. Simpler, easy and clean.
The main issue in your code is that you override the variable val each time you wrote var val = ....
Keeping your own your logic, you could write something like that.
var formModule = (function () {
var $fields = [
document.getElementById('fillMeIn'),
document.getElementById('fillMeIn2'),
document.getElementById('fillMeIn3'),
document.getElementById('fillMeIn4'),
document.getElementById('fillMeIn5'),
document.getElementById('fillMeIn6'),
document.getElementById('fillMeIn7')
];
function markInvalid($field) {
$field.style.borderColor = 'red';
}
function markValid($field) {
$field.style.borderColor = 'green';
}
return {
check: function () {
var isValid = true;
$fields.forEach(function ($f) {
if ($f.value === '') {
if (isValid) alert('Please fill in the missing fields');
isValid = false;
markInvalid($f);
}
else markValid($f);
});
return isValid;
}
};
})();
There are some extra concepts in this example which may be useful:
Working with the DOM is really slow, that's why you should
put your elements in a variable once for all and not everytime you
click on the submit button.
In my example i wrap the code with var formModule = (function () {...})();.
It's called module pattern. The goal is to prevent variables to leak in the rest of the application.
A better solution could be this one using the 'power' of html form validation:
HTML:
<form id="mbrForm" action="thanks.html" method="post">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
FIRST NAME:
<input id="fillMeIn" type="text" required class="form-control" placeholder="First Name">
</div>
<div class="col-md-4 vertical-gap">
LAST NAME:
<input id="fillMeIn2" type="text" required class="form-control" placeholder="Last Name">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8 vertical-gap">
ADDRESS:
<input id="fillMeIn3" type="text" required class="form-control vertical-gap" placeholder="First Line">
<input id="fillMeIn4" type="text" required class="form-control vertical-gap" placeholder="Second Line">
<input id="fillMeIn5" type="text" required class="form-control vertical-gap" placeholder="Town/City">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4 vertical-gap">
POST CODE:
<input id="fillMeIn6" type="text" required class="form-control vertical-gap" placeholder="Postcode">
</div>
<div class="col-md-4 vertical-gap">
PHONE No:
<input type="number" class="form-control vertical-gap" placeholder="Tel no">
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
EMAIL ADDRESS:
<input id="fillMeIn7" type="email" required class="form-control vertical-gap" placeholder="Email address">
</div>
<div class="col-md-2"></div>
</div>
<div class="row vertical-gap">
<div class="col-md-2"></div>
<div class="col-md-8">
DISCIPLINE:
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Cross Country"> CROSS COUNTRY
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Enduro"> ENDURO
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input horizontal-gap" type="checkbox" value="Downhill"> DOWNHILL
</label>
</div>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-10">
<input id="btnSubmit" type="submit" value="SUBMIT" class="btn btn-success btn-lg">
</div>
<div class="col-md-2"></div>
</div>
</form>
JS:
var formModule = (function () {
var $form = document.getElementById('mbrForm');
var $btn = document.getElementById('btnSubmit');
var $fields = [
document.getElementById('fillMeIn'),
document.getElementById('fillMeIn2'),
document.getElementById('fillMeIn3'),
document.getElementById('fillMeIn4'),
document.getElementById('fillMeIn5'),
document.getElementById('fillMeIn6'),
document.getElementById('fillMeIn7')
];
checkValidation();
$form.addEventListener('change', checkValidation);
$form.addEventListener('keyup', checkValidation);
$fields.forEach(function ($f) {
$f.addEventListener('change', function () {
markInput($f, $f.checkValidity());
});
});
function checkValidation() {
$btn.disabled = !$form.checkValidity();
}
function markInput($field, isValid) {
$field.style.borderColor = isValid ? 'green' : 'red';
}
})();
In this example, the button gets disabled until the form is valid and inputs are validated whenever they are changed.
I added required attribute in HTML inputs so they can be handled by native javascript function checkValidity(). Note that in this case inputs email and number are also correctly checked. You could also use attribute pattern to get a more powerfull validation:
<input type="text" pattern="-?[0-9]*(\.[0-9]+)?">
Hope it helps.

JQuery Bootstrap Modal auto calculate text field not updating

I have a bootstrap html page that contains already 2 auto update text field functions for its needs. Along with that I added another fields in a modal to complete the page and requires another auto calculation to be populated on a certain text field.
Base form for first and 2nd instance of auto update
<form role="form" id="myForm" action="cashier.php?submit=yes" method="post" data-toggle="validator">
<div class="form-group">
<div class="row">
<div class="col-md-6 col-xs-6">
<div class="form-group">
<label for="exampleInputEmail1">Item</label>
<select onchange="GenPrice(this)" id="items" name="items" class="form-control" required>
<option value="" selected disabled>Select Item</option>
<?php
//some sql function for fetch
echo '<option value="'.$row['sup_eaprice'].'|'.$row['sup_name'].'" required>'.$row['sup_name'].'</option>';
}
}
?>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6 col-xs-6">
<div class="form-group">
//FIRST INSTANCE AUTO UPDATING TEXT FIELD
<label for="exampleInputEmail1">Price (ea)</label>
<input type="text" class="form-control" id="eaprice" placeholder="No Item Selected" required disabled>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-xs-6">
<div class="form-group">
<label for="exampleInputEmail1">Quantity</label>
<input type="text" class="form-control calculate" onchange="GenTot(this)" name="quantity" id="quantity" placeholder="How many?" pattern="^[0-9]*[1-9][0-9]*$" maxlength="3" data-minlength="1" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6 col-xs-6">
<div class="form-group">
//2ND INSTANCE AUTO UPDATING TEXTFIELD
<label for="exampleInputEmail1">Total</label>
<input type="text" class="form-control" id="ztotal" name="ztotal" readonly>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="form-group" align="right">
<button id="submit" type="submit" class="btn btn-primary" name="addcart">Add Cart</button>
</div>
</div>
</form>
Modal window 3rd instance
<!--create confirmation modal window-->
<div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<b>Final Check</b>
</div>
<div class="modal-body">
<div class="row">
<form role="form" id="purchformx" action="cashier.php?submit=yes" method="post" data-toggle="validator">
<!-- hidden for purpose of change auto calc -->
<input type="hidden" name="thetotal" class="calchange" id="thetotal" value="<?php echo $overall; ?>">
<div class="col-md-6 col-xs-6">
<div class="form-group">
<label for="exampleInputEmail1">Received</label>
<input type="text" class="form-control calchange" name="received" id="received" placeholder="How much given?" pattern="^[0-9]*[1-9][0-9]*$" maxlength="4" data-minlength="1" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6 col-xs-6">
<div class="form-group">
//3RD INSTANCE AUTO UPDATE NOT WORKING
<label for="exampleInputEmail1">Change</label>
<input type="text" class="form-control" id="thechange" name="thechange" readonly>
<div class="help-block with-errors"></div>
</div>
</div>
</form>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
Submit
</div>
</div>
</div>
</div>
<!--end modal-->
JQUERIES
For first instance (working)
<script type="text/javascript">
function GenPrice(data) {
var xprice = data.value;
var zprice = xprice.split("|");
document.getElementById ("eaprice").value = zprice[0];
document.myForm.eaprice.value = zprice[0];
}
</script>
For second instance (working) based from Calculate total value inline form
<script type="text/javascript">
/* total value calculator */
$(document).ready(function () {
//Calculate both inputs value on the fly
$('.calculate').keyup(function () {
var Tot = parseFloat($('#eaprice').val()) * parseInt($('#quantity').val());
if(isNaN(Tot)) Tot = "";
$('#ztotal').val(Tot);
});
//Clear both inputs first time when user focus on each inputs and clear value 00
$('.calculate').focus(function (event) {
$(this).val("").unbind(event);
});
});
</script>
For third instance (not working) based from auto calculate total value
<script type="text/javascript">
$(document).ready(function(){
$('.calchange').change(function(){
var total = 0;
$('.calchange').each(function(){
if($(this).val() != '')
{
total = parseFloat($(this).val()) - parseFloat($('#thetotal').val());
}
});
$('#thechange').html(total);
});
})(jQuery);
</script>
I'm not sure why the 3rd instance which is inside a modal window doesn't auto update at all given ive just made a separate jquery class for it. Thanks in advance for further suggestions.
$('.calchange').change(function(){
var total = 0;
$('.calchange').each(function(){
if($(this).val() != '') {
total += parseFloat($(this).val());
}
});
var totalFinal = total - parseFloat($('#thetotal').val());
$('#thechange').val(totalFinal);
});

Dynamic ng-model with ng-repeat

I would like to create dynamically some input fields, that I used ng-repeat with ng-model. I meet some problems. ng-model without ng-repeat works correctly (transitPointStart). transits should work exactly the same, but they don't. What am I missing?
(link to plunker on the bottom)
transitPointStart:
<div class="col-lg-6">
<div class="form-group">
<label class="control-label" for="field_start">Start Point</label>
<input type="text" class="form-control" name="field_start" id="field_start"
ng-model="transitPointStart.city" placeholder="e.g. London"
/>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label class="control-label" for="field_start_date">Date</label>
<div class="input-group">
<input id="field_start_date" type="text" class="form-control" placeholder="YYYY-MM-DD HH:MM"
name="field_start_date"
datetime-picker="{{dateformat}}" ng-model="transitPointStart.date"
is-open="datePickerOpenStatus.field_start_date"
/>
<span class="input-group-btn">
<button type="button" class="btn btn-default"
ng-click="openCalendar('field_start_date')"><i
class="glyphicon glyphicon-calendar"></i></button>
</span>
</div>
</div>
</div>
transits:
<div class="row" ng-repeat="transit in transits">
<!--TEST-->
<!--<div> Model: {{transit.modelName}} </div>-->
<!--<div> dateModel: {{transit.dateModelName}} </div>-->
<!--<div> datePicker: {{transit.datePickerName}} </div>-->
<!--<div> fieldName: {{transit.fieldName}} </div>-->
<!--<div> fieldDateName: {{transit.fieldDateName}} </div>-->
<!--<div> button: {{transit.buttonDateName}} </div>-->
<!--/TEST-->
<div class="col-lg-6">
<div class="form-group">
<label class="control-label" for="transit.fieldName">Transit {{$index+1}}</label>
<input type="text" class="form-control" name="transit.fieldName" id="transit.fieldName"
ng-model="transit.modelName" placeholder="transit"
/>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label class="control-label" for="transit.fieldDateName">Date {{$index+1}}</label>
<div class="input-group">
<input id="transit.fieldDateName" type="text" class="form-control" placeholder="e.g"
name="transit.fieldDateName"
datetime-picker="{{dateformat}}" ng-model="transit.dateModelName"
is-open="transit.datePickerName"
/>
<span class="input-group-btn">
<button type="button" class="btn btn-default"
ng-click="transit.buttonDateName"><i
class="glyphicon glyphicon-calendar"></i></button>
</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-2">
<span class="btn btn-primary" ng-click="addTransit()" ng-if="transits.length < 3">Add transit</span>
</div>
<div class="col-lg-2"></div>
</div>
controller:
$scope.transits = [];
$scope.addTransit = function () {
var tempId = $scope.transits.length + 1;
var tempName = "transitPoint_" + tempId;
var tempModelName = tempName + ".city"; // Here I would like to have access to transitPoint.city
var tempDateName = tempName + ".date"; // as above (transitPoint.date)
var tempDate = "datePickerOpenStatus.field_transit_date_" + tempId;
var tempFieldName = "field_transit_" + tempId;
var tempFieldDateName = "field_transit_date_" + tempId;
var tempButton = "openCalendar('" + tempFieldDateName + "')";
$scope.transits.push({
modelName: tempModelName,
dateModelName: tempDateName,
datePickerName: tempDate,
fieldName: tempFieldName,
fieldDateName: tempFieldDateName,
buttonDateName: tempButton
});
}
/*
{...} - rest of code, sending queries (vm.save() ect.)
*/
$scope.datePickerOpenStatus = {};
$scope.datePickerOpenStatus.field_start_date = false;
$scope.datePickerOpenStatus.field_end_date = false;
// I should've used loop here
$scope.datePickerOpenStatus.field_transit_date_1 = false;
$scope.datePickerOpenStatus.field_transit_date_2 = false;
$scope.datePickerOpenStatus.field_transit_date_3 = false;
$scope.openCalendar = function (date) {
$scope.datePickerOpenStatus[date] = true;
};
Demo: Plunker
Some of the bindings in your HTML are not correct. You need to use interpolation (the {{ }} format) whenever you need to emit data from the model into the HTML.
For example, when assigning IDs, you have:
<input id="transit.fieldDateName" type="text" class="form-control" placeholder="e.g" name="transit.fieldDateName" ...
This should be:
<input id="{{transit.fieldDateName}}" type="text" class="form-control" placeholder="e.g" name="{{transit.fieldDateName}}" ...
Second, your ng-click syntax is not correct. You should not create the openCalendar expression in JavaScript, but in your HTML, like so:
<button type="button" class="btn btn-default" ng-click="openCalendar(transit.fieldDateName)">
I think your Plnkr is missing some scripts and/or steps to make the calendar work, but these changes will at least cause your openCalendar function to get called.

Categories