Pass Cpf to a javascript function

Asked

Viewed 122 times

-3

My field that carries Cpf is this:

<div class="form-group">
    @Html.LabelFor(model => model.cpf, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.cpf, new { htmlAttributes = new { @class = "form-control", @id = "cpf" } })
        @Html.ValidationMessageFor(model => model.cpf, "", new { @class = "text-danger" })
    </div>
</div>

and the button submit I call the function in the click:

<input type="submit" value="Create" class="btn btn-default" onclick="replaceCpf();"/>

My function js:

function replaceCPF(cpf) {
    return cpf.replace(/^(\d{3})(\d{3})(\d{3})(\d{2})/, "$1.$2.$3-$4");
}

How can the Cpf parameter?

  • onclick="replaceCpf(document.getElementById("cpf").value);" ?

  • You don’t need the @id = "cpf", may delete. The model.cpf generates the id.

2 answers

2

From what I see in your Razor template, the field id is cpf. So you can take the field and its value from within the function, based on that id. It doesn’t make sense for this function to return value like you did. I would do something like this:

function replaceCpf() {
    var campo = document.getElementById('cpf');
    var cpf = campo.value;
    campo.value = cpf.replace(/^(\d{3})(\d{3})(\d{3})(\d{2})/, "$1.$2.$3-$4");
}

Another thing: the name of the function needs to match in the statement and in the call! You used replaceCpf in onclick and replaceCPF in the statement. Note that in the above code I have already adjusted the name to not give problem.

  • 1

    @Matheusmiranda Taking out the js syntax problems from the other answer, just a matter of style. I prefer to avoid mixing js with html. I just didn’t suggest addeventlistener in the answer to not cause noise.

1

You should pass the field id in replaceCpf(), something like

replaceCpf(document.getElementById('cpf'));

only that within its function it will not receive the string but rather the Cpf’s INPUT object, then something like:

function replaceCPF(inpuCpfField) {
    cpf = inputCpfField.text;
    cpf = cpf.replace(/^(\d{3})(\d{3})(\d{3})(\d{2})/, "$1.$2.$3-$4");
    inputCpfField.text(cpf);
}

PS: I’m not sure about the syntax of JS, but the logic is this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.