0

I have done the dynamic generates textbox based on the number that user type. For example, user types 10 in the input box clicked add will generate 10 input box. I have a label to catch the number.

here is my question

  • how do I start from 1?
  • how do I rearrange the number when user remove one of the input boxes

here is my javascript

$(document).ready(function () {
$("#payment_term").change(function () {

    var count = $("#holder input").size();
    var requested = parseInt($("#payment_term").val(), 10);

    if (requested > count) {
        for (i = count; i < requested; i++) {                
            $("#payment_term_area").append('<div class="col-lg-12 product_wrapper">' +

                  '<div class="col-lg-12 form-group">' +
                  '<label>' + i + 'Payment</label>' +
                  '<input type="text" class="payment_term form-control" name="PaymentTerm[]"/>' +
                  '</div>' +

                  '<a href="#" class="remove_field btn btn-danger pull-right">cancel</a>' +

                  '</div>');
        }
        $("#payment_term_area").on("click", ".remove_field", function(e) {                  //user click on remove text
            e.preventDefault();
            $(this).parent('.product_wrapper').remove();              
            calculateTotal();
            x--;
        })
    }
});

});

here is my view

<input type="text" id="payment_term" />
<button onclick="function()">Add</button>
<div id="payment_term_area"></div>
nonstop328
  • 629
  • 1
  • 6
  • 17

2 Answers2

2

You were nearly there, however, by hardcoding the label's you were making updating them difficult for yourself. I have created a jsfiddle of my solution to your problems. I personally prefer to cache the values of my jQuery objects so that they arent hitting the DOM each time they are referenced, for the performance boost (hence why they are listed at the top). I also, find it nicer to bind the click event in JS rather than using the html attribute onclick, but this is just a preference.

JSFIDDLE

Javascript

// create cache of jQuery objects
var add_payment_terms_button = $('#add_payment_terms');
var payment_term_input = $('#payment_term');
var payment_term_area = $('#payment_term_area');
var default_payment_values = ['first value', 'second value', 'third value', 'forth value', 'fifth value'];
var default_other_value = 'default value';

// bind to generate button
add_payment_terms_button.on('click', generatePaymentTerms);

function generatePaymentTerms(){
    var requested = parseInt(payment_term_input.val(), 10);
    // start i at 1 so that our label text starts at 1
    for (i = 1; i <= requested; i++) {
        // use data-text to hold the appended text to the label index
        payment_term_area.append(
        '<div class="col-lg-12 product_wrapper">' +
            '<div class="col-lg-12 form-group">' +
                '<label data-text=" Payment"></label>' +
                '<input type="text" class="payment_term form-control" name="PaymentTerm[]"/>' +
            '</div>' +
            '<a href="#" class="remove_field btn btn-danger pull-right">cancel</a>' +
        '</div>');
    }
    // call the function to set the labels
    updateProductIndexes();
}

function updateProductIndexes(){
    // get all labels inside the payment_term_area
    var paymentLabels = payment_term_area.find('.product_wrapper label');
    for(var x = 0, len = paymentLabels.length; x < len; x++){
        // create jQuery object of labels
        var label = $(paymentLabels[x]);
        // set label text based upon found index + 1 and label data text
        label.text( getOrdinal(x + 1) + label.data('text'));

        // either set the next input's value to its corresponding default value (will override set values by the user)
        label.next('input.payment_term').val(default_payment_values[x] || default_other_value)

        // or optionally, if value is not equal to blank or a default value, do not override (will persist user values) 
        /* var nextInput = label.next('input.payment_term');
        var nextInputValue = nextInput.val();
        if(nextInputValue === '' || default_payment_values.indexOf(nextInputValue) >= 0 || nextInputValue === default_other_value){
            nextInput.val(default_payment_values[x] || default_other_value)
        } */
    }
}

// courtesy of https://gist.github.com/jlbruno/1535691
var getOrdinal = function(number) {
   var ordinals = ["th","st","nd","rd"],
       value = number % 100;
   return number + ( ordinals[(value-20) % 10] || ordinals[value] || ordinals[0] );
}

payment_term_area.on("click", ".remove_field", function(e) { //user click on remove text
    e.preventDefault();
    $(this).parent('.product_wrapper').remove();
    // after we remove an item, update the labels
    updateProductIndexes();
})

HTML

<input type="text" id="payment_term" />
<button id="add_payment_terms">Add</button>
<div id="payment_term_area"></div>
haxxxton
  • 6,422
  • 3
  • 27
  • 57
  • wow thx!, i have an idea about the payment term, how do i manage to set default as 1st payment , 2nd payment , 3rd payment , 4th payment and so on. how do i get this to done? – nonstop328 Nov 22 '16 at 07:00
  • @nonstop328, do you mean, how do you set the default input value for the payment terms? if someone were to remove the 3rd item, would you expect it to update the 4th and 5th to update to their new positions default values, or remain as the original 4th and 5th defaults? – haxxxton Nov 22 '16 at 07:28
  • ya if user remove 3rd will update 4th and 5th to become 3rd and 4th. would it possible to do so? – nonstop328 Nov 22 '16 at 10:15
  • this is what i have done so far [testing here](https://jsfiddle.net/fsk2ucxo/2/) what i have missed to get the value 1 , 2 and 3? – nonstop328 Nov 22 '16 at 10:44
  • @nonstop328, you had missed double equals (`==`) in a few places so were assigning numbers to x instead of comparing them. Updated fiddle contains ordinals (eg. `st`, `nd`, etc.) for you, and assignment of default values, with an optional override on remove set of code – haxxxton Nov 23 '16 at 00:30
0

First you have to give id for each label tag ex:<label id='i'> Then you can re-arrange the number by using document.getElementById('i') Refer the Change label text using Javascript

hope this will be much helpful

Community
  • 1
  • 1
user3875464
  • 121
  • 9