Javascript - Compare 2 input split arrays and output the difference - arrays

I have 2 inputs both containing a list of numbers separated by a '|'.
I need to check if any of the ids from the first input exist in the second and if it doesn't add it to a third.
<input type="text" id="access_ids" value="13|16|24|25|31|33|36|42|43|45|48|49|58|59|61|8" /><br />
<input type="text" id="replied_ids" value="8|9|16" /><br />
<input type="text" id="not_replied_ids" value="" />
.
$(document).ready(function(){
var acc_ids = $('#access_ids').text();
var acc_array = acc_ids.split('|');
for (var i = 0; i < acc_array.length; i++) {
if (acc_array[i].indexOf($('#replied_ids')) > -1) {
$('#not_replied_ids').text(acc_array[i].join('|'));
return;
}
}
});
I made a jsfiddle:
https://jsfiddle.net/sheferd/nhj63fbu/1/
Thanks

You are wrong syntax, ex: $('#access_ids').text() --> $('#access_ids').val() ... You can try follow code:
$(document).ready(function(){
var acc_ids = $('#access_ids').val();
var acc_array = acc_ids.split('|');
var not_replied_arr = [];
for (var i = 0; i < acc_array.length; i++) {
if ($('#replied_ids').val().indexOf(acc_array[i]) == -1) {
not_replied_arr.push(acc_array[i]);
$("#not_replied_ids").val(not_replied_arr.join("|"));
return;
}
}
});

Related

Make React Properties not Tied to Specific Variables

I'm trying to create a group of react elements through a for loop. However, it seems that, rather than each element getting its own copy of the variables per for loop, they are tied to whatever the variable is at the end of the for loop (where i = 3). How can I prevent this. Thanks.
makeCheckboxes() {
var checkboxes = [];
for(var i = 0; i < this.props.flagNames.length; i++) {
console.log("Making checkbox. i = " + i);
checkboxes.push((
<React.Fragment>
<label><input type="checkbox" name="reportFlags" value="fraud" checked={this.state.reportFlags[i]} onClick={() => this.handleCheck(i)}/>{this.props.flagNames[i]} </label><br />
</React.Fragment>
));
}
return checkboxes;
};
just replace
for(var i = 0; i < this.props.flagNames.length; i++) {
by
for(let i = 0; i < this.props.flagNames.length; i++) {
actually it will create a closure, so it should sove the problem
if you still want to use var you can change your code like this using immediately-invoked function expression iife
for(var i = 0; i < this.props.flagNames.length; i++) {
console.log("Making checkbox. i = " + i);
checkboxes.push((
<React.Fragment>
<label>
<input
type="checkbox"
name="reportFlags"
value="fraud"
checked={this.state.reportFlags[i]}
onClick={((j) => () => this.handleCheck(j))(i)} //here is the iife
/>
{this.props.flagNames[i]}
</label><br />
</React.Fragment>
));
}
return checkboxes;

How to Display the first 20 messages in the DB

I found this code in the internet, it functions as a message box. The code works perfectly fine. However, it display all the messages stored in the file message.db.
My question is, how can I make it display only the last 20 posted messages? I'm sorry for asking this. I have no knowledge about programming. I appreciate any help...
Here is the snippet of the code:
<div class="container" ng-controller="MessageBoardCtrl">
<form>
<input type="email" placeholder="Email Address" ng-model="email" required/>
<textarea placeholder="Advertise your link here for Free..." rows="5" style="width:90%" ng-model="message" required=""></textarea>
<button class="btn btn-primary" ng-click="sendMessage()">Post</button>
</form>
<p>{{item.message}}</p>
<script>
function MessageBoardCtrl($scope, $http, $timeout) {
$scope.items = [];
$scope.message = '';
$scope.email = '';
$scope.lastTime = 0;
$scope.refreshMessages = function() {
$http.get('../templates/faucet.php/messages?time=' + $scope.lastTime).success(function(data) {
for(id in data) {
item = data[id];
$scope.items.unshift(item);
if($scope.lastTime<item.time)
$scope.lastTime = item.time;
}
});
}
$scope.sendMessage = function() {
if(!$scope.message)
return;
$http.post('../templates/faucet.php/add_message', {message: $scope.message, email: $scope.email}).success(function() {
$scope.message = '';
$scope.refreshMessages();
});
}
$scope.periodicRefresh = function() {
$scope.refreshMessages();
$timeout($scope.periodicRefresh, 5000, true);
}
$scope.periodicRefresh();
}
</script>
I found this function to limit the result:
function limitToFilter(){
return function(array, limit) {
if (!(array instanceof Array)) return array;
limit = int(limit);
var out = [],
i, n;
// check that array is iterable
if (!array || !(array instanceof Array))
return out;
// if abs(limit) exceeds maximum length, trim it
if (limit > array.length)
limit = array.length;
else if (limit < -array.length)
limit = -array.length;
if (limit > 0) {
i = 0;
n = limit;
} else {
i = array.length + limit;
n = array.length;
}
for (; i<n; i++) {
out.push(array[i]);
}
return out;
}
}
Now, I just need help on how to combine them together to make the script work. I hope someone can help. I really do not have any idea... Thanks.

Submit validation in anjularjs

Let say I have the following codes:-
<form name="table" ng-submit="createtable()">
<input type="number" ng-model="tab.num" required></input>{{win.numR}}
<button>Save</button>
</form>
I will be adding number in this order(1,2,3,4,5,6). What I want to achieve is e.g.
I have input 1,2, and then when I input 6 it prevents me from adding the 6 because I need to add the 3, the 4 and the 5 before the 6.
thanks for the help.
Here's a full Plunkr to help you out.
http://plnkr.co/edit/1GK1JjFLoCJQd4K3l6eh?p=preview
I am using ui-validate to simplify. I suggest using this module to simplify your validation code.
var application = angular.module("validator", ["ui.validate"]);
application.controller("ValidatorExampleController", ['$scope', function($scope) {
$scope.numberStationValidationFn = function(value) {
if(angular.isUndefined(value)) {
return true;
}
for(var i = 1; i <= value.length; i++) {
if(value[i - 1] != i) {
return false;
}
}
return true;
};
}]);
Add ng-valid attribute to your input and implement a method which will set the input valid to either true or false:
<input type="number" ng-model="tab.num" ng-valid="inputIsValid(tab.num)" required>
In your controller:
$scope.inputIsValid = function(str) {
// check if str is valid and return true or false
}

Apply Range Validation for Input Value AngularJS

When an user entering a value, system should check whether this value is within the range of Minimum and Maximum defined for this field. also, need check for number of decimal points allowed.
<input ng-model='data.value1' >
<input ng-model='data.value2' >
<input ng-model='data.value3' >
<input ng-model='data.value4' >
you can add type="number". and for angularJS
<input type="number"
ng-model=""
[name=""]
[min=""]
[max=""]
[required=""]
[ng-required=""]
[ng-minlength=""]
[ng-maxlength=""]
[pattern=""]
[ng-pattern=""]
[ng-change=""]>
Follow the link for more clarification
AngularJs Documentation
Extending My comment:
var range = 'your range';
var checkRange = function () {
var value = data.value;
if(value <=range) {
//your code;
} else {
//your code;
}
}
Update:
$scope.data.value = 500;
$scope.$watch('data.value', function (oldVal,newVal) {
if(newVal > 1000 ) {
$scope.data.value = 500;
}
})

AngularJS : Two-way binding between a textarea and ng-repeat-ed inputs

I was going to ask this as a question, but I figured out a solution. So at this point, I'm looking for a critique of my solution.
I've got a static textarea, and an input with an ng-repeat directive.
As the user types a sentence into the textarea, a input is rendered for each word in the sentence.
Then if the user updates the text in any input, the corresponding word in the textarea sentence is updated (really the whole sentence is recreated).
Demo: http://plnkr.co/edit/bSjtOK?p=preview
Questions
Keeping in mind that I'm only 2 weeks into my AngularJS learning:
Did I write this in the "angular" way?
Is there something I could have done better?
Am I violating any no-nos?
Abbreviated Code
HTML
<textarea ng-model="sentence" ng-change="parseSentence()" style="width: 100%; height: 15em;"></textarea>
<input type="text" ng-repeat="w in words" ng-model="w.word" ng-change="buildSentance(w)" />
JavaScript
function WordCtrl($scope, debounce) {
$scope.words = [];
$scope.sentence = 'Hello there how are you today?';
// this is called when the textarea is changed
// it splits up the textarea's text and updates $scope.words
$scope.parseSentence = function() {
var words = $scope.sentence.split(/\s+/g);
var wordObjects = [];
for (var i=0;i<words.length;i++) {
wordObjects.push({word: words[i]});
}
if ((words.length == 1) && (words[0] === '')) {
$scope.words = [];
} else {
$scope.words = wordObjects;
}
};
$scope.parseSentenceDebounced = debounce($scope.parseSentence, 1000, false);
$scope.buildSentance = function(w) {
var words = [];
for (var i=0;i<$scope.words.length;i++) {
var word = $scope.words[i].word;
if (word.replace(/\s+/g,'') !== '') {
words.push(word);
}
}
$scope.sentence = words.join(' ');
// if the user puts a space in the input
// call parseSentence() to update $scope.words
if (w.word.indexOf(' ') > -1) {
$scope.parseSentenceDebounced();
}
}
$scope.parseSentence();
}
Interesting issue you are having. I put your code on my page and the first thing I noticed is that you cannot pass debounce in the controller method.
Next Problem I noticed is that you have an ng-change that changes the values on another box with ng-change. I changed the event to Keypress to stop the digest in a digest.
Here it is working in JSFiddle enter link description here
The code:
HTML
<body ng-app="portal">
<div ng-controller="WordCtrl">
<textarea ng-model="sentence" ng-keypress="parseSentence()" style="width: 100%; height: 15em;"></textarea>
<input type="text" ng-repeat="w in words" ng-model="w.word" ng-keypress="buildSentance(w)" />
</div>
</body>
Javascript
angular.module("portal",[]).controller("WordCtrl",function($scope) {
$scope.words = [];
$scope.sentence = 'Hello there how are you today?';
$scope.parseSentence = function () {
var words = $scope.sentence.split(/\s+/g);
var wordObjects = [];
for (var i = 0; i < words.length; i++) {
wordObjects.push({ word: words[i] });
}
if ((words.length == 1) && (words[0] === ''))
{
$scope.words = [];
}
else
{
$scope.words = angular.copy(wordObjects);
}
}
$scope.buildSentance = function (w) {
var words = [];
for (var i = 0; i < $scope.words.length; i++) {
var word = $scope.words[i].word;
if (word.replace(/\s+/g, '') !== '') {
words.push(word);
}
}
$scope.sentence = words.join(' ');
// if the user puts a space in the input
// call parseSentence() to update $scope.words
if (w.word.indexOf(' ') > -1) {
$scope.parseSentenceDebounced();
}
}
$scope.parseSentence();
});
Hope this solves your issue.

Resources