Javascript Code Reduction

For my project I was working on. I have a Javascript code snippet that inserts text into an input element with a double-click label.

$(document).ready(function() {
    $('#name-label').dblclick(function(){
        $("#name").val('[b][color="#FF0000"]Please Submit![/color][/b]');
    });
});

But I would like this code to work with multiple fields without copying and pasting the code again and again. I would like the text to stand the same way.

Here are the labels and input id that I would like to use:

Shortcut / Enter

name-label / name
image-label / image
quest-label / quest
price-label / price
ge-label / ge
halch-label / halch
lalch-label / lalch
details-label / details
examine-label / examine
location-label / location
stats-label / stats
keywords-label / keywords
+3
source share
5 answers
$(document).ready(function() {
    $('label[id$="label"]').dblclick(function(){
        $('#' + this.id.split('-')[0]).val('[b][color="#FF0000"]Please Submit![/color][/b]');
    });
});

1 - bind to all elements with identifiers completion with 'label'.

2 - , , "#", .

+7

element-id/object ptr.

0

for, <input> .

$(document).ready(function () {
    $("label").dblclick(function () {
        $("#" + $(this).attr("for")).val('[b][color="#FF0000"]Please Submit![/color][/b]');
    });
});
0

- :

function insertSubmitString(label_id, id) {
    $('#' + label_id).dblclick(function(){
        $('#' + id).val('[b][color="#FF0000"]Please Submit![/color][/b]');
    });
};

function insertAllSubmitStrings() {
  insertSubmitString('name-label', 'name');
  insertSubmitString('image-label', 'image');
  insertSubmitString('quest-label', 'quest');
  // and so on
};

$ (document) .ready (insertAllSubmitStrings ());
0
source
$(document).ready(function() {
    $('label').dblclick(function(){
        var inp = $(this).attr('id').split('-');
        $("#"+inp[0]).val('[b][color="#FF0000"]Please Submit![/color][/b]');
    });
});
0
source

Source: https://habr.com/ru/post/1791532/


All Articles