0

I wrote some code a while ago with the jQuery method focus; it worked then and it still works now. But now I tried writing some virtually identical code with the same method, in the same app, and it didn't do anything. In fact, no newly-written usage of the method works. Even stranger, it doesn't seem to work on jsfiddle either:

https://jsfiddle.net/3jmmL7ya/1/

<div id="click">CLICK ME</div><br>
<input id="focus" name="focus"></input>

<script type="text/javascript">
  $("#click").click(function() {
    $(':input[name="focus"]').focus();
  });

  $("#click").click(function() {
    $("#focus").focus();
  });
</script>

It may be unrelated, but I think it's worth mentioning that I recently had a similar problem with the Rails method respond_to do |format|. It worked in the past, and my old code still works, but new code I write results in an "Unknown Format" error. More details here.

I'm using jQuery 1.10.0 and Rails 4.0.10.

I'm either doing something absurdly stupid, or something pretty bizarre is happening.

UPDATE

Okay I got it to work with

  $("#click").click(function() {
    $("#focus").focus();
  });

But when I type in $("#focus").focus(); in the js console, the input is selected, but nothing happens. Is this expected behavior?

Community
  • 1
  • 1
Joe Morano
  • 1,715
  • 10
  • 50
  • 114

1 Answers1

0

This is because you are using a id selector to connect the events.

Ids are by definition supposed to be unique. When you use an id jQuery will automatically select the first matching element it finds. To solve this just add a class on the elements and use that selector instead.

Albin
  • 2,912
  • 1
  • 21
  • 31