javascript - How to join array values in jQuery but formatting them? -
i have following input in javascript: ["1213381233", "1213551233", "1213551255"]
, need join them , format them. take following example:
<div id="segment_form"> <button id="add_condition"> click me </button> </div>
var data_field = 'asset_locations_name'; var data_condition = 'in'; var data_values = ["1213381233", "1213551233", "1213551255"]; $("#segment_form").on('click', '#add_condition', function() { var li = ''; var has_parenthesis = false; if (data_condition == 'in' || data_condition == 'not in' || data_condition == 'between' || data_condition == 'not between') { has_parenthesis = true; } if (data_values instanceof array && data_values.length >= 1) { li += '<li data-field="' + data_field + '" data-condition="' + data_condition + '">'; li += data_field + ' ' + data_condition; if (has_parenthesis) { li += '( '; } $.each(data_values, function(index, value) { li += '<span title="click remove item list" data-id="' + value + '">' + value + '</span>'; }); if (has_parenthesis) { li += ' )'; } li += '</li>'; } $('body').append(li); });
the idea have following output:
asset_locations_name in (1213381233,1213551233,1213551255)
my code working getting:
asset_locations_name in( 121338123312135512331213551255 )
the trick here can't data_values.join()
because need value of each add data-id
property on span itself.
any other clean solution? welcome!
i forgot mention there fiddle here ready play with.
what this?
var data_field = 'asset_locations_name'; var data_condition = 'in'; var data_values = ["1213381233", "1213551233", "1213551255"]; $("#segment_form").on('click', '#add_condition', function() { var li = ''; var has_parenthesis = false; if (data_condition == 'in' || data_condition == 'not in' || data_condition == 'between' || data_condition == 'not between') { has_parenthesis = true; } if (data_values instanceof array && data_values.length >= 1) { li += '<li data-field="' + data_field + '" data-condition="' + data_condition + '">'; li += data_field + ' ' + data_condition; if (has_parenthesis) { li += '('; } $.each(data_values, function(index, value) { // note 'prefix' variable here var prefix = (index == 0) ? '' : ', '; li += '<span title="click remove item list" data-id="' + value + '">' + prefix + value + '</span>'; }); if (has_parenthesis) { li += ')'; } li += '</li>'; } console.log('data_field =>', data_field, 'data_condition => ', data_condition, 'data_values =>', data_values, 'li =>', li); $('body').append(li); });
i created new fiddle solution.
Comments
Post a Comment