Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - Split String (For Each)

Current Code Below - I have to copy and paste each arr[0], arr[1], arr[2]. However, in the future I may have more or less array options and would like the code to auto update itself without needing to alter my code.

Basically, I want to create a "for-each" situation for each list item:

<li><i class='icon-check twentytwo color'></i><span>" + arr + "</span></li>

Current Code:

var data = $('.availability').text();
var arr = data.split('•');
$('.availability').html("<li><i class='icon-check twentytwo color'></i><span>" + arr[0] + "</span></li><li><i class='icon-check twentytwo color'></i><span>" + arr[1] + "</span></li><li><i class='icon-check twentytwo color'></i><span>" + arr[2] + "</span></li>");

ANSWER = All of these would have worked in various situations. I selected my answer based on the fact that I am using a handlebar template making some of these code snippets not usable for my project.

like image 904
Bryan Counts Avatar asked Sep 17 '15 08:09

Bryan Counts


1 Answers

You can loop your array by using the $.each function.

But instead of using html() which will override your HTML, you should append() the items.

var data = $('.availability').text();
var arr = data.split('•');
$.each( arr, function( index, value ) {
    $('.availability').append("<li><i class='icon-check twentytwo color'></i><span>" + value + "</span></li>");
});
like image 68
LinkinTED Avatar answered Sep 19 '22 10:09

LinkinTED