How do I get jQuery to select elements with a . (period) in their ID?

JavascriptJqueryJquery Selectors

Javascript Problem Overview


Given the following classes and controller action method:

public School
{
  public Int32 ID { get; set; }
  publig String Name { get; set; }
  public Address Address { get; set; }
}

public class Address
{
  public string Street1 { get; set; }
  public string City { get; set; }
  public String ZipCode { get; set; }
  public String State { get; set; }
  public String Country { get; set; }
}

[Authorize(Roles = "SchoolEditor")]
[AcceptVerbs(HttpVerbs.Post)]
public SchoolResponse Edit(Int32 id, FormCollection form)
{
  School school = GetSchoolFromRepository(id);

  UpdateModel(school, form);

  return new SchoolResponse() { School = school };
}

And the following form:

<form method="post">
  School: <%= Html.TextBox("Name") %><br />
  Street: <%= Html.TextBox("Address.Street") %><br />
  City:  <%= Html.TextBox("Address.City") %><br />
  Zip Code: <%= Html.TextBox("Address.ZipCode") %><br />
  Sate: <select id="Address.State"></select><br />
  Country: <select id="Address.Country"></select><br />
</form>

I am able to update both the School instance and the Address member of the school. This is quite nice! Thank you ASP.NET MVC team!

However, how do I use jQuery to select the drop down list so that I can pre-fill it? I realize that I could do this server side but there will be other dynamic elements on the page that affect the list.

The following is what I have so far, and it does not work as the selectors don't seem to match the IDs:

$(function() {
  $.getJSON("/Location/GetCountryList", null, function(data) {
    $("#Address.Country").fillSelect(data);
  });
  $("#Address.Country").change(function() {
    $.getJSON("/Location/GetRegionsForCountry", { country: $(this).val() }, function(data) {
      $("#Address.State").fillSelect(data);
    });
  });
});

Javascript Solutions


Solution 1 - Javascript

From Google Groups: >Use two backslashes before each special character. > A backslash in a jQuery selector escapes the next character. But you need two of them because backslash is also the escape character for JavaScript strings. The first backslash escapes the second one, giving you one actual backslash in your string - which then escapes the next character for jQuery.

So, I guess you're looking at

$(function() {
  $.getJSON("/Location/GetCountryList", null, function(data) {
    $("#Address\\.Country").fillSelect(data);
  });
  $("#Address\\.Country").change(function() {
    $.getJSON("/Location/GetRegionsForCountry", { country: $(this).val() }, function(data) {
      $("#Address\\.State").fillSelect(data);
    });
  });
});

Also check out How do I select an element by an ID that has characters used in CSS notation? on the jQuery FAQ.

Solution 2 - Javascript

You can't use a jQuery id selector if the id contains spaces. Use an attribute selector:

$('[id=foo bar]').show();

If possible, specify element type as well:

$('div[id=foo bar]').show();

Solution 3 - Javascript

Escape it for Jquery:

function escapeSelector(s){
	return s.replace( /(:|\.|\[|\])/g, "\\$1" );
}

usage example:

e.find('option[value='+escapeSelector(val)+']')

more info here.

Solution 4 - Javascript

The Release Candidate of ASP.NET MVC that was just released fixed this issue, it now replaces the dots with underscores for the ID attribute.

<%= Html.TextBox("Person.FirstName") %>

Renders to

<input type="text" name="Person.FirstName" id="Person_FirstName" />

For more information view the release notes, starting on page 14.

Solution 5 - Javascript

This is documented in jQuery Selectors docs:

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

In short, prefix the . with \\ as follows:

$("#Address\\.Country")

Why doesn't . work in my ID?

The problem is that . has special significance, the string following is interpreted as a class selector. So $('#Address.Country') would match <div id="Address" class="Country">.

When escaped as \\., the dot will be treated as normal text with no special significance, matching the ID you desire <div id="Address.Country">.

This applies to all the characters !"#$%&'()*+,./:;<=>?@[\]^`{|}~ which would otherwise have special significance as a selector in jQuery. Just prepend \\ to treat them as normal text.

Why 2 \\?

As noted in bdukes answer, there is a reason we need 2 \ characters. \ will escape the following character in JavaScript. Se when JavaScript interprets the string "#Address\.Country", it will see the \, interpret it to mean take the following character litterally and remove it when the string is passed in as the argument to $(). That means jQuery will still see the string as "#Address.Country".

That's where the second \ comes in to play. The first one tells JavaScript to interpret the second as a literal (non-special) character. This means the second will be seen by jQuery and understand that the following . character is a literal character.

Phew! Maybe we can visualize that.

//    Javascript, the following \ is not special.
//         | 
//         |
//         v    
$("#Address\\.Country");
//          ^ 
//          |
//          |
//      jQuery, the following . is not special.

Solution 6 - Javascript

Using two Backslashes it´s ok, it´s work. But if you are using a dynamic name, I mean, a variable name, you will need to replace characters.

If you don´t wan´t to change your variables names you can do this:

var variable="namewith.andother";    
var jqueryObj = $(document.getElementById(variable));

and than you have your jquery object.

Solution 7 - Javascript

I solved the issue with the solution given by jquery docs

My function:

//funcion to replace special chars in ID of  HTML tag

function jq(myid){


//return "#" + myid.replace( /(:|\.|\[|\]|,)/g, "\\$1" );
return myid.replace( /(:|\.|\[|\]|,)/g, "\\$1" );


}

Note: i remove the "#" because in my code i concat the ID with another text

Font: Jquery Docs select element with especial chars

Solution 8 - Javascript

Just additional information: Check this ASP.NET MVC issue #2403.

Until the issue is fixed, I use my own extension methods like Html.TextBoxFixed, etc. that simply replaces dots with underscores in the id attribute (not in the name attribute), so that you use jquery like $("#Address_Street") but on the server, it's like Address.Street.

Sample code follows:

public static string TextBoxFixed(this HtmlHelper html, string name, string value)
{
    return html.TextBox(name, value, GetIdAttributeObject(name));
}

public static string TextBoxFixed(this HtmlHelper html, string name, string value, object htmlAttributes)
{
    return html.TextBox(name, value, GetIdAttributeObject(name, htmlAttributes));
}

private static IDictionary<string, object> GetIdAttributeObject(string name)
{
    Dictionary<string, object> list = new Dictionary<string, object>(1);
    list["id"] = name.Replace('.', '_');
    return list;
}

private static IDictionary<string, object> GetIdAttributeObject(string name, object baseObject)
{
    Dictionary<string, object> list = new Dictionary<string, object>();
    list.LoadFrom(baseObject);
    list["id"] = name.Replace('.', '_');
    return list;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDoug WilsonView Question on Stackoverflow
Solution 1 - JavascriptbdukesView Answer on Stackoverflow
Solution 2 - JavascriptElliot NelsonView Answer on Stackoverflow
Solution 3 - Javascriptuser669677View Answer on Stackoverflow
Solution 4 - JavascriptDale RaganView Answer on Stackoverflow
Solution 5 - JavascriptJon SurrellView Answer on Stackoverflow
Solution 6 - JavascriptDanielView Answer on Stackoverflow
Solution 7 - JavascriptGabriel MolinaView Answer on Stackoverflow
Solution 8 - JavascriptgiusView Answer on Stackoverflow