Wednesday, January 9

HTML textarea tag maxlength, copy & paste issues solved using javascript

Problem: To limit the number of characters entered in a textarea including copy paste issues.

HTML Textarea Limitations:

1) No maxlength property available like input tag.
2) Paste event only available in IE.

Cross browser solution: (Works on IE & Mozilla)

< textarea rows="10" cols="50"
onkeypress = "e = event || window.event; code = e.charCode || e.keyCode;
if((code == 8 || code == 46) || (code >= 37 && code <= 40))
return true; else return (this.value.length <= 100);"

onpaste =
"if((this.value.length +
window.clipboardData.getData('Text').length) > 100)
{ this.value +=
window.clipboardData.getData('Text').substr(0,
(100 - this.value.length));
alert('There is a limit of 100 characters in textarea.
Text beyond this limit has not been added.');
event.returnValue = false; }"

oninput = "if(this.value.length > 100){
this.value = this.value.substr(0,100);
alert('There is a limit of 100 characters in textarea.
Text beyond this limit has not been added.'); }">
< /textarea >

Wednesday, January 2

One practical drawback of RoR

< % form_remote_tag :url=>{ :controller=>"controller_name", :action=>"action1" },

:html=>{ :action=>"/controller_name/action1/", :style=>"margin:0px;" },

:condition=>"$(title').value.strip().length > 0",

:complete=>"if(request.responseText == '1') alert('title exists'); else alert('title doesn't exist');" do -% >



< %= text_field_tag "title", nil, {:size=>65} -% >

< %= image_submit_tag "ok.gif", {:onclick=>"if($('title').value.strip().length == 0) alert('Title cannot be blank');" -% >

< % end -% >



controller_name.rb



1. def action1

2. if Model.exists?(params[:title].strip)

3. render :text=>1 //drawback

render :text=>"1" //the right way

4. else

5. render :text=>0 //drawback

render :text=>"0" //the right way

6. end

7. end



Well the above code seems pretty much OK but using the above code, the AJAX request took 33000 milliseconds as recorded by Firebug to complete that too on my local machine server. At first I thought its the query that is causing the problem but to my surprise the query turned out to be pretty efficient. I tried all possible combinations changing rather optimising the query but AJAX request still took 33000 milliseconds to complete. Finally after getting frustated I thought of trying to change line #3 in above code to render :text=>"1" (watchout the double quotes). To my surprise this time the AJAX request took only 2078 milliseconds to complete. To me its certainly a drawback of RoR.