简体   繁体   English

关于问题<form onsubmit “function() ”>

[英]Question about <form onsubmit “function() ”>

i have wrote a function to activate onsubmit"" in the form. 我已经写了一个函数来激活表单中的onsubmit“”。 In the function(JavaScript) i try to fill variables with input from the fieldset. 在功能(JavaScript)中,我尝试用字段集的输入填充变量。 On troubleshooting i immediately found out that all the input gets cleared before i can save them into the variables. 在进行故障排除时,我立即发现所有输入都已清除,然后才能将它们保存到变量中。 I know that this is not how forms are used but i do like how it points out the fields that still needs to be filled. 我知道这不是表单的使用方式,但我确实喜欢它指出仍然需要填写的字段的方式。 so is there a way or someone how figured out a way to outsmart the submit to do something(function) before the refresh? 所以有没有办法或某人如何找到一种方法来使提交在刷新之前执行某些操作(功能)? or is there absolutely no way? 还是绝对没有办法?

function objectfill() {
var vnaam = document.getElementById('Voornaam').value;
var anaam = document.getElementById('naam').value;
var mail = document.getElementById('email').value;
var tele = document.getElementById('mobiel').value;
var rknr = document.getElementById('rijksregister').value;
var actie = document.getElementById('workshop').value
var k = document.getElementsByName('Room');
var room
for (var i = 0; i < k.length; i++) {
    if (k[i].checked) {
        room = k[i].value;
    }
}

var personeel = new personeelgegevens(pnr, vnaam, anaam, mail, tele, rknr, 
actie, room);
console.log(personeel)

This was the function i used onsubmit="objectfill()" I wanted to fill the object but obviously not working. 这是我使用的函数onsubmit =“ objectfill()”,我想填充对象,但显然不起作用。

You just need to prevent that submit from happening so that your JavaScript can run, by calling event.preventDefault() . 您只需通过调用event.preventDefault()来阻止该提交发生,以便您的JavaScript可以运行。 Also, try using element.addEventListener() instead of inline event properties. 另外,尝试使用element.addEventListener()代替内联事件属性。

// Assuming a form that looks like
<form id="myform">

// Do

const form = document.getElementById('form')

form.addEventListener('submit', event => {
  // prevent the form from submitting
  event.preventDefault()

  // The rest of your form code here
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM