0

I have the following array in JavaScript

("error", "No name entered", "Invalid Email", "No Message")

The array can also be

("success", "Your message has been sent.")    

I would like to create a string that looks like this

<div class="error">
<ul>
    <li>No Name entered</li>
    <li>Invalid Email</li>
    <li>No Message</li>
</ul>
</div>

The first item in the array is used for the div class the rest will be list items,

i've tried using formData[0], formData[1], etc. but that just prints undefined if the array item doesn't exist.

6
  • 2
    What is the variable called housing the original array? Commented May 21, 2013 at 18:22
  • The array is called formData Commented May 21, 2013 at 18:24
  • 1
    You could dynamically create an unordered list , append the array elements while running it through a loop till the array length Commented May 21, 2013 at 18:24
  • Why don't use some templating engine like github.com/visionmedia/jade Commented May 21, 2013 at 18:27
  • @slobodan.blazeski I guess it is easier to use something like handlebars in this case. Commented May 21, 2013 at 18:30

5 Answers 5

2

I'd suggest:

var formData = ["error", "No name entered", "Invalid Email", "No Message"];

for (var i = 0, len = formData.length; i < len; i++) {
    if (i == 0) {
        var wrapper = $('<div />', { 'class' : formData[i] }).appendTo('body');
        $('<ul />').appendTo(wrapper);
    }
    else {
        $('<li />', { text : formData[i] }).appendTo('div.' + formData[0] + ' > ul');
    }
}

JS Fiddle demo.

As pointed out in the comments, though, it'd be easier to avoid re-querying the DOM each iteration, so this version maintains references to the various created-elements:

var formData = ["error", "No name entered", "Invalid Email", "No Message"];

for (var i = 0, len = formData.length; i < len; i++) {
    if (i == 0) {
        var wrapper = $('<div />', { 'class' : formData[i] }).appendTo('body'),
            ul = $('<ul />').appendTo(wrapper);
    }
    else {
        $('<li />', { text : formData[i] }).appendTo(ul);
    }
}

JS Fiddle demo.

References:

Sign up to request clarification or add additional context in comments.

3 Comments

Why aren't you storing references to the elements that you create (the ul) and appending the li elements to that, instead of querying the DOM every loop iteration?
@Ian: because, honestly, I thought about doing that when I wrote the original (posted that to provide a useful answer) and then got distracted by dinner. blush...
@DavidThomas Haha just trying to help :) Good answer, by the way!
1

You can do

var array = ["error", "No name entered", "Invalid Email", "No Message"];

function makeDiv(array) {
var newDiv = '<div class="' + array[0] + '"><ul>';

for (var i = 1; i < array.length; i++) {
        newDiv += '<li>' + array[i] + '</li>';
}

newDiv += '</ul></div>';

//append newDiv somewhere

}

3 Comments

Why would you loop through all items? Always take the first item and make it a div. Then loop from 1 to length. The if/else is unnecessary to include in the loop
@Ian -- Made the changes, makes much more sense...I was over thinking the first element with useless logic :\
@tymeJV No problem. It was perfectly valid before, I just thought it was a little unnecessary when it's always the first item you're checking for. If it were like every other item, it would obviously need to be included
1

This should do it for you:

$('div').addClass(formData[0]);
$('li').each(function(index, el){ $(el).html(formData[index] || '') });

According comments is better to use a for loop, http://jsperf.com/jquery-each-vs-for-loop/73:

var lis = $('li');
for( int i = 0; i < lis.size(); i ++ ){
  var li = lis.eq(i);
  li.html(formData[i] || '');
}

2 Comments

uhg... jQuery .each() is insanely slow!
what to use instead? a for loop?
0
var formData = ["error", "No name entered", "Invalid Email", "No Message"]
  , first = formData.shift()
  , elem = $('<div />').addClass(first)
  , ul = $('<ul />').appendTo(elem)

 $.each(formData, function( ind, item ) {
    $('<li />').text(item).appendTo(ul)
 })

 // now elem has your DOM element 

Comments

0

Would you post the variable names for your arrays? This may be due to a reference error / assignment error.

In the mean time, a simple for loop could do the trick, but you may also want to look into JavaScript templating. It can make things like this much more simple.

Here's a JS Fiddle that may help you: http://jsfiddle.net/HepFw/

var failureMessage = ["error", "No name entered", "Invalid Email", "No Message"],
    successMessage = ["success", "Your message has been sent."];


function getMarkup ( resultArray ) {
    var markup = "";

    for ( var i = 0, loopCount = resultArray.length; i < loopCount; i++) {
        if ( i === 0 ) {
            markup += '<div class="' + resultArray[i] + '"><ul>';
        }
        else {
            markup += '<li>' + resultArray[i] + '</li>';
        }    
    }

    return markup += '</ul></div>';   
}

document.getElementById('so-example-success').innerHTML = getMarkup( successMessage );
document.getElementById('so-example-failure').innerHTML = getMarkup( failureMessage );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.