Javascript - [removed].assign not working

2019-07-15 20:56发布

问题:

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>

回答1:

Looks like the form is submitting. Cancel it.

<form name="myform" onsubmit="return false">


回答2:

You want:

window.location = field1;


回答3:

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>