Uncaught TypeError Cannot set property 'oninput' of null

hi - how do I loop through one or more matches in the JS code example below without returning error 'Uncaught TypeError Cannot set property ‘oninput’ of null ’ I need the function to work on different pages, some pages have just one title and slug input, other pages have multiple title and slug inputs

		title 1:<input type="text" name="textfield" id="news_title_1"> slug 1: <input type="text" name="textfield2" id="news_slug_1"><br>
			title 2:<input type="text" name="textfield" id="news_title_2"> slug 2: <input type="text" name="textfield2" id="news_slug_2">
</form>
<script>
// Create URL Slug
	function slugify(value) {
	return value.toLowerCase()
		.replace(/\+/g, " plus")
		.replace(/(the |and |for |at )+/g, " ")
		.replace(/[^a-z0-9-\s]/gi, "")
		.replace(/\s+/g, "-")
		.replace(/-+/g, "-")
		.replace(/(^-+|-+$)/g, "");
}
document.addEventListener('DOMContentLoaded', function(){

for (let i = 1; i > 0; i++) { // at least one match
	const title = document.getElementById('news_title_' + i); // title_1, title_2, etc
	const slug = document.getElementById('news_slug_' + i); // slug_1, slug_2, etc
	title.oninput = function() {
		console.log(title.value);
		slug.value = slugify(title.value);
	}
}
});
	</script>

thanks in advance …

Before the oninput line, you can check if the title exists. If it doesn’t, you can break out of the for loop.

for (let i = 1; i > 0; i++) { // at least one match
    const title = document.getElementById('news_title_' + i); // title_1, title_2, etc
    const slug = document.getElementById('news_slug_' + i); // slug_1, slug_2, etc
    if (!title) {
        break;
    }
    title.oninput = function() {
        console.log(title.value);
        slug.value = slugify(title.value);
    }
}

A possibly better way to deal with that is to get all inputs with an id that starts with news_title_ by using the *= selector, and use forEach on those instead.

const newsTitles = document.querySelectorAll("[id*='news_title_']");
newsTitles.forEach(function (title) {
    title.oninput = function() {
        console.log(title.value);
        const slug = document.getElementById(title.id.replace("news_title", "news_slug"));
        slug.value = slugify(title.value);
    };
});

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.