2015-01-07 3 views
1

Я пытаюсь получить forloop с входными элементами для запуска между формой и создать форму динамически с помощью JavaScriptзаселения динамической формы с JavaScript

1: в случае одной, форма в сценарии становится закрыта до элементы ввода заполняются.

2: в сценарии два, когда я помещаю переменную цикла for между формой, ошибка, которая приходит, не определена.

ПОМОГИТЕ

СЦЕНАРИЙ ONE

<form> 
No of Feilds <input type="text" id= "numberoffeilds"> 
<input type="button" value = "Create Feilds" onclick= "addfeilds1();"> 
</form> 

<div id= "div4" style= "color:gray"></div> 


<script> 

function addfeilds1() 
{ 
    var totalfeilds = document.getElementById("numberoffeilds").value; 
    var i; 

    document.getElementById("div4").innerHTML += '<form action= "issue.html" method = "POST">'; 

    for(i=0;i<totalfeilds;i++) 
    { 
     document.getElementById("div4").innerHTML += '<input type = "text">'; 
    } 

    document.getElementById("div4").innerHTML += '<input type = "submit" value="submit" name="submit">'; 

} 
</script> 

СЦЕНАРИЙ TWO

<form> 
No of Feilds <input type="text" id= "numberoffeilds"> 
<input type="button" value = "Create Feilds" onclick= "addfeilds2();"> 
</form> 

<div id= "div4" style= "color:gray"></div> 

<script> 
    function addfeilds2() 
    { 
     var totalfeilds = document.getElementById("numberoffeilds").value; 
     var i; 

     function forloop() 
     { 
      for(i=1 ;i<totalfeilds;i++) 
      { 
       document.getElementById("div4").innerHTML += '<input type = "text">'; 
      } 
     } 

     var loopvar = forloop(); 

     document.getElementById("div4").innerHTML += '<form action= "issue.html" method = "POST">'+ 
     '<input type = "text">'+ 
     loopvar + // it shows the loop as undefined 
    '<input type = "text">'+ 
    '<input type = "text">'+ 
    '<input type = "submit" value="submit" name="submit">'; 

    } 
</script> 
+0

новичок в использовании StackOverflow, Ват я хотел подразумевать это differenciate как сценарии 2 дифф .. может я редактировать. ? – Sebastian

+0

спасибо adeno, я исправился .. – Sebastian

+0

спасибо mouser ... :) – Sebastian

ответ

0

Вы должны строить HTML-элементы в строке первой и добавить их в DIV как последний шаг.

Fixed Сценарий 1:

function addfeilds1() 
{ 
    var totalfeilds = document.getElementById("numberoffeilds").value; 
    var i; 

    var htmlString = ""; 
    htmlString += '<form action= "issue.html" method = "POST">'; 

    for(i=0;i<totalfeilds;i++) 
    { 
     htmlString += '<input type = "text">'; 
    } 

    htmlString += '<input type = "submit" value="submit" name="submit">'; 
    document.getElementById("div4").innerHTML = htmlString; 
} 

Это предотвращает тэг формы от закрытия, прежде чем он заполнен входами.

Закрепление Сценарий 2:

function forloop() 
    { 
     var htmlString = ""; 
     for(i=1 ;i<totalfeilds;i++) 
     { 
      htmlString += '<input type = "text">'; 
     } 
     return htmlString; // now forloop returns a string that can be added to the element. It no longers returns undefined. 
    } 

На самом деле сценарий 2 чинил сценарий 1, но не включает в себя возвращение в вашей функции. Если вы ожидаете, что функция создаст какой-то текст и concat, то в строку вам понадобится ваша функция, чтобы вернуть строку.

Третий пример (продвинутый)

function addfeilds1() 
{ 
    var totalFields = parseInt(document.getElementById("numberoffeilds").value); //parse integer from value 
    if (isNaN(totalFields) || totalFields < 1) 
    { 
     //check if the input is valid, if not alert. 
     alert("Value is not a valid number or lower than 1."); 
    } 

    var container = document.getElementById("div4"); 
    //create the form  
    var form = document.createElement("form"); 
    form.setAttribute("action", "issue.html"); 
    form.setAttribute("method", "POST"); 

    for(var i=0; i<totalFields; ++i) 
    { 
     var node = document.createElement("input"); 
     node.setAttribute("name", "field[]"); //this sends a array to the request page containing all input field values. 
     form.appendChild(node); //add the fields to the form. 
    } 

    //create the submit button. 
    var button = document.createElement("input"); 
    button.setAttribute("type", "submit"); 
    button.setAttribute("value", "submit"); 
    button.setAttribute("name", "submit"); 
    form.appendChild(button); 

    container.appendChild(form); //append the form to the div. 
} 
+0

awesome dude, его работа сейчас .. kewlll ... спасибо, zillion bro .. это очень полезно .., еще раз спасибо .. – Sebastian

+0

@ Себастьян взглянет на решение 3, это очень чисто. – Mouser

+0

еще раз спасибо ... третье решение ... это то, что мне придется потратить некоторое время ... потому что его лил продвинулся для меня прямо сейчас (я новичок в программировании), но ваши ответы дали мне так много новых вещей, чтобы узнать о .... спасибо, что направили меня в правильном направлении :) – Sebastian

Смежные вопросы