Passing cpf to a javascript function

-3

My field that loads 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 on the submit button I call function on the click:

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

My js function:

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

How can I parameter the cpf?

    
asked by anonymous 10.08.2018 / 23:34

2 answers

2

From what I see in your razor template, the field id is cpf . So you can get the field and its value from within the function, based on that id. It does not 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 role name must match the declaration and call! You used replaceCpf onclick and replaceCPF on the declaration. Notice that in the above code I have already set the name to give no problem.

    
11.08.2018 / 00:13
1

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

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

But within its function it will not receive the string but the INPUT object from cpf, so 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.

    
10.08.2018 / 23:56