简体   繁体   中英

jquery can we loop a function?

why cant this type of loop works? if this function not looped, it works perfectly. i need this code because i have dynamic appended div

$(document).ready(function(){
    for (var count = 1; count < 10; count++) {
            $('#keranjang').on('keyup', '#tinggikm'+count+', #lebarkm'+count, function(){
            <!-- Ambil nilai !-->
            var tinggi=parseInt($('#tinggikm'+count).val());
            var lebar=parseInt($('#lebarkm'+count).val());
            var harga=(tinggi * lebar) * 1000;

            $('#hargakm'+count).val(format1(harga, "Rp."));
            });
    }
});

this is my html from appended jquery

countkm = 1;
 countj = 1;
 countp = 1;
$("#somebutton").click(function () {
 var tipe = $( "#selecttipe option:selected" ).val();
  $("#keranjang").append(
                '<div class="col-md-4" style="border:1px solid #0d8b2a; border-radius:10px; width:31%; margin:10px">'+
                    '<p style="font-size:16px; letter-spacing:1px; font-weight:700; text-transform:uppercase; text-decoration:underline; margin-bottom:15px">'+
                    (tipe == "km" ? 'Kaca Mati ' : tipe == "j" ? 'Jendela ' : 'Pintu ')+(tipe == "km" ? countkm : tipe == "j" ? countj : countp)+
                    '</p>'+
                    '<div class="form-group">'+
                        '<label class="control-label">TINGGI (cm)</label>'+
                        '<input type="text" class="form-control" value="'+
                        (tipe == "Pintu" ? '200' : '100')+
                        '" id="tinggi'+tipe+(tipe == "km" ? countkm : tipe == "j" ? countj : countp)+'">'+
                        '<label class="control-label">LEBAR (cm)</label>'+
                        '<input type="text" class="form-control" value="'+
                        '100'+
                        '" id="lebar'+tipe+(tipe == "km" ? countkm : tipe == "j" ? countj : countp)+'">'+
                        '<label class="control-label">HARGA</label>'+
                        '<input type="text" class="form-control" disabled value="'+
                        '0'+
                        '" id="harga'+tipe+(tipe == "km" ? countkm : tipe == "j" ? countj : countp)+'">'+
                    '</div>'+
                '</div>'
                );
                if (tipe == "km"){countkm++;}else if(tipe =="j"){countj++;}else{countp++;};

});

and this is my button html to create the div

<select style="float:left; width:50%" class="form-control select2me" id="selecttipe" required>
                            <option value="km">Kaca Mati</option>
                            <option value="j">Jendela</option>
                            <option value="p">Pintu</option>
                        </select>
                        <button id="somebutton" style="float:left; margin-left:10px" type="submit" class="btn"> Tambah</button>

What about using id starts with selector instead of looping like this:-

$(document).ready(function() {
  $('#keranjang').on('keyup', '[id^=tinggikm], [id^=lebarkm]', function() {
    <!-- Ambil nilai !-->
    var tinggi = parseInt($('#tinggikm' + count).val());
    var lebar = parseInt($('#lebarkm' + count).val());
    var harga = (tinggi * lebar) * 1000;
    $('#hargakm' + count).val(format1(harga, "Rp."));
  });
});

It is not a good approach to loop for simply attaching an event. You can do it in a better and simpler way using data attributes. I am guessing that you need to attach a keyup event on dynamically generated input fields.

Here is what you can do;

  1. Assign a unique id to every element in you div on HTML creation time in your view eg id="tinggikm#{i}" which will render like id="tinggikm1" , id="tinggikm2" .
  2. Then add common class ie "my_keyup_input" to the input field on which you want to call keyup method. IMPORTANT! add a data attribute for the unique count like this data-count="#{i}" depending your language.
  3. Then finally in jQuery you can listen to the event using the class selector, something like this;

      $(document).ready(function(){ $('.my_keyup_input').on('keyup', function(){ // Lets get the count to uniquely identify our related div elements var count = $(this).data('count'); var tinggi=parseInt($('#tinggikm'+count).val()); var lebar=parseInt($('#lebarkm'+count).val()); var harga=(tinggi * lebar) * 1000; $('#hargakm'+count).val(format1(harga, "Rp.")); }); }); 

Based on the created html, an option is to capture all keyups and use the containing .form-group to find the respective inputs and values. This way no referencing to specific created id's is necessary. There are more effective ways by changing the way the html is created, but the below should work with the current functionality:

$('#keranjang').on('keyup', function(e){ //bind on keyup for entire container (no loop)
    var inp = $(e.target), //the input for which the keyup was captured
        grp=inp.closest('.form-group') //the group the input is in
      inputs = grp.find('.form-control'), //all inputs
        lbl = inputs.filter(':disabled'); //the disabled input is the total (if possible: using specific classes for the inputs and labels would be better)
  lbl.val(inputs.not(lbl).toArray().reduce(function(t,i){return t * parseInt(i.value);}, 1000)); //use reduce on the other inputs, to multiply them with each other (with a base of 1000)  
});

Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM