Knockout foreach generate html fields - html

I want to display as many fields as user wants.
Maybe you have idea how can I do this case using foreach loop in Knockout framework.
For example numberOfFields is input field where user can enter how many fields he wants to display
<input id="numberOfFields" type="text" data-bind="value: obj().numberOfFields() />
<div data-bind="foreach: new Array(obj().numberofCashFlows())">
<label for="quantity$index()">Flow number $index()</label>
<input id="quantity$index()" type="text" data-bind="value: quantityArray[$index()]" />
</div>
Of course code doesn't work, I want to tell you what I mean.
If user enters 3 I want to show 3 labels and inputs with id quantity1, quantity2, quantity3 and with values: quantityArray[0], quantityArray[1], quantityArray[2]
Can you help me or give some advice?

If I got your question right, this should be it by approx. I've also added and observable to the Quantity to show you how you could expand on the example with bound properties.
console.clear();
function Quantity(id, label) {
var self = this;
self.id = id;
self.label = ko.observable(label);
};
ko.applyBindings(() => {
var self = this;
self.amount = ko.observable(0);
self.quantity = ko.observableArray([]);
self.amount.subscribe(function(amount) {
var quantity = self.quantity().length;
amount = Number(amount);
if (amount > quantity) {
for (var i = quantity; i < amount; i++) {
self.quantity.push(new Quantity(i+1, 'label for ' + (i+1)));
}
} else if (amount < quantity) {
var minus = quantity - amount;
for (var i = 0; i < minus; i++) {
self.quantity.pop();
}
}
});
self.amount(2);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<label>amount: </label>
<input type="number" data-bind="textInput: amount" min="0" />
<div data-bind="foreach: quantity">
<input type="text" data-bind="textInput: label, attr: { placeholder: 'label for ' + id }" /><span data-bind="text: label"></span><br />
</div>

Related

assign value from two input to a single input type hidden

I am trying to get the value of first input or second input and assign it to a hidden input type. When the value updates from the above default value.
HTML
<input id="amount2" name="s_value6" type="number" value="48">
<input id="amount3" name="s_value11" type="number" value="500">
<input id="mak" type ="hidden" name="distance" value="">
jQuery
if(mafsForm.find("#amount3").val().length !== 0 || mafsForm.find("#amount2").val().length !== 0) {
var s_value11 = mafsForm.find("#amount3").val();
var s_value6 = mafsForm.find("#amount2").val();
var dist = $('#mak').val($(this).val());
}
Hope this is what you are looking for. To test this, remove 'hidden' from the hidden input field. Then change the value of any of the first two input boxes. On every change, 3rd input box will be updated with latest value. Below code only shows latest value from the last updated input box
$("#amount2, #amount3").change(function(){
var changedVal = $(this).val();
if(changedVal !== '0'){
$("#mak").val(changedVal);
}
});
This is a working example of pure javascript ...
<input id="amount2" name="s_value6" type="number" value="48">
<input id="amount3" name="s_value11" type="number" value="500">
<input id="mak" type="hidden" name="distance" value="">
<script>
var amnt2 = document.getElementById("amount2");
var amnt3 = document.getElementById("amount3");
var mak = document.getElementById("mak");
amnt2.addEventListener("change", function(event) {
setValue(this.value);
});
amnt3.addEventListener("change", function(event) {
setValue(this.value);
});
function setValue(num) {
mak.value = num;
}
</script>
The mafsForm variable was not assigned a selector in your code, so instead of mafsForm.find(selector).val() I wrote $(selector).val(). Also, I used the parseInt() method to convert the value to a number for summation. You can easily adapt this code for yourself.
$('#amount2, #amount3').on('change', function() {
var s_value11 = $("#amount3").val();
var s_value6 = $("#amount2").val();
if(s_value11.length !== 0 || s_value6.length !== 0) {
value_sum = parseInt(s_value11) + parseInt(s_value6);
console.log(value_sum);
var dist = $('#mak').val(value_sum);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="amount2" name="s_value6" type="number" value="48">
<input id="amount3" name="s_value11" type="number" value="500">
<input id="mak" type ="hidden" name="distance" value="">
Your issue is that $(this) is referencing the window object. Here's a working solution:
var mafsForm = $('#mafsForm');
var dist;
if(mafsForm.find("#amount3").val().length !== 0 || mafsForm.find("#amount2").val().length !== 0) {
var s_value11 = mafsForm.find("#amount3").val();
var s_value6 = mafsForm.find("#amount2").val();
dist = $('#mak').val(s_value11);
};
console.log(dist.val());
// Now if you want to update the value of the hidden value when changing the value of a filed you can do this
mafsForm.find("#amount3").on('input', function() {
var s_value11 = mafsForm.find("#amount3").val();
dist = $('#mak').val(s_value11);
console.log(dist.val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<form id = "mafsForm">
<input id="amount2" name="s_value6" type="number" value="48">
<input id="amount3" name="s_value11" type="number" value="500">
<input id="mak" type ="hidden" name="distance" value="">
</form>

restrict input type="text" only to numbers and show default first 3 numbers in input box in react js

I am using an input type text and i want to restrict the input box to only numbers and first 3 numbers of input box are default numbers like 750
I tried regex but its not working
Here is my HTML Code:
<input custom="full-width" autoComplete="off" placeholder="optional" type="text" value={DFAmngt['item']} name="DFAmngt" pattern="[0-9]*" onChange={this.searchPartSuggestions.bind(this)} required disabled={statusCancelled}/>
JS Code:
let { name, value } = e.target;
let { masterData, masterDataReducer } = this.props;
console.log(masterData,masterDataReducer);
let { DFAmngt } = masterDataReducer;
console.log(DFAmngt);
const re = /^[0-9\b]+$/;
if (value === '' || re.test(value)) {
DFAmngt['item'] = value;
// DFMMannualIssue[name+"Error"]='';
console.log(DFAmngt['item']);
}
masterData[name] = value;
if(name === 'DFAmngt'){masterDataReducer[name]['item'] = value;}else{masterDataReducer[name] = value; }
// this.props.updateMasterData(masterData,"masterData");
this.props.updateMasterReducer(masterDataReducer);
this.props.partSuggestions(value,name);
}
This solution doesn't allow negative numbers, e, +, - etc. Reference
<input type="number" name="test_name" min="0" oninput="validity.valid||(value='');">

after clicking on button the data should be filtered between 2 dates- Angularjs

scope.routeToTxn = function(){
route.reload();
location.path('/tellers/' + routeParams.tellerId + "/cashiers/" + routeParams.cashierId +"/txns/" + scope.formData.currencyCode);
return function( item, startdate,enddate ) {
var filtered = [];
var txnstartDate = Date.parse(txnstartDate);
var txnendDate = Date.parse(txnendDate);
angular.forEach(item, function(item) {
if(item.completed_date > txnstartDate && item.completed_date < txnendDate) {
filtered.push(item);
}
});
return filtered;
};
};
<td class="col-md-2">
from date:
<input id="startDate" sort type="text" datepicker-pop="dd MMMM yyyy" ng-model="txnstartDate" class="form-control" is-open="opened" min="minDate" max="restrictDate"/>
</td>
<td class="col-md-2">
To date:
<input id="endDate" sort type="text" datepicker-pop="dd MMMM yyyy" ng-model="txnendDate" class="form-control" is-open="opened" min="minDate" max="restrictDate"/>
</td>
<td>
<a ng-click="routeToTxn()" class="btn btn-primary">{{'label.button.cashier.showtxn' | translate}} </a>
</td>
after clicking on search button the data should be filtered via 2 dates :
there are two insert boxes which will take 2 dates starting date and end date and after clicking on search box the data filtered data should be seen
Check at this snippet you probably want to format those dates so when you compare them they actually compare
https://jsfiddle.net/Lt7aP/14764/
formater used from this answer
https://stackoverflow.com/a/29774197/8101253
html
<div ng-app ng-controller="Ctrl">
<input ng-model="date1" type="date"></input>
<input ng-model="date2" type="date"></input>
<input type="submit" ng-click="compare(date1, date2)"></input>
{{array}}
</div>
javascript
function Ctrl($scope) {
$scope.array = [new Date("2018-11-06").toISOString().split('T')[0],
new Date("2018-11-07").toISOString().split('T')[0],
new Date("2018-11-09").toISOString().split('T')[0]
];
$scope.compare = function(date1, date2) {
$scope.array
.filter(x => {
console.log(x, date1, date2)
return x > date1 && x < date2
})
.forEach(x => console.log(x));
};
}

Ionic pass data

I got these codes online and below are what the codes are supposed to achieve as stated by the owner.
The user can add a new contact (name, email address and phone number)
List of contacts should be shown
The user can delete any contact from the contact list
The User can edit any contact from the contact list
However, when I tried it out, there is a default data in the contact list and if I want to add/save additional data to the contact list, it will only save the data in the contact list after I edit what one of the data which was already in the contact list.
enter image description here
Below are the codes:
1. HTML:
<ion-view view-title="Dashboard">
<ion-content class="padding">
<div>
<form>
<label>Name</label>
<input type="text" name="name" ng-model="newcontact.name"/>
<label>Email</label>
<input type="text" name="email" ng-model="newcontact.email"/>
<label>Phone</label>
<input type="text" name="phone" ng-model="newcontact.phone"/>
<br/>
<input type="hidden" ng-model="newcontact.id" />
<input type="button" value="Save" ng-click="saveContact()" />
</form>
<table border='1',cellpadding='10',cellspacing ='0', width ='600'>
<tr>
<td Align = 'center'>Name</td>
<td Align = 'center'>Email</td>
<td Align = 'center'>Phone</td>
<td Align = 'center'>Action</td>
</tr>
<tr ng-repeat="contact in contacts">
<td Align = 'center'>{{ contact.name }}</td>
<td Align = 'center'>{{ contact.email }}</td>
<td Align = 'center'>{{ contact.phone }}</td>
<td Align = 'center'>
edit |
delete
</td>
</tr>
</table>
</div>
</ion-content>
</ion-view>
2.JS: (controller)
angular.module('starter.controllers', [])
.controller('DashCtrl', function($scope, ContactService) {
$scope.contacts = ContactService.list();
$scope.saveContact = function () {
ContactService.save($scope.newcontact);
$scope.newcontact = {};
}
$scope.delete = function (id) {
ContactService.delete(id);
if ($scope.newcontact.id == id) $scope.newcontact = {};
}
$scope.edit = function (id) {
$scope.newcontact = angular.copy(ContactService.get(id));
}
})
(services)
angular.module('starter.services', [])
.service('ContactService',function() {
var uid = 1;
var contacts = [{
id: 0,
'name': 'Viral',
'email': 'hello#gmail.com',
'phone': '123-2343-44'
}];
//save method create a new contact if not already exists
//else update the existing object
this.save = function (contact) {
if (contact.id == null) {
//if this is new contact, add it in contacts array
contact.id = uid++;
contacts.push(contact);
} else {
//for existing contact, find this contact using id
//and update it.
for (i in contacts) {
if (contacts[i].id == contact.id) {
contacts[i] = contact;
}
}
}
}
//simply search contacts list for given id
//and returns the contact object if found
this.get = function (id) {
for (i in contacts) {
if (contacts[i].id == id) {
return contacts[i];
}
}
}
//iterate through contacts list and delete
//contact if found
this.delete = function (id) {
for (i in contacts) {
if (contacts[i].id == id) {
contacts.splice(i, 1);
}
}
}
//simply returns the contacts list
this.list = function () {
return contacts;
}
});
codes credit to : https://viralpatel.net/blogs/angularjs-service-factory-tutorial/

Javascript how to allow array to take more than one digit?

I've been trying lately to build up a mean calculator using html and javascript. i want to take all the inputs from the one text box add them to an array and get the average result. what i did in the following code takes only one digit because of str[i-1] is there any other alternative way of doing it? Thanks!
Output photo
function calculate()
{
var str= document.getElementById("meanvalue").value;
for(var i=0; i<str.length; i++)
{
if(str[i] == ".")
{
sum+=parseInt(str[i-1]);
count++;
}
}
sum/=count;
document.getElementById("meanresult").value=sum;
}
Here is a small example:
document.getElementById('input').onkeyup = function() {
this.value = this.value.replace(/[^0-9\.]/gi, '');// restrict non digit
var sum = 0;
var array = this.value.split(/\./);
array.forEach(function(str) {
sum += (parseInt(str, 10) || 0); //avoid NaN
});
document.getElementById('output').value = (sum / array.length || 0);// avoid NaN
}
<input type="text" id="input" />
<input type="text" id="output" readonly='' />
i just want to know how the values are updated while im typing my
inputs automatically
Here, I am using onkeyup event to handle user input.
document.getElementById('input').onkeyup = function() {
document.getElementById('output').value = this.value;//get input, set output
}
<input type="text" id="input" />
<input type="text" id="output" readonly='' />
You can use the split function on the input. I give you a quick example here :
var string = "1.3.45.7";
var array = string.split(".");
// array = [1, 3, 45, 7]
document.write(array);
First split your str and than use for loop.
var str= document.getElementById("meanvalue").value.split('.');
Also remove your if condition inside the loop.
for(var i=0; i<str.length; i++)
{
//if(str[i] == ".")
// {
sum+=parseInt(str[i-1]);`
count++;
// }
}
sum/=count;
document.getElementById("meanresult").value=sum;
hope this helps you.