Javascript function does not work

Asked

Viewed 81 times

-1

I’m doing this job:

function toDate(data) {
  let partes = data.split('/');
  return new Date(partes[2], partes[1] - 1, partes[0]);
}
var atual_data1 = toDate($("#txtDataInicio").val());
$("#txtVencimentoC").val() = (atual_data1.format("dd/MM/yyyy HH:mm:ss"));
var tol = ($("#txtTolerancia").val());
atual_data1.setDate(atual_data1.getDate() + parseInt(tol));
$("#txtDataTolerancia").val(atual_data1.format("dd/MM/yyyy HH:mm:ss"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

But it returns me the following error:

Referenceerror: Invalid left-hand side in assignment

In this line:

$("#txtVencimentoC").val() = (atual_data1.format("dd/MM/yyyy HH:mm:ss"));

I tried to do it too but it didn’t work:

$("#txtVencimentoC").val(atual_data1.format("dd/MM/yyyy HH:mm:ss"));
  • 1

    I believe that if you move: $("#txtVencimentoC").val() = (atual_data1.format("dd/MM/yyyy HH:mm:ss")); for $("#txtVencimentoC").val((atual_data1.format("dd/MM/yyyy HH:mm:ss"))); remember that val() is to set a value and not receive with the allocation operator (=)

  • your problem https://stackoverflow.com/a/9132972/2740371

  • Uncaught Typeerror: actual_data1.format is not a Function

1 answer

2


The val() jQuery is a method, so you need to treat it differently from a variable (which stores a value and you can change it with the syntax you used). To set the value from within an element with this method use:

$("#txtVencimentoC").val(atual_data1.format("dd/MM/yyyy HH:mm:ss"));

Another question is that there is no method format on objects Date in Javascript. To format the date the way you described it, use the native function toLocaleString():

$("#txtVencimentoC").val(atual_data1.toLocaleString());

If you need something more specific or other type of formatting, take a look at answers to this question.

See the fixes in your code:

function toDate(data) {
  let partes = data.split('/');
  return new Date(partes[2], partes[1] - 1, partes[0]);
}

var atual_data1 = toDate($("#txtDataInicio").val());

$("#txtVencimentoC").val(atual_data1.toLocaleString());

var tol = $("#txtTolerancia").val();

atual_data1.setDate(atual_data1.getDate() + parseInt(tol));

$("#txtDataTolerancia").val(atual_data1.toLocaleString());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Data Inicio: <input type="text" id="txtDataInicio" value="04/07/2013"><br>
VencimentoC: <input type="text" id="txtVencimentoC"><br>
Tolerancia: <input type="text" id="txtTolerancia" value="1"><br>
Data Tolerancia: <input type="text" id="txtDataTolerancia"><br>

  • I tried this way, returns me another error: Uncaught Typeerror: actual_data1.format is not a Function

  • I changed the answer!

  • 1

    It worked fine, thank you.

Browser other questions tagged

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