通过Javascript动态添加输入到表单

时间:2016-09-28 18:11:10

标签: javascript html css forms

我正在修复一个表格,其中有一系列区域有两个或三个重复输入,例如雇主姓名,职位,等等。我认为用onclick按钮动态添加它们会更容易,但我遇到两个主要问题:(1)当onclick事件创建一个新的输入行时,标签属性似乎放弃了它们的CSS和(2)当你单击标签应该提升的表单输入,但输入不再提高其各自的标签。

我的问题是(1)修改css以保持标签相对于其输入所需的内容和(2)为什么/如何在第一级输入中工作而不是第二级?另外,我该如何解决这个问题?

任何帮助都会很棒!

我在下面的代码笔中以一种小的方式重新创建了这个问题。如果你在输入内部点击,你就会明白我的意思"提升。"

CodePen示例:http://codepen.io/theodore_steiner/pen/WGOaAR

HTML:

 <p class="subtitleDirection">Please list your employment histroy in chronological order, beginning with your current position (Limit of Three)</p>

 <div class="clearFix"></div>

 <div id="employmentHistory">    

     <div class="input-group" id="employment-history-1">

         <input type="text" name="job_1" />
     <label class="schoolBoard">School Board</label>

     <input type="text" name="position_1" />
     <label class="position">Position</label>   

         <input type="text" name="years_1" />
     <label class="years">Years</label>

     <button type="button" id="add_job()" onclick="addJob()" value="+">+</button>
     </div>
</div><!--end of employmentHistory Div-->

CSS:

input
{
  background: none;
  border: 1px solid #21a1e1;
  margin: 15px;
    margin-top: 25px;
    margin-left: 15px;
    margin-bottom: 25px;
    display: inline-block;
  height: 30px;
  width: 320px;
    float: left;
}

.input-group label
{
  position: absolute;
  left: 17px;
  top: 42px;
  font-style: italic;
  font-size: 17.5px;
  color: #999;
  -webkit-transform: translateY(-50%);
  -moz-transform: translateY(-50%);
  -o-transform: translateY(-50%);
  transform: translateY(-50%);
  pointer-events: none;
  transition: all 0.2s ease;
}

.input-group input:focus+label,
.input-group input.has-value+label {
  top: 20px;
  font-size: 12px;
  color: #aaa;
}

input:focus,
input:active
{
  outline: none;
}

input[type="text"],
input[type="email"]
{
  border: none;
  border-bottom: 1px solid #b3c1cc;
}

.input-group
{
  position: relative;
}

#teaching-experience-years input
{
    margin-left: 70px;
}

#teaching-experience-years label
{
    left: 421px;
}

#employment-history-1 input
{
    width: 220px;
    float: left;
}

#employment-history-1 label.position
{
    left: 265px;
}

#employment-history-1 label.schoolBoard
{
    left: 15px;
}

#employment-history-1 label.years
{
    left: 514px;
}

JS:


var i = 1;

function addJob()
{
    if( i <= 3 )
    {
        i++;
        var div = document.createElement("div");
        div.innerHTML = '<div class="input-group" id="employment-history-1"><label class="schoolBoard">School Board</label><input type="text" name="job_'+i+'"><label class="position">Position</label><input type="text" name="position_'+i+'"><label class="years">Years</label><input type="text" name="years_'+i+'"><button type="button" id="add_job()" onclick="addJob()" value="+"></button></div>';

        document.getElementById("employmentHistory").appendChild(div);
    }
};

0 个答案:

没有答案