简体   繁体   中英

Create an associative array in jquery from hidden hashes

I am trying to create an associative array from hidden hashes. The jquery below calls to the specific hashes, but I would like to create this dynamically with one code.

$(document).ready(function() {
     $("#tokens").tokenInput([
         {id: 1, name: "Darren Criss"},
         {id: 2, name: "Ann Arbor T-shirt Company"},
         {id: 3, name: "StarKid Product Store"},
     ]);
 });

I tried to do this:

 $(document).ready(function() {
     var variable = $("input[type='hidden'][class='stores']").val();
      $("#tokens").tokenInput(variable);
 });

but it doesnt work.

here are the hashes

  <input id="1" class="stores" type="hidden" value="Darren Criss" taxonomies_count="9"  
 name="1" disabled="disabled"></input>

 <input id="2" class="stores" type="hidden" value="Ann Arbor T-shirt Company" 
 taxonomies_count="46" name="2" disabled="disabled"></input>

 <input id="3" class="stores" type="hidden" value="StarKid Productions Store" 
 taxonomies_count="22" name="3" disabled="disabled"></input>

Your current code calls tokenInput , but only passes it a single string (the value of the first input element encountered in the DOM. Assuming that these hashes are present in the DOM when the document loads,

  var val = $("input[type='hidden'][class='stores']").val();
  $("#tokens").tokenInput(val);

is functionally equivalent to

$("#tokens").tokenInput("Darren Criss");

which does not match the kind of argument expected by tokenInput (see http://loopj.com/jquery-tokeninput/#installation--setup ) (You seem to have the right idea in your first code example). Why not iterate over a jQuery input selection, pushing new hash objects into a list, and, finally, call tokenInput, passing it the complete list:

$(document).ready(function() {
    var hashes = [];
    $('input.stores').each(function(i, elem) {
        hashes.push({
            'id': $(elem).attr('id'),
            'name': $(elem).val(),
        });
    });
    console.log(hashes);
    //$('#tokens').tokenInput(hashes);
});

EDIT:

what is the i and the elem?

My approach is using jQuery's built-in iterator function each ( http://api.jquery.com/jQuery.each/ ). This utility function allows programmers to easily iterate over existing collections, including objects, arrays, and jQuery selections. Here is the function's signature (for lack of a better term) as seen in jQuery's documentation:

jQuery.each( collection, callback(indexInArray, valueOfElement) )

You can call each on any iterable JavaScript object (eg - foo.each(...); ), although it is more common to see a jQuery selection preceeding the call. each expects you to pass it a callback function that accepts two arguments: an index/key argument, and a value/item argument (as a side note, you also have access to this , an implicit argument referencing the value/item) inside of the body of the callback.

each will call this function once for each item in the collection, automatically passing it the appropriate index/key and value arguments for you, based on the current item in the iteration. jQuery selections are iterable array-like objects: they behave like JavaScript arrays, and their 'items' can be referenced using numerical indexes (eg — Calling $('div')[0] or $('div').get(0) will return a reference to first DOM element matching the div selector, if a div is present on the page).

When we iterate over a jQuery selection, the 'items' that we are iterating over are references to DOM elements. In my example, when I call each on a jQuery selection and provide it with a callback function, i is given the value of the current DOM element's index within the selection, while elem references the actual element. Oftentimes we want to call jQuery methods on these elements inside of the callback function. This requires us to wrap the element as a jQuery object ( $(elem) ), allowing us to manipulate the element using all of jQuery's functionality.

Conventionally, calling each on a jQuery selection follows this form:

$('your selector here').each(function(i,elem) {
    var foo = $(elem); //Allows us to treat the DOM element as a jQuery object
    //Do stuff ... foo.val().attr().css().toggle();
});

Further reading on jQuery objects:

and what does console.log(hashes);

I've simply included a console.log() to let you explore the hash list that is generated. It is not necessary for calling tokenInput .

What you gave as the source are not hashes but HTML input tags. If you want to extract values from them, you can use jquery's attr function .

$(function(){
  var tokens = $('.stores').map(function(index, el) {
     var element = $(el)
     return {
       id: element.attr('id'),
       name: element.attr('value')
     }
  })
  $("#tokens").tokenInput(tokens);
});

I'm not sure what you are trying to do with the hashes once you have them, but that should get you started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM