March 18, 2012

Jquery keyup multiple inputs

Question by Claremont

I am trying to make it so when someone uses the input the text that corresponds to it will show.

<div class="content1" style="display: block;">Content 1</div>
<div class="content2" style="display: none;">Content 2</div>
<div class="content3" style="display: none;">Content 3</div>
<div class="content4" style="display: none;">Content 4</div>

<ul class="addReview">
        <li><p>Input 1</p><input type="text" name="input1" value="" id="input1" autocomplete="off" maxlength="2"  /></li>
        <li><p>Input 2</p><input type="text" name="input2" value="" id="input2" autocomplete="off" maxlength="2"  /></li>
        <li><p>Input 3</p><input type="text" name="input3" value="" id="input3" autocomplete="off" maxlength="2"  /></li>
        <li><p>Input 4</p><input type="text" name="input4" value="" id="input4" autocomplete="off" maxlength="2"  /></li>
    </ul>

Would I do a keyup function for each input or is there a way to make one keyup function?

Answer by nnnnnn

This should do it for your current markup:

$('.addReview input[type="text"]').keyup(function() {
   $('div[class^="content"]').hide();
   $('div.' + this.id.replace(/input/, "content")).show();
});​

Demo: http://jsfiddle.net/WD3CU/

But it would be neater if you gave the divs a common class and different ids. E.g., if all the divs had a class “content” and an id in the form “content1” then you could do this:

$('.addReview input[type="text"]').keyup(function() {
   $('div.content').hide();
   $('#' + this.id.replace(/input/, "content")).show();
});​

Which looks similar but is much more robust (the way I did it for your current html will likely break if you were to give the divs additional classes).

Demo incorporating my suggested markup changes: http://jsfiddle.net/WD3CU/1/

Also, in my opinion it would make more sense to use the .focus() event rather than .keyup(), so that the appropriate div is shown as soon as the user clicks or tabs into one of the inputs.

Answer by Starx

You have to bind to a common selector like this

$('.addReview input:text').keyup(function() { });

demo

Or a class selector like this

$('.addReview .mytextboxclass').keyup(function() { });

demo

Or an attribute selector like in nnnnnn’s answer

$('.addReview input[type="text"]').keyup(function() { });​

demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!