0

I am trying to create a html table rows on select change my idea to create row is based on the select changes the number of select option is selected that many number or rows i want to be created in a specific html table with a input text box but that is applicable on button click i have no idea how to create on select change

HTML:

<select id="Number_of_position"  onchange="getval(this);"></select> 
<table id="Positions_names"></table>

JS:

$(document).ready(function(){

    var select = document.getElementById("Number_of_position"); 
    for (var i = 100; i >= 1; i--) {
        var option = document.createElement('option');
        option.text = option.value = i; 
        select.add(option, 0);
    }

});

function getval(sel) {
    alert(sel.value);
}

$("#addRow").click(function () {
    $("#Positions_names").append("<tr><td><input type='text'></td></tr>");
});
1
  • I can't understand what you want to achieve: you want to create a number of row and that number is the number you select on the select node? Commented Sep 19, 2015 at 7:20

1 Answer 1

2

Make sure you remove onchange attribute and switch to the unobtrusive way of binding event handlers

<select id="Number_of_position"onchange="getval(this);"></select>

You're looking for jQuery's change(handler) event handler.

This will update the table with fresh content each time you change select value:

var select = $("#Number_of_position"), table = $("#Positions_names");

select.change(function () {
    var rows = '';
    for (var i = 0; i < $(this).val(); i++) {
        rows += "<tr><td><input type='text'></td></tr>";
    }
    table.html(rows);
});

JSFiddle demo

Sign up to request clarification or add additional context in comments.

2 Comments

ᴀʀᴛᴜʀ ғɪʟɪᴘɪᴀᴋ i have a quick question why my option are starting from 100 to 0ne they should start from 1 to 100
@Shaik , because your for loop is reversed. You have to use this: for (var i = 1; i <= 100; i++) instead of this: for (var i = 100; i >= 1; i--) JSFiddle demo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.