Search code examples
javascriptdry

How to DRY javascript code to minimize redundancy


i'm new to Javascript when it comes to DRYing code. Can someone kindly help me DRY this javascript code

This is where the JS code gets it's data from:

<div class="form-group">
    @Html.LabelFor(model => model.eMP.EMPNO, "Employee Number", htmlAttributes: new { @class = "control-label" })
    @Html.EditorFor(model => model.eMP.EMPNO, new { htmlAttributes = new { @class = "form-control", @id = "EMPNO" } })
    @Html.ValidationMessageFor(model => model.eMP.EMPNO, "", new { @class = "text-danger" })
</div>

And this is where the value should go:

<div class="form-group">
    @Html.LabelFor(model => model.Emp_educ.EMPNO, "EMPNO", htmlAttributes: new { @class = "control-label" })
    @Html.EditorFor(model => model.Emp_educ.EMPNO, new { htmlAttributes = new { @class = "form-control", @id = "EMPNOEDUC", readOnly = "readonly" } })
    @Html.ValidationMessageFor(model => model.Emp_educ.EMPNO, "", new { @class = "text-danger" })
</div>

This is my code so far, i'm currently trying to minimize the redundancy of the code. is there are way to DRY this code?

$(document).ready(function () {
    $("#EMPNOEDUC").val($("#EMPNO").val());
    $("#EMPNOJOBHIST").val($("#EMPNO").val());
    $("#EMPNOREFERENCE").val($("#EMPNO").val());
    $("#EMPNOLICENSES").val($("#EMPNO").val());
});

Solution

  • Add a class to the inputs and then you can set the value $("#EMPNO").val() in one line

    $(document).ready(function () {
        $(".myinputs").val($("#EMPNO").val());
    });