user6762872 user6762872 - 3 months ago 10
HTML Question

.push() command in javascript not working?

When I try to push a url into an array then window.open() all urls in the array, I get a null error. I believe this is because the url is not being properly placed in the array to start. What am I doing wrong? Thanks.

<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form>
Series Name:
<input type="text"
name="series1name"
id="seriesname"/>
<br/>
Series Link:
<input type="text"
name="series1link"
id="serieslink"/>
</form>
<div>
<button onclick="AddSeries()">Add A New Series </button>
</div>
<div>
<button onclick="OpenSeries()">Open Incomplete Series </button>
</div>
</body>
<script type="text/javascript">

var urlArray = [];

function AddSeries() {

var url = document.getElementById('serieslink');
urlArray.push(url);
}

function OpenSeries() {
for (url in urlArray) {
alert(url.constructor === Array);
window.open(url, '_blank');
}
}
</script>
</html>


I'm sorry if the error is obvious, I am somewhat new to coding and so I'm sure this code isn't perfect by any means.
Thank you in advance.

Thank you everyone, a combination of two responses got my code to work the way I wanted it to.

Answer

Get the value of the textbox, not the textbox

You need to add the value of the textbox, not the textbox itself

var url = document.getElementById('serieslink').value;

When you run document.getElementById(), the return value is an object with many properties and methods. You can read about Element objects here.

Use the proper for loop

Pointed out by @Juhana

The for in loop will give you the key of an associative array or object. If the array is non-associative (which all arrays are in JavaScript), the use the for of loop instead. You can read about it here

Put script tag in the Body

Pointed out by @Xufox

<script> tags should be inside of the <body> tag. And putting the script at the end of the body is recommended to decrease load time.

Comments