Estoy usando el matraz para crear un sitio web y quiero obtener la fecha local del cliente cuando compra mi producto y agregarlo al formulario cuando se envía usando javascript.
<form id="form" onsubmit="return addTime()" method="post"> <script type="text/javascript"> // the datetime javascript. Triggers when the form is submitted. function addTime() { /*var form=document.getElementById('form'); var input = document.createElement('input'); input.setAttribute('local date', new Date()); form.appendChild(input); form.submit();*/ var oldhtml = document.getElementById("myform").html(); var newhtml = `<input type="text" name="local date" value=${new Date()}>`; document.getElementById("myform").html(oldhtml+newhtml); } </script>Intenté dos métodos. El primero toma la forma y le agrega un atributo. No estoy seguro de si debería usar form.submit() después de eso o no, pero tampoco funcionó. El segundo método toma el html del formulario y le agrega la entrada. Eso tampoco funcionó.
¿Qué estoy haciendo mal?
Editar: los métodos que utilicé se basan en esto, esto y esto
Agregar un elemento de input es correcto. Pero debe establecer su value , no local date . Ese debería ser el nombre de la entrada, no un atributo.
var input = document.createElement('input'); input.name = 'local date'; input.value = new Date().toString(); form.appendChild(input); No necesita llamar a form.submit() en su función. Eso se hará automáticamente a menos que la función devuelva false .
Incluiría el campo de texto de entrada en el código HTML para el formulario, como este:
<input type="hidden" name="local date" id="localdate" />En el código JavasScript, use algo similar a esto:
function enterdate(field_id) { var field = document.getElementById(field_id); var newdate = prompt("Enter a new name"); if (newdate != null) { field.disabled = false; field.value = newdate; return true; } else { return false; } } En el botón de envío del formulario, use onClick="return enterdate('localdate)" .
No agregue información a un formulario al enviarlo,
prefiero usar el atributo type="hidden"
<form id="my-form" method="post"> <input name="local-date" type="hidden" value="">JS
const myForm = document.getElementById("my-form") myForm.onsubmit = e => { myForm['local-date'].value = new Date().toLocaleString('en-US') }