I'm trying to validate a discount code field in Rails 7 using Jquery. If it returns valid I wanna set the border color to green and if invalid then red. But atm I'm just trying to console log.
Everything works like I want it when I enter the URL and try out different params. It returns {"valid":false / true} like I want to.
But, it's my first time using Jquery and I'm struggling to get my code inside the script working.
Currently I'm stuck with this error:
Uncaught SyntaxError: Unexpected token '.'
caused by
.then(response => response.json());
View:
<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').blur(function(){
let code = $('#validateCode').val()
fetch('/choose_plan/validate_discount_code?code=' + code);
.then(response => response.json());
.then(data => console.log(data));
});
</script>
Routes
get 'choose_plan/validate_discount_code', to: 'choose_plan#validate_discount_code'
Controller
class ChoosePlanController < ApplicationController
def validate_discount_code
discount_code = params[:code]&.upcase
@discount = Discount.find_by(code: discount_code)
apply_discount = @discount if @discount&.active?
render json: { valid: params[:code]&.upcase == apply_discount&.code }
end
end
Any ideas what might be the reason for this error? And any help completing the border color change is appreciated :)