David T. Shin David T. Shin - 6 months ago 22
jQuery Question

How do you fill a text field based on dynamically generated links?

The gist of it is that I have a dynamically generated drop down based off an array in JQuery. I have a text field next to it that should output an answer based on what was selected in the array.

<ul>
<li>
Vendor Contacts
<ul class="vendor_list">
</ul>
</li>
<input id="vendor_contact" type="text" />
</ul>


This is the HTML that I set up and here's the Javascript:

var vendors = ['vendor1, vendor2, vendor3'];
var contact_info = ['email1','email2','email3']

var vList = $('ul.vendor_list');
$.each(vendors, function (i)
{
var li = $('<li/>')
.addClass('menu_item')
.attr('role', 'menuitem')
.appendTo(vList);
var aaa = $('<a/>')
.addClass('vendors')
.text(vendors[i])
.appendTo(li);
});


What I think is the next step is:

$("#vendor_list").on('click', '.vendors', function () {
$("vendor_contact")val($(contact_info[i]))


Needless to say, I mind's pretty warped around this one. I'm starting to get into jQuery and just want to see how I can fill the text box in.

Answer

First, you have missing quotation marks in your vendors array:

var vendors = ['vendor1', 'vendor2', 'vendor3'];

Next, you should use class selector, not id on your .vendor_list element:

$(".vendor_list").on('click', '.vendors', function () {
    // ...

Next, missing # sign, as you're selecting the element by its id:

$("#vendor_contact")val(//...

(by $("vendor_contact") you're trying to select a not existing tag <vendor_contact>)

Last thing, use something like data attribute to determine the actual selection:

$.each(vendors, function(i){
    var li = $('<li/>')
        .addClass('menu_item')
        .attr('role', 'menuitem')
        .appendTo(vList);
    var aaa = $('<a/>') 
        .addClass('vendors')
        .text(vendors[i])
        // add 'data-id' attr:
        .data('id', i)
        .appendTo(li);
});

final JS:

$(".vendor_list").on('click', '.vendors', function () {
    $("#vendor_contact").val(contact_info[$(this).data('id')]);
});

JSFiddle Demo