0

I have several links. When I click a link I want jQuery to give focus to the corresponding input.

Links:

<a href="#" class="copy_go_to_input_field" data-divid="inp_copy_input_item_evidece_38">Focus</a>
<a href="#" class="copy_go_to_input_field" data-divid="inp_copy_input_item_evidece_39">Focus</a>
<a href="#" class="copy_go_to_input_field" data-divid="inp_copy_input_item_evidece_34">Focus</a>

Input fields:

<input type="text" name="inp_copy_input_item_evidece_38" value="2020_71_206_1" size="25" />
<input type="text" name="inp_copy_input_item_evidece_39" value="2020_71_206_1" size="25" />
<input type="text" name="inp_copy_input_item_evidece_40" value="2020_71_206_1" size="25" />

jQuery (not working):

<script>
$(function() {
    $('.copy_go_to_input_field').click(function() {
        var field = $(this).data('divid');
                $('[name=""+ field + ""]').focus();

        return false;
        });
});
</script>
Europa
  • 974
  • 12
  • 40

2 Answers2

2

You really don't need JS for that. You can do this quite easily using <label>. Just assign an ID to your inputs, and use the for attribute as follows:

<label class="copy_go_to_input_field" for="inp_copy_input_item_evidece_38">Focus</label>
<label class="copy_go_to_input_field" for="inp_copy_input_item_evidece_39">Focus</label>
<label class="copy_go_to_input_field" for="inp_copy_input_item_evidece_40">Focus</label>

<input type="text" id="inp_copy_input_item_evidece_38" name="inp_copy_input_item_evidece_38" value="2020_71_206_1" size="25" />
<input type="text" id="inp_copy_input_item_evidece_39" name="inp_copy_input_item_evidece_39" value="2020_71_206_1" size="25" />
<input type="text" id="inp_copy_input_item_evidece_40" name="inp_copy_input_item_evidece_40" value="2020_71_206_1" size="25" />
BenM
  • 52,573
  • 26
  • 113
  • 168
  • Thanks, this also worked, however I want to do extra things inside my jquery function after giving focus. I will keep this in mind for future problems where I can use labels and inputs. – Europa Feb 17 '20 at 12:20
  • 2
    "*after giving focus*" - in which case, you should use `$("input").on("focus"...` as they can get focus other ways than clicking the *label* – freedomn-m Feb 17 '20 at 12:44
1

The first thing that pops up is that it seems you misused the quotes in the name selector.

<script>
$(function() {
    $('.copy_go_to_input_field').on('click', function() {
        var field = $(this).data('divid');
        $('[name="'+ field + '"]').focus();

        return false;
    });
});
</script>

Also, you should try to use .on('click', function(){}) instead of the .click(function(){}). You can see why here: Difference between .on('click') vs .click()

You can check the solution posted by @BenM which is much cleaner than mine. The one I posted provides a fix for your JS. But for the functionality you need it's much cleaner to use what @BenM did.

Cornel Raiu
  • 2,758
  • 3
  • 22
  • 31