Javascript - [removed].assign not working

2019-07-15 20:37发布

I've a project where I scan a QR code, and it will then automatically print out information based on which code was scanned.

I have the scanner, and a printer. Each QR code is to correspond to a URL. I can get the scanner to fill an input field, and I can get an alert to show the information that was scanned. However, whenever I try to assign the URL it simply appends the information to the current URL, instead of replacing it.

I need it to replace the current URL. Does anyone know why it is doing this, and how to fix it?

<html>
<head><title>QR Printing</title></head>

<body onload="document.myform.mytextfield.focus();">

<form name="myform">
    <input type="text" name="mytextfield" onchange="checkForm()">
</form>

<script type="text/javascript" language="JavaScript">

function checkForm() { 
    var field1 = document.forms['myform'].elements['mytextfield'].value; 
    alert(field1);
    window.location.assign(field1);
}    

</script>

</body>
</html>

3条回答
闹够了就滚
2楼-- · 2019-07-15 21:00

You want:

window.location = field1;
查看更多
够拽才男人
3楼-- · 2019-07-15 21:16

add return false; after window.location.assign(field1);

 <html>
<head><title>QR Printing</title></head>

<body onload="document.myform.mytextfield.focus();">

<form name="myform">
    <input type="text" name="mytextfield" onchange="checkForm()">
</form>

<script type="text/javascript" language="JavaScript">

function checkForm() { 
    var field1 = document.forms['myform'].elements['mytextfield'].value; 
    alert(field1);
    window.location.assign(field1);
    return false;
}    

</script>

</body>
</html>
查看更多
等我变得足够好
4楼-- · 2019-07-15 21:20

Looks like the form is submitting. Cancel it.

<form name="myform" onsubmit="return false">
查看更多
登录 后发表回答