JavaScript function does not work

-1

I'm doing this function:

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>

Butitreturnsmethefollowingerror:

  

ReferenceError:Invalidleft-handsideinassignment

Inthisline:

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

I've tried to do this too but it did not work:

$("#txtVencimentoC").val(atual_data1.format("dd/MM/yyyy HH:mm:ss"));
    
asked by anonymous 03.07.2018 / 22:48

1 answer

2

val() of 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 of within an element using this method use:

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

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

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

If you need something more specific or other formatting, take a look at answers 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>DataInicio:<inputtype="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>
    
03.07.2018 / 23:00