Danielle Rose Mabunga Danielle Rose Mabunga - 4 months ago 27
jQuery Question

Generate a random number for data-id in html

I want to generate a random data-id for every html that I need to save in the database, but I dont know how to properly implement it

var html='<div class="portlet portlet-sortable light bordered ui-widget-content ui-resizable" style="display: block;" data-id:Generator()>'


js

function Generator(){};

Generator.prototype.rand = Math.floor(Math.random() * 26) + Date.now();

Generator.prototype.getId = function() {
return this.rand++;


full html

idGen = new Generator();
var $randomId = idGen.getId();
var html='<div class="portlet portlet-sortable light bordered ui-widget-content ui-resizable" style="display: block;" data-id="' + $randomId + '">'
+'<div class="portlet-title ui-sortable-handle">'
+'<div class="caption font-green-sharp">'
+'<i class="icon-speech font-green-sharp"></i>'
+'<span class="caption-subject bold uppercase"> '+$widgetTitle+'</span>'
+'</div>'
+'<div class="actions">'
+'<a href="javascript:;" class="btn btn-circle btn-default btn-sm remove">'
+'<i class="fa fa-times"></i> Remove </a>'
+'<div class="btn-group">'
+'<a class="btn btn-circle btn-default " href="javascript:;" data-toggle="dropdown" aria-expanded="false">'
+'<i class="fa fa-wrench"></i> Settings'
+'<i class="fa fa-angle-down"></i></a>'
+'<ul class="dropdown-menu pull-right">'
+'<li>'
+'<a href="javascript:;"><i class="fa fa-pencil"></i> Edit </a></li>'
+'<li><a href="javascript:;"><i class="fa fa-trash-o"></i><span class="delete"> Delete </span></a></li>'
+'<li><a href="javascript:;"><i class="fa fa-ban"></i> Ban </a></li>'
+'<li class="divider"> </li>'
+'<li><a href="javascript:;"> Make admin </a></li>'
+'</ul>'
+'</div>'
+'<a class="btn btn-circle btn-icon-only btn-default fullscreen" href="javascript:;"></a>'
+'</div>'
+'</div>'
+'<div class="portlet-body">'
+'<div>'+$widgetContent+'</div>'
+'</div>'
+'</div>';
return html;


},

Answer

You either need to concatenate the value within the string parts:

var html='<div class="..." style="..."  data-id="' + Generator() +'">'

Or create jQuery object from the html string and do:

var $div = $(html).data('id', Generator());
$('#someOtherDiv').append($div)
Comments