vishal vishal - 3 months ago 8
HTML Question

values are undefined in array type ids using jquery

I am changing src of an image after a colorbox is being closed. When ID of the

img
tag is like
tabImage
, it works fine but when I change the id to
tabImage[0]
it stop working.

Working code is as follow :

<div class="whBg"><a href="javascript:openIframe('offerImage');">Select Image</a></div>
<form:hidden path="offerImageName" />
<form:hidden path="offerImageRel" />
<form:hidden path="offerImageTitle" />
<form:errors path="offerImage" cssClass="errorInst" />
<img id="offerImages" src="" style="width: 642px; margin:0px 0 0 220px;" />
<input type="hidden" id="returnImageName" />
<input type="hidden" id="returnImageSrc" />
<input type="hidden" id="returnImageRel" />
<input type="hidden" id="returnImageTitle" />

<script>
function openIframe(tabName)
{
$.colorbox({
iframe:true,
href:"imageListFrame",
innerWidth:1000,
innerHeight:500,
onClosed: function() {
$("#"+tabName+"s").attr("src", $("#returnImageSrc").val());
$("#"+tabName+"Name").val($("#returnImageName").val());
$("#"+tabName+"Rel").val($("#returnImageRel").val());
$("#"+tabName+"Title").val($("#returnImageTitle").val());
}
});
}
</script>


When I change IDs of
input
and
img
it stop working.

<div class="whBg"><a href="javascript:openIframe('toursImage',0);">Select Image</a></div>
<input type="hidden" id="toursImageName[0]" />
<input type="hidden" id="toursImageRel[0]" />
<input type="hidden" id="toursImageTitle[0]" />
<img id="toursImages[0]" name="toursImages[0]" src="" style="width: 642px; margin:0px 0 0 220px;" />
<input type="hidden" id="returnImageName" />
<input type="hidden" id="returnImageSrc" />
<input type="hidden" id="returnImageRel" />
<input type="hidden" id="returnImageTitle" />

<script>
function openIframe(tabName,id)
{
$.colorbox({
iframe:true,
href:"imageListFrame",
innerWidth:1000,
innerHeight:500,
onClosed: function() {
$("#"+tabName+"s["+id+"]").attr("src", $("#returnImageSrc").val());
alert($("#"+tabName+"s["+id+"]").attr("src"));
$("#"+tabName+"Name["+id+"]").val($("#returnImageName").val());
$("#"+tabName+"Rel["+id+"]").val($("#returnImageRel").val());
$("#"+tabName+"Title["+id+"]").val($("#returnImageTitle").val());
}
});
}
</script>


I have double checked that
returnImageName
,
returnImageSrc
etc are getting right values. I tried to access value of
#toursImages[0]
using jquery but I am getting
undefined
in alert.

Answer

You have to escape the [] - Brackets with \\

$("#"+tabName+"Name\\["+id+"\\]")

From jQuery Docu: LINK

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\.

Comments