endeka endeka - 4 years ago 75
HTML Question

JQuery - after() function with quotes

I need to add some HTML after a radio-button, I want to add an image and function so I check the radio button when I click on it. I would check the radio button with my own

selectRadioButton()
function.

The existing code is, I can't edit this part:

<span class="ms-RadioText">
<input id="idFirstRadioButton" type="radio" name="idFirstRadioButton" value="1" />
</span>


My idea, to add my image with function, was to do it like this:

$("#idFirstRadioButton").after("Image 1:<br/><a href=\"javascript:selectRadioButton(\"idFirstRadioButton\")\"><img src=\"http://urltoimage/image.jpg\" border=\"0\"/></a>");


But when I use this code, the HTML of my page is this:

<span class="ms-RadioText">
<input id="idFirstRadioButton" type="radio" name="idFirstRadioButton" value="1" /> Image 1:<br/><a href="javascript:selectRadioButton(" shape="" idFirstRadioButton?)?=""><IMG src="http://urltoimage/image.jpg" border=0></a>
</span>


He's adding "shape="" idFirstRadioButton?)?="""

The correct code should be:

<span class="ms-RadioText">
<input id="idFirstRadioButton" type="radio" name="idFirstRadioButton" value="1" /> Image 1:<br/><a href="javascript:selectRadioButton("idFirstRadioButton")><IMG src="http://urltoimage/image.jpg" border=0></a>
</span>


I already tried with
'
, with
\"
, combination of both, with a variable, ...

$("#idFirstRadioButton").after("Image 1:<br/><a href=\"javascript:selectRadioButton(\"idFirstRadioButton\")\"><img src=\"http://urltoimage/image.jpg\" border=\"0\"/></a>");
$("#idFirstRadioButton").after('Image 1:<br/><a href="javascript:selectRadioButton(\"idFirstRadioButton\")"><img src="http://urltoimage/image.jpg" border="0"/></a>');
$("#idFirstRadioButton").after('Image 1:<br/><a href="javascript:selectRadioButton("' + VARidFirstRadioButton + '")"><img src="http://urltoimage/image.jpg" border="0"/></a>');


What am I doing wrong or what is the code that I should use?

Answer Source

what you're doing wrong is using strings of HTML instead of constructing and appending Elements themselves, which (in addition to potential security concerns) can lead to the sort of confusing and annoying behavior you're seeing here. You want something like this:

var myImg = $("<img/>");
myImg.attr("src", "http://urltoimage/image.jpg");
myImg.on("click", function(e) {
  selectRadioButton("idFirstRadioButton");
});
$("#idFirstRadioButton").after(myImg);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download