First, let's make this a form. Forms are the standard way to encapsulate a collection of input boxes. They're well understood by normal browsers, but also by screen readers and what not.
<form>
<label>
Stream
<input name="url" type="url" />
</label>
</form>
This is similar to what you had, but I made a few changes:
<label>
elements need to either wrap what they're labeling, or the they need the for
attribute. Otherwise, they're not very useful.
- I dropped the
label
class. You can style this in CSS without it by simply using label
as the selector.
- I set a name for the
input
to make it easier to get its value later.
- The
input
is now of type url
. This has some built-in validation, and will fall back to a regular text
input if the browser doesn't support it.
Your audio
element is fine, but let's re-work it a bit:
<audio src=""></audio>
Basically, since we're only getting a single URL from the user, there's no need for child source
elements. We also shouldn't set the type
because we don't know what it's going to be.
Now, to directly answer your question... we handle the form submit with JavaScript.
// Ensure the page is loaded before querying for elements to attach handlers to
document.addEventListener('DOMContentLoaded', (e) => {
// Get the form, add a submit handler
document.querySelector('form').addEventListener('submit', (e) => {
// Get the form values from the form that was just submitted
const formData = new FormData(e.target);
// Set the audio `src` attribute from the form's `url` field input value
document.querySelector('audio').src = formData.get('url');
// Prevent default form handling (which would reload the page, in this case)
e.preventDefault();
});
});
Fiddle: https://jsfiddle.net/xnwr5jeq/7/