Experiments to create forms with components. The idea is to use this with the Wordpress block editor.
Last active
April 6, 2023 09:52
-
-
Save osvik/728f0eba5310791167f29af2d16c8305 to your computer and use it in GitHub Desktop.
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Experiment with form elements as components in Alpine.js</title> | |
<style> | |
[x-cloak] { | |
display: none !important; | |
} | |
.error { | |
color: red | |
} | |
.formElementBlock input, | |
.formElementBlock button, | |
.formElementBlock label { | |
display: block; | |
margin: 5px; | |
} | |
</style> | |
<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"></script> | |
</head> | |
<body> | |
<form x-data="{ values: {}, | |
sent: false, | |
submit: function(){ | |
if (!this.sent){ | |
for (const a in this.values) { | |
console.log(a, this.values[a]); | |
if (a){ | |
this.sent = true; | |
} | |
} | |
} | |
} | |
}"> | |
<div class="formElementBlock" x-data="{ | |
_value: '', | |
set value(v) { | |
this._value = v; | |
if (this.isValid()){ | |
this.values.email = v; | |
} else { | |
delete(this.values.email); | |
} | |
}, | |
get value() { | |
return this._value; | |
}, | |
isValid(){ | |
if ( /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(this._value) ){ | |
return true; | |
} | |
return false; | |
} | |
}"> | |
<label for="email">Email:</label> | |
<input type="email" id="email" x-model="value" /> | |
<label x-show="_value.length > 2 && !isValid()" class="error">An email address please!</label> | |
<button type="button" x-on:click="submit()">Submit</button> | |
</div> | |
</form> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment