AngularJS pass index of repeater to function - javascript

I have a dynamic table that creates the amount of rows based on the user selection. Each row in the table then has input boxes for numbers. If I have a table with 7 rows for example, I want to store those 7 different inputs into an array. So far I am trying to pass the input of the textbox to a function which updates declared blank arrays. So something like this
HTML
<td id="{{'redScore'+($index+1)}}">
<input required="" ng-change="updateRedScore(inputValue)" ng-model="inputValue" type="number" step="1" name="rate" min="1" max="10"> </td>
Script
$scope.redRoundScore = [];
$scope.inputValue = null;
$scope.updateRedScore = function(passedscore){
$scope.redRoundScore[index] = passedscore
}
Is there a way I can pass the index alongside the inputValue to updateRedScore?

In the interest of completing this question/answer that may help others in the future, adding $index as a parameter to the method should work. Also, the $scope.inputValue = null; is not needed since the inputValue variable only exists on the scope that is created for the ng-repeat.
HTML:
<td id="{{'redScore'+($index+1)}}">
<input required
ng-change="updateRedScore(inputValue, $index)"
ng-model="inputValue"
type="number"
step="1"
name="rate"
min="1"
max="10">
</td>
JS:
$scope.redRoundScore = [];
$scope.updateRedScore = function(passedscore, index) {
$scope.redRoundScore[index] = passedscore
}

Related

Finding the value of multiple input boxes

I'm building a multiple quantity selector for my store. Image below:
On the site, the price of the product updates based on the quantity added. 10 products = 10% off etc. I'd like to be able to display this price change as and when the user edits any one of the input boxes in the quantity selector.
The input fields are built like this:
<div data-value="S" data-varientid="8195426353207" class="swatch-element swatch-element-2 size s available">
<input id="swatch-0-s" data-variant-id="variant_8195426353207" type="checkbox" name="option-0" value="S">
<label for="swatch-0-s">
S
<img class="crossed-out" src="//cdn.shopify.com/s/files/1/0020/2188/3959/t/2/assets/soldout.png?5180939831627851747" alt="">
</label>
<input id="qty" name="quantity" class="swatchinput" placeholder="0" value="0" type="text">
</div>
I'm able to watch the input boxes for change by doing the below:
var qty = $('.swatchinput');
$('.swatchinput').on('paste keyup', function() {
console.log(qty);
});
However, this returns the information about the element rather than the contents. I'm also unsure of the best way to then add the contents of the various input fields together to reach the total quantity.
You could also use the Array reduce method to do this. Select all the inputs, get the array, then reduce their values into the sum.
var total = $('.swatchinput').get().reduce(function(total, input){
return total + parseInt(input.value || '0');
}, 0);
console.log(total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="quantity" class="swatchinput" placeholder="0" value="1" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="2" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="3" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="4" type="text">
This needs to be
var qty = $('.swatchinput').val();
not
var qty = $('.swatchinput');
As for your second question,
loop each of these inputs, getting the value, then add them up with a total. Initialize the total OUTSIDE of the loop also so it doesn't overwrite it.
Something like this?
var total = 0;
$('.switchinput').each(function(){
total += $(this).val();
});
console.log(total);
To get the value of an element in jQuery, use .val():
http://api.jquery.com/val/
.each loops through each matched element and runs a function on that element (accessible through 'this')
http://api.jquery.com/each/

Calculate 2 sets of input types using javascript in one html page

I have 2 set of input types of text boxes. 2 fields on each. I am trying to calculate and compare each set individually in single page.
The input types have different ids.
<input type="text" id="tmcp_textfield_1" name="blueberry"
placeholder="blueberry" value="0" onkeydown="calculate()"
onkeyup="calculate()">
<input type="text" id="tmcp_textfield_2" name="plums" placeholder="plums" value="0"
onkeydown="calculate()" onkeyup="calculate()">
<input type="text" id="a3" name="a3" placeholder="a3" value="0">
<br>second set below<br>
<input type="text" id="tmcp_textfield_3" name="blueberry"
placeholder="blueberry" value="0" onkeydown="calculate()"
onkeyup="calculate()">
<input type="text" id="tmcp_textfield_4" name="plums" placeholder="plums" value="0"
onkeydown="calculate()" onkeyup="calculate()">
<input type="text" id="a3`" name="a3" placeholder="a3" value="0">
My javascript in header:
For First set:
<script type="text/javascript">
calculate = function() {
var blueb = parseFloat($('#tmcp_textfield_1').val());//document.getElementById('blueberry').value;
var plumsb = parseFloat($('#tmcp_textfield_2').val());//document.getElementById('plums').value;
var thetotal = /*document.getElementById('a3').value =*/ parseInt(blueb)+parseInt(plumsb);
if (thetotal > 6) {
$('#tmcp_textfield_2').val('');
$('#tmcp_textfield_1').val('');
alert('Combination must be below 6');
}
}
</script>
For Second Set:
<script type="text/javascript">
calculate = function() {
var blueb = parseFloat($('#tmcp_textfield_3').val());//document.getElementById('blueberry').value;
var plumsb = parseFloat($('#tmcp_textfield_4').val());//document.getElementById('plums').value;
var thetotal = /*document.getElementById('a3').value =*/ parseInt(blueb)+parseInt(plumsb);
if (thetotal > 12){
$('#tmcp_textfield_4').val('');
$('#tmcp_textfield_3').val('');
alert('Combination must be below 12');
}
}
</script>
The problem only the first set of calculation work. When i remove the first set of javascript then the second set only work and vise versa.
How could i differentiate the sets in javascript so that both the set of inputs work together in one single html page.
Problem:
You are having same name functions "calculate()" for both sets that's why only 1 is working at a time.
Solution:
Rename the function name to different names like calculateOne() and calculateTwo() then both will work.
Hope this helps

Java Script Function Not working in second loop

When the page load the loop start and the java script function also work in the first row of loop but in the second loop it not working the multiplication does not work you can see in the pic ( unit rate * quantity = total price)
foreach($db->getRecordSet($sqlTrRecord) as $row){$counter += 1; ?>
<tr id="temTr" class="banktblhd">
<td width="5"> <?php echo($counter); ?> </td>
<td class="w10"> <input type="text" name="item_code" id="item_code" class="form-control" value="<?php echo($row['item_code']); ?>" readonly /></td>
<td class="w20"><input type="text" class="form-control" name="item_name" id="item_name" value="<?php echo($row['item_name']); ?>" readonly /> </td>
<td class="w10"><input type="text" class="form-control" name="description" id="description" value="<?php echo($row['description']); ?>" readonly /></td>
<td class="w10"><input type="text" class="form-control" name="availableQty" id="availableQty" value="<?php echo($row['quantity']); ?>" readonly /></td>
<td class="w10"><input type="text" class="form-control" name="unit_rate" id="unit_rate" onKeyUp="total()" value="<?php echo($row['unit_rate']); ?>" readonly /></td>
<td class="w10">
<input type="number" class="form-control" name="quantity" id="quantity" onKeyUp="total()" autocomplete="off" /> </td>
<td class="w10"><input type="text" class="form-control" name="total_price" id="total_price" value="" />
</td>
</tr>
--------------------------
function total(){
var unitRate= document.getElementById("unit_rate");
var qty = document.getElementById("quantity");
var total = unitRate.value * qty.value;
document.getElementById("total_price").value = total;
}
You cannot give the same ID to more than one element. It's invalid HTML. If you do, getElementById will typically return the first (but it could do anything, including returning none, since again it's invalid).
In your case, the minimal changes necessary to make this work are:
Remove all those ids in the rows, you don't need them. Keep the names on the inputs.
Pass this into total everywhere you call it so it knows what element the keyup occurred on, e.g.:
<input type="number" class="form-control" name="quantity" onKeyUp="total(this)" autocomplete="off" />
<!-- --------------------------------------------------------------------^^^^ -->
Update total to receive that as a parameter, and to find the various inputs in the same row by traversing the DOM:
function total(element) {
var row = element.closest("tr");
var unitRate = row.querySelector("input[name=unit_rate]");
var qty = row.querySelector("input[name=quantity]");
// (Note you're relying on implicit coercion from string to number here)
var total = unitRate.value * qty.value;
row.querySelector("input[name=total_price]").value = total;
}
That works by finding the row containing the element the event occurred on, and then using Element#querySelector with CSS selectors to find the various inputs within that row.
Note that that uses Element#closest, which is fairly new. To avoid using it, you could replace
var row = element.closest("tr");
with
var row = element;
while (row && row.tagName !== "TR") {
row = row.parentNode;
}
A couple of side notes:
keyup isn't a reliable event to use to update the total field, because it doesn't fire if the user updates the field via the mouse (for instance, right-clicking and choosing paste from the context menu). I'd suggest using the input event.
Using onxyz-attribute-style event handlers is not best practice, not least because they can only call global functions (or methods on the element, containing form if any, etc.). Instead, you could use an event handler registered on the table and use the target of the event object to know which element the event targeted (and thus what row to work in). That's possible because input and keyup both bubble.

binding JavaScript slider values to variables

I’m trying to figure out how to store JavaScript slider values as variables, to use later on for d3.js.
In the head of my html doc I have 6 sliders, each which displays 0-100 value.
I want to assign the slider values as variables – one variable for each slider. At each point in time, of course, each slider will only have one value.
But the idea is that I can change the slider position to change the slider value, and then hit an update button and then the newer slider values will become the new variable values.
I’ve tried a variety of different naming methods but none seems to be the right syntax.
What I am caught up on, is how to refer to the (slider) form by id or name or input id, which is html, when I create JavaScript variables for the values that are selected using the sliders.
Any ideas on how I can get this to work?
I searched online and could not readily find a solution on how to do this, or even a template to go off of. Any suggestions are welcome. Thanks!
Code is posted below (I took away my non-working attempts and replaced with hard coded values as an example for what slider positions could look like):
<p>
<form name = "weight1" id = "weight1" >
<text><b> weight1 </b></text> <input id="weight1" input type="range" name="weight1" min="0" max="100" value="0" step="1" onchange="showValue(this)" />
<span id="range">0</span>
<script type="text/javascript">
function get_nextsibling(n) {
x=n.nextSibling;
while (x.nodeType!=1) {
x=x.nextSibling; }
return x; }
function showValue(self) {
get_nextsibling(self).innerHTML=self.value; }
</script>
</form>
<form name = "weight2" id = "weight2" >
<text><b> weight2 </b></text> <input id="weight2" input type="range" name="weight2" min="0" max="100" value="0" step="1" onchange="showValue(this)" />
<span id="range">0</span>
</form>
<form name = "weight3" id = "weight3" >
<text><b> weight3 </b></text> <input id="weight3" input type="range" name="weight3" min="0" max="100" value="0" step="1" onchange="showValue(this)" />
<span id="range">0</span>
</form>
<form name = "weight4" id = "weight4" >
<text><b> weight4 </b></text> <input id="weight4" input type="range" name="weight4" min="0" max="100" value="0" step="1" onchange="showValue(this)" />
<span id="range">0</span>
</form>
<form name = "weight5" id = "weight5" >
<text><b> weight5 </b></text> <input id="weight5" input type="range" name="weight5" min="0" max="100" value="0" step="1" onchange="showValue(this)" />
<span id="range">0</span>
</form>
<form name = "weight6" id = "weight6" >
<text><b> weight6 </b></text> <input id="weight6" input type="range" name="weight6" min="0" max="100" value="0" step="1" onchange="showValue(this)" />
<span id="range">0</span>
</form>
</p>
<script type="text/javascript">
//put JavaScript function that makes each slider a variable, or just assign slider values directly to variables if easier...then use in body
var weightfactor1 = 0 ; //want this variable to be the form output value instead of hard coded values between 0-100 ...so weight1 slider
var weightfactor2 = 100 ; //want this variable to be weight2 slider value
var weightfactor3 = 10 ; //want this variable to be weight3 slider value
var weightfactor4 = 100 ; // " "" weight4
var weightfactor5 = 12 ; // " "" weight5
var weightfactor6 = 100 ; // " "" weight6
</script>
See: http://jsbin.com/ISekuSiN/5 for an example of the working sliders (solution that was provided to a prior question I had about this, Displaying values from multiple JavaScript slider values )
Couple of suggestions:
Make sure your html has been rendered before running your JavaScript
For the case above case you can use the document object as follows:
var weightFactor1 = document.getElementById("weight1").value;

Choosing data from field

I'm a newbie in terms of js, and I need to make such a calculator that does not provide data, but takes them from the field. For illustration I did this file
jsfiddle.net/HHv3y/3/
<input id="id1" type="range" min="1" step="1" max="6" value="1" onChange="sliderChange(); setValue1(this.value)" />
<br>
<input id="id2" type="range" min="1" max="4" value="1" step="1" onChange="sliderChange(); setValue2(this.value)" />
result: <span id="sliderStatus">12</span>
There are only two sliders (1 - 6 steps long) and a field for the result. In the jsFiddle is an example of a field which I would like to set.
I just need to show the value of the intersections of the two sliders, which represents an adequate entry field.
Try this simple approach.
function sliderChange() {
var var1 = document.getElementById('id1').value;
var var2 = document.getElementById('id2').value;
if (var1 == var2) { //If both values are equal show the result
document.getElementById('sliderStatus').innerHTML = var1;
} else {
alert('Not interscted');
}
}
Whenever the values are equal, the resultant value will be displayed.
JSFiddle

Categories

Resources