gonfer
gonfer

Reputation: 33

Handle many IDs

I am making a character counter for all input fields in a form. This is my script, for when I focus on the input field, when I leave it, and when I finish pressing a key:

$(document).ready(function () {
    $("#in1").keyup(function () {
        $("#count1").text(50 - this.value.length);
    });
    $("#in1").focus(function () {
        $("#countainer1").show();
        $("#count1").text(50 - this.value.length);
    });
    $("#in1").blur(function () {
        $("#countainer1").hide();
    });
});

You can see it working here: http://jsfiddle.net/UQFD6/12/

The question is:

Do I have to generate the script for each ID?

I mean, the code will be the same, but applied to different IDs: #input1 shows #countainer1 and modifies #count1, then #input2 with #countainer2 and #count2, and so on.

I thought of using classes instead of ids, but when it shows the container, it will show every container of that class, instead of only the one for the field I'm writing in.

Upvotes: 0

Views: 79

Answers (3)

Jai
Jai

Reputation: 74738

You can try with classes instead:

$(document).ready(function () {
    $(".in").keyup(function () {
        $(this).siblings(".count").text(50 - this.value.length);
    }).focus(function () {
        $(".countainer").show();
        $(this).siblings(".count").text(50 - this.value.length);
    }).blur(function () {
        $(this).siblings(".countainer").hide();
    });
});

Upvotes: 0

Eric J.
Eric J.

Reputation: 150108

No, you can use a class instead of #in1, e.g. add the in class to elements you currently give the id in1, in2, etc.

$(".in").keyup(function () {

You can use an attribute e.g. data-id=1 on elements that you need to select that are associated with your current #in1, e.g.

var id = $(this).data('id');
$(".count[id='" + id + "']").text(...);

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382102

I'd suggest this :

$(document).ready(function () {
    $('input[id^=in]').each(function(){ // all inputs whose id starts with "in"
       var i = this.id.slice(2); // finds "32" from "in32"
        $(this).keyup(function () {
            $("#count"+i).text(50 - this.value.length);
        }).focus(function () { // let's chain
            $("#countainer"+i).show();
            $("#count"+i).text(50 - this.value.length);
        }).blur(function () {
            $("#countainer"+i).hide();
        });
    });
});

Upvotes: 0

Related Questions