开发者

Shortening Javascript code

For my project i've been working on. I have a piece of Javascript code that inserts text into an input element with it's label has been double clicked.

$(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 over and over again. I would like the text inserted to stay the same.

Here are labels and input ID's I would like to use:

Label / Input

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


$(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 IDs ending with 'label'.

2 - Since you follow the same convention for your ID attributes, find the correct element by extracting the first word from the clicked ID, and prepend a '#' to form an ID selector.


create a map of element-id/object combination and attach the function ptr to it.


This code takes the clicked label, and uses the for attribute to find the appropriate <input> field to populate.

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


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


Something like:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜