min_jeong min_jeong - 1 month ago 6
Javascript Question

javascript url check error


The script receives the url to go to that url.
However, 'http://' will be added unless a written note.
But 'http: //' There was a problem with validation.


<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
label {
width : 100px;
float : left;
background-color:#66ccff,
font-weight : bold;
}
</style>
<script>
window.onload=init;
function init() {
document.getElementById("myForm").onsubmit = goURL;
}
function goURL() {

var myurl = document.getElementById("url");
if(myurl.indexOf('http://')==0) {
myurl += "http://"+url;
}
window.open(myurl.value);
}
</script>
</head>
<body>
<form id = "myForm">
<label> Go to </label>
<input type="text" id="url" placeholder="http://add url....">
<input type="submit" value="go website">
</form>
</body>
</html>

Answer
var myurl = document.getElementById("url").value;
if (myurl.indexOf('http://') != 0) {
    myurl = "http://" + myurl;
}
window.open(myurl);

Notes:

  • added .value after getElementById("url")
  • == 0 changed to != 0
  • += has changed to =
  • url has changed to myurl
  • window.open(myurl.value) changed to window.open(myurl)