1

I need to create input fields on the basis of which number was chosen from select menu, like this code:

<select id="inputs" style="width:60px;">
    <option>1</option>
    <option>2</option>
    <option>3</option>                      
    <option>4</option>
    <option>5</option>
    <option>6</option>
    <option>7</option>
    <option>8</option>
    <option>9</option>
    <option>10</option>
</select>

When we select 10, input fields will increase to 10 at the same time, When I select 2, it doesn't decrease from 10 to 2 :(

I think the best way might be to use replace() with a loop; unfotunately I couldn't get a solution.

$(document).ready(function() {
    var scntDiv = $('#add_words');
    var wordscount = 0;
    var i = $('.line').size() + 1;

    $('#inputs').change(function() {
        var inputFields = parseInt($('#inputs').val());
        for (var n = i; n < inputFields; ++ n){
            wordscount++;
            $('<div class="line">Word is ' + wordscount + '<input type="text" value="' + wordscount + '" /><a class="remScnt" href="#">Remove</a></div>').appendTo(scntDiv);
            i++;
        }  
        return false;
    });

    //    Remove button
    $('#add_words').on('click', '.remScnt', function() {
        if (i > 1) {
            $(this).parent().remove();
            i--;
        }
        return false;
    });
});

​ Could you help me please?

David Thomas
  • 249,100
  • 51
  • 377
  • 410
Mo.
  • 26,306
  • 36
  • 159
  • 225
  • 2
    "I used to try with appendto which doesn't work :(" If you just want to create a new input field then that ought to work. Please show us what you have tried and give us details of exactly why it didn't work, what errors and behaviour you see, etc. You could also just create ten input fields on the page and show / hide them as appropriate, although they will then get submitted with the form which you might not want. – Rup Mar 27 '12 at 14:14
  • @Rup I can show you my JQuery code. – Mo. Mar 27 '12 at 14:19
  • 1
    have you refer the question in http://stackoverflow.com/questions/8280426/how-would-i-dynamically-create-input-boxes-on-the-fly – prabu Mar 27 '12 at 14:26

5 Answers5

2

Try

$(function(){
    $('#inputs').change(function(){
        for(i=0; i < $("select option:selected").text; i++)
        {
            $('#divIdHere').append('<input blah blah />');
        }
    })
});

obviously change to suit :)

The Angry Saxon
  • 792
  • 2
  • 7
  • 24
  • increase number of fields working fine :). unfortunately decrease doesn't work :( – Mo. Mar 27 '12 at 14:22
2

I realise that you already accepted an answer for this question, but I wasn't content to just leave the question as-is. Also: I was a little bored. Make of that what you will...

So! Here's my (belated) answer.

The benefits of my approach, or the reasoning behind it, are:

  1. You can use the select to remove, and add, rows.
  2. When removing rows using the select to remove rows it first removes those lines with empty inputs, and then removes whatever number of filled in input-containing rows from the end.
  3. It allows you to use the .remScnt links as well.

Hopefully this is of some, even if only academic, use or interest to you:

function makeRow() {
    var div = document.createElement('div'),
        input = document.createElement('input'),
        a = document.createElement('a');
        t = document.createTextNode('remove');
    div.className = 'line';
    input.type = 'text';
    a.href = '#';
    a.className = 'remScnt';
    a.appendChild(t);
    div.appendChild(input);
    div.insertBefore(a, input.nextSibling);

    return div;
}


$('#inputs').change(

function() {
    var num = $(this).val(),
        cur = $('div.line input:text'),
        curL = cur.length;
    if (!curL) {
        for (var i = 1; i <= num; i++) {

            $(makeRow()).appendTo($('body'));
        }
    }
    else if (num < curL) {
        var filled = cur.filter(

        function() {
            return $(this).val().length
        }),
            empties = curL - filled.length,
            dA = curL - num;

        if (empties >= num) {
            cur.filter(

            function() {
                return !$(this).val().length;
            }).parent().slice(-num).remove();
        }
        else if (empties < num) {
            var remainder = num - empties;
            cur.filter(

            function() {
                return !$(this).val().length;
            }).parent().slice(-num).remove();
            $('div.line').slice(-remainder).remove();
        }
    }
    else {
        var diff = num - curL;
        for (var i = 0; i < diff; i++) {
            $(makeRow()).appendTo($('body'));
        }
    }
});
$('body').on('click', '.line a.remScnt', function() {
    console.log($(this));
    $(this).parent().remove();
});​

JS Fiddle demo.

Please note that I've made little, or (more precisely) no, attempt to ensure cross-browser usability with this. The native DOM methods used in the makeRow() function are used for (minor optimisations of increasing the) speed, using jQuery (with its cross-browser-abstractions might make things even more reliable. And is worth considering.

References:

  1. Native vanilla JavaScript:

  2. jQuery stuff:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
1

okay change it a little to allow for a new list to be created.

$(function(){
    $('#inputs').change(function(){
        $('#divIdHere').empty()
        for(i=0; i < $("select option:selected").text; i++)
        {
            $('#divIdHere').append('<input blah blah />');
        }
    })
});

that will basically empty out the contents of the div before adding them all back in again :)

The Angry Saxon
  • 792
  • 2
  • 7
  • 24
0

you need to make you DIV before use append just try this html

<select id="inputs" style="width:60px;">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>                      
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    <option value="9">9</option>
    <option value="10">10</option>
</select>
<div id="add_words"></div>

and Jquery with this importand line scntDiv.empty();

JQuery

$(document).ready(function() {
    var scntDiv = $('#add_words');
    var wordscount = 1;
    var i = $('.line').size() + 1;

    $('#inputs').change(function() {
        var inputFields = parseInt($('#inputs').val());
          scntDiv.empty()
          for (var i = 0; i < inputFields; i++){
            scntDiv.append($('<div class="line">Word is ' + wordscount + '<input type="text" value="' + wordscount + '" />'));
          }
    });
});

Mo.
  • 26,306
  • 36
  • 159
  • 225
0

You could only add new lines to make up the number of lines when the select's value increases and only remove the 'extra' lines when it decreases.

$( document ).ready(
    function() {
        var divs = $( 'div#add_words' );
        $( '#inputs' ).change(
            function(evt) {
                var n = $( this ).val();
                var lines = $( 'div.line' );
                var numlines = lines.size();
                if( n > numlines ) {
                    // We want more line. Add some.
                    while( n > numlines ) {
                        numlines += 1;
                        divs.append( '<div class="line">Line ' + numlines + '</div>' );
                    }
                }
                else {
                    // Remove everything after the n'th line.
                    lines.slice( n ).remove();
                }
            } )
        .change();
    } );
neniu
  • 419
  • 3
  • 8