Take one parameter from tokeinput JS - javascript

i use tokeinput "good plugin" with PHP and JSON work very good but now i need to take only 1 parameter from tokeinput form and use in JS. I need to take the parameter id the tokens are limit 1
$('.tags').tokenInput("get"); // for take all parameters and now i want only id
// and?
Thank you so much :)

The above will return you an array of Javascript objects. If you're only allowing the selection of one item at a time, then just select the ID of the first object in your returned array
var objArr = $('.tags').tokenInput("get");
var objID = objArr[0].id;
You may also want to check that there IS an item selected, depending on how you're implementing.

Related

How to change the array elements proprity in javascript?

I am adding the new task using following javascript code:
function addTask(name, important){
alert(important);
const newTask = {id: "todo" + nanoid(), name:name, completed:false, important:important, checked:false};
setTasks([...tasks, newTask]);
console.log(setTasks)
}
Now, I would like to add the last task on the first place of the application. May I ask please how to make it possible?
setTasks([newTask, ...tasks]);
Is the cleanest way to add items in front, however later on it may prove inconsistent (after saving into db for example and retrieving the list from db), personally I would use array.sort() method and sort the array by creation date or / and by "important" key. This way, no matter how you push an item into array, they will be always in correct / needed order.

how to bind values to an object in order of insertion

I have some inputs, and I want to get data in order of insertion, for example: if I insert the value bbb then the value aa I want to get bbb befor aa
I search in the net and find that this order is ensured using Mapbut I don't know how to use it with ng-model.
thank you in advance.
EDIT
I'm using an object that store the value of the inputs and a customized key passed with value
here is an example, if you insert the values in input 3 then 2 then 1, and click ok, in the console the output will be ordered in an alphabetic order
As stated by #czosel, javascript objects are not ordered, and are usually sorted by alphabetical order of the keys. Therefore, your best solution is probably going to involve going beyond using the ng-model directive as is.
Here are two possibilities you could try out:
Solution 1
In every <input /> place an ng-blur directive that will determine the input's order. For instance:
HTML
<input ng-blur="onBlur('model1')" ng-model="model1" />
<input ng-blur="onBlur('model2')" ng-model="model2" />
controller.js
app.module('myModule').controller('myCtrl', ['$scope', function($scope) {
$scope.count = 0;
$scope.onBlur = function(key){
// check if anything was entered
if($scope[key]){
// make sure this is first time data was entered into this input
if(!$scope[key].order)
$scope[key].order = $scope.count++;
}
};
}]);
Solution 2
Store the values in an array. Similar to the first solution, but instead of keeping count, you would forego the ng-model altogether and manually add the value to an array (after checking that it doesn't already exist, which gets a little tricky with an array). Of course you also have to handle updates yourself, so the first method is definitely going to be simpler. The lodash library will probably be of much help if for some reason you decide to choose this approach.
Lots of luck!
JavaScript Object properties have no guaranteed order, see this answer.
Try using an array instead.
You can Queue(First in First Out) to get data in the order of insertion. Trigger a function and store the values binded in ng-model into queue.
Ex: ng-model = data // here data will be bbb
var queue = [];
function bind(value){
queue.push(value); // value will be bbb
}
if user enters aa then again bind function needs to be called to push the value inside queue
U can get the values in the order of insertion.

pass multidimensional javascript array to another page

I have a multidimensional array that is something like this
[0]string
[1]-->[0]string,[1]string,[2]string
[2]string
[3]string
[4]-->[0]string,[1]string,[2]string[3]string,[4]string,[5]INFO
(I hope that makes sense)
where [1] and [4] are themselves arrays which I could access INFO like myArray[4][5].
The length of the nested arrays ([1] and [4]) can varry.
I use this method to store, calculate, and distribute data across a pretty complicated form.
Not all the data thats storred in the array makes it to an input field so its not all sent to the next page when the form's post method is called.
I would like to access the array the same way on the next page as I do on the first.
Thoughts:
Method 1:
I figure I could load all the data into hidden fields, post everything, then get those values on the second page and load themm all back into an array but that would require over a hundred hidden fields.
Method 2:
I suppose I could also use .join() to concatenate the whole array into one string, load that into one input, post it , and use .split(",") to break it back up. But If I do that im not sure how to handel the multidimensional asspect of it so that I still would be able to access INFO like myArray[4][5] on page 2.
I will be accessing the arrary with Javascript, the values that DO make it to inputs on page 1 will be accessed using php on page 2.
My question is is there a better way to acomplish what I need or how can I set up the Method 2 metioned above?
This solved my problem:
var str = JSON.stringify(fullInfoArray);
sessionStorage.fullInfoArray = str;
var newArr = JSON.parse(sessionStorage.fullInfoArray);
alert(newArr[0][2][1]);
If possible, you can use sessionStorage to store the string representation of your objects using JSON.stringify():
// store value
sessionStorage.setItem('myvalue', JSON.stringify(myObject));
// retrieve value
var myObject = JSON.parse(sessionStorage.getItem('myvalue'));
Note that sessionStorage has an upper limit to how much can be stored; I believe it's about 2.5MB, so you shouldn't hit it easily.
Keep the data in your PHP Session and whenever you submit forms update the data in session.
Every page you generate can be generated using this data.
OR
If uou are using a modern browser, make use of HTML5 localStorage.
OR
You can do continue with what you are doing :)

Safely using eval to use variable as an object name

As shown in this example
javascript-use-variable-as-object-name
I am using eval to use a DOM attribute to select an element from an array. Though there is no direct way for the user to change the input, I want to be as secure as possible and make sure that the variable is indeed an integer before I evaluated it.
Which of the following would be the best, most secure, way?
$(".listitem").click(function(){
var id = $(this).attr("record-id");
if(!isNaN(new Number(id))){
Storage.search.nearby.currec = rowsHolder[eval(id)];
}else{
// send email to admin, shut down
}
});
or
$(".listitem").click(function(){
var id = $(this).attr("record-id");
if(parseInt(id)){
Storage.search.nearby.currec = rowsHolder[eval(id)];
}else{
// send email to admin, shut down
}
});
More, but not required info:
Basically I am pulling down a large JSON string from online, containing an array of records. Upon building a table from the info using a for statement ( for(i in array) ), I push each row into an array called rowsHolder and give the tr an attribute of record-id="i". Then when the user clicks the row, I call the method you see above. I am using PhoneGap with JQuery Mobile.
As always, thanks for the input
-D
There is absolutely no reason to use eval here.
If your id is kind of a number, use parseFloat(id) to get it. Unnecessary as it would be converted back to a string when used as a property name, though.
If your id is an integer, use parseInt(id, 10) to get it. Unnecessary as it would be converted back to a string when used as a property name, though.
If your id is a string, just let it be a string. The property name you use it for would be one anyway.

Capturing form data: variables or array?

I have a form with about 20 input fields. I capture values of these fields, then do some calculations and output several values.
Is there a preferred/recommended way of capturing form data? Currently I store every form field into a separate variable. I was wondering if storing it to an array would be a better and more effective approach.
I'm quite new to Javascript and programming in general, trying to learn the best practices.
My best practice on this depends on what I have to do with the data. If I do not need to loop through it, or send it to another page/service, then there's nothing wrong with individual scoped-variables.
If I need to loop at all, I commonly use an array or object to loop through.
If I have to pass it to another page/service, I make one object variable to encapsulate the rest of them, so I can "stringify" it to JSON and parse back to an object on the other end.
Just my opinion,
Pete
You might consider the third approach - just use the data from the form without storing it anywhere.
First check the correctness, once it is considered correct just use what you have.
You should always assign the attribute "name=..." to an input element, so you can use something like:
var form = document.forms['form'];
var email = form['email'];
email = do something
if you use javascript... if you use jquery it's simple $('input[name="email"]') = do something
I prefer this way because you can call variables by name, not by number, for example "form[0] that corresponds to input[name="email"]".
Use the associative properties of arrays in JavaScript to get the benefits of unique field names and OOP:
var formModel = new Array();
formModel['myField'] = getMyFieldValue(); // make 'myField' index to any object
Then you can do things like:
formModel['myField'] // get the value
formModel.length; // number of fields added
for (entry in formModel) { /* loop thru entries */ }
formModel.sort([compareFunction]) // custom sort
formModel = []; // clear the model
Convert array to JSON
Any of these ArrayMDN conveniences.
Just one approach, but arrays in JS are extremely versatile and IMO underused objects in JS.

Categories

Resources