Can't seem to reference a dynamically added field
I have code that adds list items to an unordered list, and associated with each list item is a button the user can click to delete that item out of the list. This happens dynamically (ie. they select something from a modal screen that needs to be added back to this unordered list). Usually the value of the item is just an int. And in this case my code all works fine.
However if the value of the item is a string (because sometimes I need to deal with multiple ids represented as the one item) then the remove doesn't do anything.
So at run time it can generate html like this (as grabbed from firebug)
<ul id="AgencySpecialism-selected-items" class="multi-select multi-select-selector">
<li>
<label>Spec 1/Spec 2</label>
<input id="AgencySpecialism-3|1" type="hidden" value="3|1" name="AgencySp开发者_JAVA技巧ecialism-3|1">
<button title="Clear selection" style="width: 28px;" onclick="AgencySpecialism_clear('3|1');return false;"> X </button>
</li>
</ul>
My javascript clear function is:
function <%= ViewData["ControlId"] %>_clear(id) {
<% if (Model.MultiSelectMode) { %>
alert('#<%= Model.ControlId %>-' + id);
alert($('#<%= Model.ControlId %>-' + id).val());
$('#<%= Model.ControlId %>-' + id).closest('li').remove();
$('#<%= Model.ControlId %>_SelectedSpecialisms').val($('#<%= Model.ControlId %>_SelectedSpecialisms').val().replace(id + ",", ""));
<% } else { %>
First alert shows
#AgencySpecialism-3|1
Second alert shows
Undefined
So it looks like it's saying that control doesn't exist - but based on the html markup - it does... ?!
So my end result is I need this line to work like it's supposed to:
$('#<%= Model.ControlId %>-' + id).closest('li').remove();
If I was to pass in
AgencySpecialism_clear(4)
or
AgencySpecialism_clear('4')
then the clear works as expected. The only difference seems to be one is pipe delimited instead of a single value :(
Any ideas would be appreciated. I even tried copying and pasting the actual rendered id into the clear method.. but it still believes its val is undefined.
edit - sorry for the .net mvc stuff thrown in there - however the issue is related to the jquery part of it :)
William is right, you need to escape the pipe:
<div id="test|1">Test</div>
alert($('#test\\|1').html());
You will want to do:
'#<%= Model.ControlId %>-' + id.replace("|", "\\|")
http://jsfiddle.net/ryyzp/1/
The double backslash is because you need to have'\|' in the jQuery selector so you are actually escaping the 2nd blackslash with the first.
精彩评论