Note that there are some explanatory texts on larger screens.

plurals
  1. POremoveClass does't work with $(this).attr('class') but $(this).attr('id')
    primarykey
    data
    text
    <p>I have this problem as reducing the size of my jQuery code. Basic function is to validate a form, if empty <code>addClass('highlight')</code> or <code>removeClass('highlight')</code>. It works fine if I use <code>$(this).attr('id')</code>, but when I tried to make it neat and changed to <code>$(this).attr('class')</code>, <code>removeClass('highlight')</code> stop working. Only thing I noticed is there are three <code>.text</code> <code>class</code>, I can't work out the reason. Please help.</p> <p>Problem code: <a href="http://jsfiddle.net/designpromote/GRG2J/" rel="nofollow">http://jsfiddle.net/designpromote/GRG2J/</a> Working code ($(this).attr('id')): <a href="http://jsfiddle.net/designpromote/GRG2J/4/" rel="nofollow">http://jsfiddle.net/designpromote/GRG2J/4/</a> or /3/ (without switch)</p> <p>I use <code>switch{}</code> because I need to validate different type of input. </p> <p>The code is list as below:</p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script&gt; $(function() { $('#myform :input').blur(function() { switch($(this).attr('class')) { case 'text': if($(this).val() == "") { console.log($(this), $(this).val()); $(this).addClass('highlight');} else {console.log($(this), $(this).val()); $(this).removeClass('highlight');} break; default: break; }http://stackoverflow.com/editing-help }); }) &lt;/script&gt; &lt;style&gt; .highlight { border: 2px solid red; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="myform"&gt; &lt;input type='text' name='business' id='business' class='text'&gt;&lt;br&gt; &lt;input type='text' name='address' id='address' class='text'&gt;&lt;br&gt; &lt;input type='text' name='city', id='city' class='text'&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload