使用jquery设置文本字段的值

时间:2012-10-22 06:19:29

标签: javascript jquery

我正在尝试创建一个包含员工月薪的简单html文件,并且必须计算每个薪水的应付税额! 我使用“添加”按钮添加更多员工文本字段,创建一个包含类似div的新div类! 在工资文本字段的onchange事件中,我无法设置相应员工的税额!

不幸的是我无法上传屏幕截图,所以我把所有代码都尽可能清楚地表达了我的问题!

这是添加员工区域的jquery代码:

$(document).ready(function(){

var counter = 2;

$("#add_emp").click(function () {


var newTextBoxDiv = $(document.createElement('div'))
     .attr("class", 'em_area' + counter);

newTextBoxDiv.after().html('<br><label>Employee '+counter+' </label> <input id=em_name name=em_name type=text required  /> <label>Position</label> <input id=em_post name=em_post type=text required  /> <label>Monthly Salary</label> <input id=em_sal name=em_sal size=10 type=text required  /> &nbsp &nbsp &nbsp <label>Salary Tax</label> <input id=em_taxds type=text size=10 required />  ' );

newTextBoxDiv.appendTo("#all_emps");


counter++;
 });

 $("#del_emp").click(function () {


counter--;

    $(".em_area" + counter).remove();

 });
 });

这是html代码:

<div id="all_emps">
    <div class="em_area">
        <label>Employee 1</label>
        <input type=text required  />
        <label>Position</label>
        <input type=text required  />
        <label>Monthly Salary</label>
        <input id=em_sal type=text required size=10 onchange="calculateTax(this.value);" />
        &nbsp &nbsp &nbsp 
        <label>Salary Tax</label>
        <input id=em_tax name=em_tax type=text required size=10 readonly />
        &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp
        <a href="#" id="add_emp"><img src="add.jpg" width="30" height="30"></img></a>
        &nbsp &nbsp &nbsp &nbsp &nbsp
        <a href="#" id="del_emp"><img src="minus.jpg" width="30" height="30"></a>
    </div>  
</div>

这是我遇到问题的税务计算代码:(??????)

function calculateTax(sal)
{
    int salary = parseInt(sal);
    if(salary < 5000)
    {
        document.getElementById("em_tax").value = '0' ;
    }
    else if(salary>5000 || salary=5000)
    {
        var due_tax ;
        due_tax= salary/100;
        due_tax=salary - due_tax;

        document.getElementById("????????").value = due_tax;
    }
}

1 个答案:

答案 0 :(得分:3)

我发现的第一件事是您的HTML中有重复的 ID 。确保页面上的ID 唯一。尝试给予班级名称而不是..

<input class=em_sal type=text required size=10 onchange="calculateTax(this.value);" />
 &nbsp &nbsp &nbsp 
<label>Salary Tax</label>
<input class=em_tax name=em_tax type=text required size=10 readonly />

在JQuery中编写更改事件

$('#all_emps').on('change' , '.em_sal', function() { // Fire the change event

    var salary = parseInt(this.value);
    var dueTax = 0;
    if(salary < 5000){  
        // Do Nothing
    }
    else if(salary >= 5000)
    {
        due_tax= salary/100;
        due_tax= salary - due_tax;
    }
    // This will get the corresponding tax input for the employee..
    $(this).closest('div').find('.em_tax').val(due_tax) ;
});

Check FIDDLE