tags:

views:

46

answers:

3

I want to replace the hard coded string "Categories" with a variable. How can I do that? Instead of having Categories all the time, the word Categories may be replaced by the value held by a variable id, var id.

$(this).closest('ul').append('<li><input type="hidden" name="Categories.Index" value=' + newValue + ' /><input type="text" value=""  name="Categories[' + newValue + '].Name" style="width:280px"/><input type="hidden" value=""  name="Categories[' + newValue + '].ID" style="width:280px"/><input type="button"  value= "Add" /> </li>');
A: 

Just concat it the same way you already do with newValue:

name="' + id + '[' + newValue + '].ID"

Do the same for every occurence of Categories.

reko_t
+3  A: 
var id = 'Categories';
$(this).closest('ul').append('<li><input type="hidden" name="' + id + '.Index" value=' + newValue + ' /><input type="text" value=""  name="' + id + '[' + newValue + '].Name" style="width:280px"/><input type="hidden" value=""  name="' + id + '[' + newValue + '].ID" style="width:280px"/><input type="button"  value= "Add" /> </li>');
Pavel Morshenyuk
A: 

This finds every element with a name starting with "Categories" and replaces it with the variable id.

var id = "something";
var el = $("[name^=Categories]");
el.attr("name", id + el.attr("name").substr("Categories".length));

The result with your above example is an input with name="something.Index"

box9