Javascript - Looping & Appending Consecutive Numeric Values

Hello - can somebody give me an example of how to condense this javascrit code please, I’m aware this is long-wided and can be shorted by looping thorugh values page_1, page_2, Page_3 etc but my unsure how to do it.

<script>
	/* Create a value to be used for URL slug */
     window.addEventListener('load', function() {
	var page_1 = document.getElementById("page_1");
    var slug_1 = document.getElementById("slug_1");
	var page_2 = document.getElementById("page_2");
    var slug_2 = document.getElementById("slug_2");
	var page_3 = document.getElementById("page_3");
    var slug_3 = document.getElementById("slug_3");
	var page_4 = document.getElementById("page_4");
    var slug_4 = document.getElementById("slug_4");
	var page_5 = document.getElementById("page_5");
    var slug_5 = document.getElementById("slug_5");
		page_1.oninput = function() {
			slug_1.value = page_1.value.toLowerCase().replace(/\+/g, " plus").replace(/[^a-z0-9-\s]/gi, "").replace(/\s+/g, "-").replace(/-+/g, "-").replace(/(^-+|-+$)/g, "");
		}
		page_2.oninput = function() {
			slug_2.value = page_2.value.toLowerCase().replace(/\+/g, " plus").replace(/[^a-z0-9-\s]/gi, "").replace(/\s+/g, "-").replace(/-+/g, "-").replace(/(^-+|-+$)/g, "");
		}
		page_3.oninput = function() {
			slug_3.value = page_3.value.toLowerCase().replace(/\+/g, " plus").replace(/[^a-z0-9-\s]/gi, "").replace(/\s+/g, "-").replace(/-+/g, "-").replace(/(^-+|-+$)/g, "");
		}
		page_4.oninput = function() {
			slug_4.value = page_4.value.toLowerCase().replace(/\+/g, " plus").replace(/[^a-z0-9-\s]/gi, "").replace(/\s+/g, "-").replace(/-+/g, "-").replace(/(^-+|-+$)/g, "");
		}
		page_5.oninput = function() {
			slug_5.value = page_5.value.toLowerCase().replace(/\+/g, " plus").replace(/[^a-z0-9-\s]/gi, "").replace(/\s+/g, "-").replace(/-+/g, "-").replace(/(^-+|-+$)/g, "");
		}

	});
    </script>

<form>
        name 1: <input type="text" id="page_1"> - slug 1: <input type="text" id="slug_1"><br><br>
        name 2: <input type="text" id="page_2"> - slug 2: <input type="text" id="slug_2"><br><br>
        name 3: <input type="text" id="page_3"> - slug 3: <input type="text" id="slug_3"><br><br>
        name 4: <input type="text" id="page_4"> - slug 4: <input type="text" id="slug_4"><br><br> 
        name 5: <input type="text" id="page_5"> - slug 5: <input type="text" id="slug_5">
    
    </form>

See https://jsfiddle.net/qxnpaysf/ :slight_smile:

2 Likes

thanks, works a treat … :ok_hand:

1 Like

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