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>
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.
Answer:
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" />
Tags: input, jqueryjquery, text