Last active
November 12, 2017 13:29
-
-
Save eugenserbanescu/c02badc8fc1c9ed9625f2536017f3613 to your computer and use it in GitHub Desktop.
Form for Cip
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<form> | |
<select name="app"> | |
<option value="app1">App 1</option> | |
<option value="amazingAppMuchWow">App 2</option> | |
</select> | |
<input name="serial" placeholder="Serial goes here" type="text" /> | |
<button type="submit">Gimme an url!</button> | |
<div class="pair"> | |
<input type="text" placeholder="key"/> | |
<input type="text" placeholder="value"/> | |
</div> | |
</form> | |
<button id="add">Add pair</button> | |
<p id="output"></p> | |
<script> | |
const form = document.querySelector('form'); | |
function makeUrl(app, serial, params) { | |
let url = `baseUrlReplaceWhenNeeded/${app}${serial || params ? '?' : ''}`; | |
if (serial) { | |
url += `serial=${serial}`; | |
} | |
if (params) { | |
url += `${serial ? '&' : ''}tracking=${encodeURIComponent( | |
JSON.stringify(params) | |
)}`; | |
} | |
return url; | |
} | |
document.querySelector('#add').addEventListener('click', function(e) { | |
const pair = document.createElement('div'); | |
pair.className = 'pair'; | |
pair.innerHTML = `<input type="text" placeholder="key"/> | |
<input type="text" placeholder="value"/>`; | |
form.appendChild(pair); | |
}); | |
form.addEventListener('submit', function(e) { | |
e.preventDefault(); | |
let data = {}; | |
const pairs = Array.from(e.target.elements); | |
for (let i = 3; i < pairs.length; i += 2) { | |
let key = pairs[i].value; | |
let value = pairs[i + 1].value; | |
if (key && value) { | |
data[key] = value; | |
} | |
} | |
const app = document.querySelector('select[name="app"]').value; | |
const serial = document.querySelector('input[name="serial"]').value; | |
let params; | |
if (Object.keys(data).length > 0) { | |
params = JSON.stringify(data); | |
} | |
const url = makeUrl(app, serial, params); | |
document.querySelector('#output').innerText = url; | |
}); | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment