1

I've looked at these posts: jQuery selector for inputs with square brackets in the name attribute Escape square brackets when assigning a class name to an element Square brackets meaning string wont work

But I still can't get jquery to properly handle a name with square brackets.

When I used jquery with a rails form_tag I had no problems because the name of the radio button was simply "option", without square brackets. When I switched to a rails form_for, rails included the object "resource" and thus the name of the radio button became "resource[option]". These square brackets caused jquery to stop working. As you'll note below, I tried using // to handle the brackets, but it still doesn't work.

This code with a form_tag worked:

$("input:radio[name='option']").click(function(){  
  if(this.value == 'no_<%= user.id %>' && this.checked){
    $("#fields_<%= user.id %>").hide();
  }
  if(this.value == 'yes_<%= user.id %>' && this.checked){
    $("#fields_<%= user.id %>").show();
  }
});

The code below with form_for(@resource) does not work:

$("input:radio[name='resource\\[option\\]']").click(function(){
  if(this.value == 'resource_option_no_<%= user.id %>' && this.checked){
    $("#fields_<%= user.id %>").hide();
  }
  if(this.value == 'resource_option_yes_<%= user.id %>' && this.checked){
    $("#fields_<%= user.id %>").show();
  }
});                   

Any help would be appreciated. Thanks

Community
  • 1
  • 1
rjnash1
  • 35
  • 6

2 Answers2

0

Either you delimit the search value or you escape meta-characters but not both. Thus use either:

$("input:radio[name='resource[option]']")....

Or:

$("input:radio[name=resource\\[option\\]]")....

console.log( 'Escaped', $("input:radio[name=resource\\[option\\]]").val() );

console.log( 'Delimited', $("input:radio[name='resource[option]']").val() );

$(':radio[name=resource\\[option\\]]').on('change', function() {
    console.log( 'Change event fired checkbox checked?', this.checked );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="resource[option]" value="3432"/>
PeterKA
  • 24,158
  • 5
  • 26
  • 48
  • Thanks for the clarification. It works nicely now. – rjnash1 Sep 02 '15 at 05:28
  • No problem. Remember that whereas you can select only one answer as the best answer, you may up-vote more than one answer as useful. Enjoy :-) – PeterKA Sep 02 '15 at 13:15
0

Since you are using Attribute value selector there is no need to escape []. Also I would recommend you to use change event and .toggle(boolean) function.

$("input:radio[name='resource[option]']").change(function(){
    $("#fields_<%= user.id %>").toggle(this.value == 'resource_option_yes_<%= user.id %>' && this.checked);
});
Satpal
  • 132,252
  • 13
  • 159
  • 168