0

I am selecting a radio button from a set of radio buttons based on its value attribute. Everything is fine except if value attribute contains a single quotes. I am encoding it before binding the value so it cause no issue in html markup. But jquery is not working while trying to make the selection. The issue is only in IE7.

Radio button markup:

<input type='radio' name='radName' value='value1'>
<input type='radio' name='radName' value='value2'>
<input type='radio' name='radName' value='value3'>

Jquery to select the radio button:

myVal = funToGetSomeValue();
if ($('input[name=radName][value="' + myVal + '"]').length) {
  $('input[name=radName][value="' + myVal + '"]').prop('checked', true);
}

Encode special characters in code behind(C#) using HtmlEncode:

System.Web.HttpUtility.HtmlEncode(EmailStr);

Everything is good here except when myVal contains value with single quotes.

Any thoughts?

hermes101
  • 176
  • 1
  • 2
  • 8
  • And what's the role of c# in your question? – Daniel Aug 25 '15 at 14:55
  • Anyway, did you use an *old enough* version of jquery, as the newer versions have issues with these older browsers. I would first figure out if you really need to support this brower? Perhaps you'll have to *encode* 'myVal' to really match? – Xabre Aug 25 '15 at 14:56
  • Try this $('input[name=radName][value=' + myVal + ']') – arterzatij Aug 25 '15 at 14:56
  • 1
    possible duplicate of [jQuery selector value escaping](http://stackoverflow.com/questions/739695/jquery-selector-value-escaping) – Daniel Aug 25 '15 at 15:02
  • 1
    How are you encoding the values when you put them in the radio buttons? I don't see any problem finding them: //fiddle.jshell.net/eo50kp48/show/ – Guffa Aug 25 '15 at 15:24
  • The issue is only in IE7 and that's bugging me. This is an ASP.NET application with C# in code behind. I use System.Web.HttpUtility.HtmlEncode(EmailStr) to encode the special characters and this is working fine. The issue is in JQuery. – hermes101 Aug 25 '15 at 17:03

1 Answers1

0

You need to escape any quotes inside your strings before inserting it into a jquery selector. For this purpose escape all single quotes with double backslashes:

myVal.replace(/\'/gi, "\\\\'")
Daniel
  • 3,541
  • 3
  • 33
  • 46