jquery .change inside loop

Let say i have this code

HTML

<select id="id1">
    <option>a</option>
    <option>b</option>
    <option>c</option>
</select>
<select id="id2">
    <option>a</option>
    <option>b</option>
    <option>c</option>
</select>
<select id="id3">
    <option>a</option>
    <option>b</option>
    <option>c</option>
</select>
<div id="result1"></div>
<div id="result2"></div>
<div id="result3"></div>

Javascript

var i;
for (i = 1; i <= 3; i++) {
$('#id'+[i]).change(function(){
    $("#result"+[i]).html('<p>Number</p>'+[i]);                 
  });
}

JS Fiddle

Different <select> id and different result <div> id through loop

I just want, each <select> tag change, show the result through the div based on the id

Like this:

<select> id1 change to b, then div1 show b

<select> id2 change to c, then div2 show c

<select> id3 change to a, then div3 show a

In my example fiddle, the code i write is not working, can you please help me?

Thank you in advance

Upvotes: 1

Views: 3373

Answers (3)

cssyphus
cssyphus

Reputation: 40038

This should do what you want:

var i, j;
$('select').change(function(){    
    i = this.id.slice(2);
    j = this.value;
    $("#result"+i).html('<p>Number: '+j+'</p>');
});

jsFiddle Demo

References:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

Upvotes: 4

balajisoundar
balajisoundar

Reputation: 571

try this code.

var i;
for (i = 1; i <= 3; i++) {
$('#id'+i).change((function(a){
            return function()
            {                   
                $("#result"+a).html('<p>Number '+a+'</p>');
            };  
        })(i));   
}

and change your select elements id to id1,id2,id3

Upvotes: 2

Jenish Rabadiya
Jenish Rabadiya

Reputation: 6766

In this case I would suggest you should use data- attribute of html to pass the related div id to the change event and get that id and change its html.

Try something like following.

var i;
for (i = 1; i <= 3; i++) {

  $('#id' + [i]).change(function() {
    console.log($(this).attr("data-shouldupdate"));
    $("#" + $(this).attr("data-shouldupdate")).html('<p>Number</p>' + $(this).attr("data-shouldupdate"));

  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="id1" data-shouldupdate="result1">
  <option>a</option>
  <option>b</option>
  <option>c</option>
</select>
<select id="id2" data-shouldupdate="result2">
  <option>a</option>
  <option>b</option>
  <option>c</option>
</select>
<select id="id3" data-shouldupdate="result3">
  <option>a</option>
  <option>b</option>
  <option>c</option>
</select>
<div id="result1"></div>
<div id="result2"></div>
<div id="result3"></div>

Upvotes: 0

Related Questions