Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot set property 'color' of undefined

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

like image 646
Carey Head Avatar asked Jan 31 '26 21:01

Carey Head


2 Answers

.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.

like image 101
mehulmpt Avatar answered Feb 03 '26 09:02

mehulmpt


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.

like image 30
cнŝdk Avatar answered Feb 03 '26 11:02

cнŝdk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!