I'm trying to create a custom error message and styling based on validation (I know about plugins, but the time involved in coordinating the validation plugin with Materialize is too much for a single field).
HTML:
<div class="input-field inline center-align">
<input id="quantity" name="quantity" type="number" class="">
<label for="qty" data-error="wrong" data-success="right"
class="active">Qty</label>
<span id="qty-error">really?</span>
</div>
JS:
$('#quantity').change(function(){
var $Qty = $(this).val();
var $Label = $('#qty-error');
if ($Qty > 0 && $Qty <= $AvailTix){
$Label.html('seems reasonable');
$Label.style.color = '#8e8ef5';
$(this).addClass('valid');
} else if ($Qty < 1){
$Label.html('really?');
$Label.style.color ='#f96d63';
$(this).addClass('invalid');
}
});
What's confusing me is that the $Label.html piece is working. It changes the text. But I get this error in the console for the $Label.style.color line:
Uncaught TypeError: Cannot set property 'color' of undefined
.style is property of an element. With jQuery you've that element in array. More like [elem]. So, use:
$Label.css('color', '#f96d63');
or
$Label.get(0).style.color = '#8e8ef5';
But the first one is more jQueryish.
Your problem is that you are trying to access a DOM property styleon a jQuery object, that's why you got Cannot set property 'color' of undefined.
In your code $Label is a jQuery object and don't have a style property because .style is a DOM object property so you can't use it with a jQuery object.
You need to use .css() method instead:
$Label.css('color', '#8e8ef5');
For more details you can read jQuery object and DOM element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With