I'm building out a feature to show if the discount code in a text field is valid. I just managed to build it out using Jquery, but now I wanna convert it into a StimulusJS controller. But I'm not really sure how to.
My current view with jquery:
<div class="mt-2 mx-1">
<label class="block text-sm font-medium text-gray-700">Discount Code</label>
<div class="mt-1">
<input type="text" name="discount_code" id="validateCode" class="appearance-none block w-
full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400
focus:outline-none focus:ring-teal-500 focus:border-teal-500 sm:text-sm">
</div>
</div>
<script>
$('#validateCode').on("keyup", function(){
let code = $('#validateCode').val()
fetch('/choose_plan/validate_discount_code?code=' + code)
.then(response => response.json())
.then(data => { if(data.valid)
{ $('#validateCode').css("background-color", "aliceblue") }
else
{ $('#validateCode').css("background-color", "white") }
});
});
</script>
My validate_discount_controller.js I've started on:
import { Controller } from "@hotwired/stimulus"
// Connects to data-controller="validate-discount"
export default class extends Controller {
connect() {
this.element.addEventListener('change', (e) => {
// execute a fetch request or something here
})
}
}