3

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

5 Answers 5

7
$(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.

Sign up to request clarification or add additional context in comments.

2 Comments

Just one more thing. Can you make it so it excludes input fields with dropdowns?
You mean if it is a <select>, do nothing?
0

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

Comments

0

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]');
    });
});

Comments

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

Comments

0

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.