set maxlength in textarea - textarea

I want to set maxlength in textarea. I have defined maxlength property in textarea but it seems to be of no use. Pls help. My code:
<html:textarea styleClass="textarea" maxlength="2100" cols="60" rows="3">

Try this javascript function:
$(function(){
$("#id").keypress(function() {
var maxlen = 100; //length as you desire
if ($(this).val().length > maxlen) {
return false;
}
})
});

You have to write code for two events, keyup and copy paste so try this:
onKeyPress = "return ( this.value.length < 2100 );", onPaste = "return onTextAreaPaste(this,2100)"
Here is Js:
function onTextAreaPaste(textArea,size) {
var length = textArea.value.length;
if(window.clipboardData!=undefined)
length = textArea.value.length + window.clipboardData.getData('Text').length;
return length < size;
}

I recently came across a problem with textarea maxlength attribute because the newlines where considered as 1 in Firefox, and 2 in IE and Chrome. So I decide to go for JavaScript for handling this.
Here is how I handle the max length, its a jquery plugin, very easy to set and there's no problem with the different behaviors of browsers, plus give you a feedback of the characters used.

Related

Svelte: How to bind a formatted input field to a property

First of all: Svelte is still new to me. I hope the question is not too trivial.
Within a simple component I want to use the content of a formatted input field for a calculation.
For example:
In the input field a Euro amount should be displayed formatted (1.000).
Next to it a text with the amount plus VAT should be displayed (1.190).
How I do this without formatting is clear to me. The example looks like this:
export let net;
export let vat;
$: gross = net + (net * vat / 100);
$: grossPretty = gross.toLocaleString('de-DE',{ minimumFractionDigits: 0, maximumFractionDigits: 0 });
with a simple markup like this:
<form>
<label>Net amount</label>
<input type="text" step="any" bind:value={net} placeholder="Net amount">
</form>
<div>
Gros = {grossPretty} €
</div>
In vue i used a computed property. Its getter delivers the formatted string and its setter takes the formatted string and saves the raw value.
(In data() I define net, in the computed properties i define netInput. The input field uses netInput as v-model).
It looks like this:
netInput: {
get(){
return this.net.toLocaleString('de-DE',{ minimumFractionDigits: 0, maximumFractionDigits: 0 });
},
set(s){
s = s.replace(/[\D\s._-]+/g, "");
this.net = Number(s);
}
}
How can I handle it in svelte?
You can do something somewhat similar, you create another computed variable that stores the deformatted string from the input field and is used in the calculation instead of the direct input
export let net;
export let vat;
$: net_plain = Number(net.replace(/[\D\s._-]+/g, ""));
$: gross = net_plain + (net_plain * vat / 100);
$: grossPretty = gross.toLocaleString('de-DE',{ minimumFractionDigits: 0, maximumFractionDigits: 0 });
But maybe find a better name for the variable :)
Thanks to Stephane Vanraes I found a solution.
It has not the charm of the vue approach but it's ok. First I inserted 'net_plain'. To have the input field formatted during input, I added an event listener for the keyup event.
<input type="text" step="any" bind:value={net} on:keyup={handleKeyUp} placeholder="Net amount">
The event is handled from the function handleKeyUp as follows:
function handleKeyUp(event){
if ( window.getSelection().toString() !== '' ) {
return;
}
// ignore arrow keys
let arrows = [38,40,37,39];
if ( arrows.includes( event.keyCode)) {
return;
}
let input = event.target.value.replace(/[\D\s._-]+/g, "");
input = input ? parseInt( input, 10 ) : 0;
event.target.value = ( input === 0 ) ? "" : input.toLocaleString( "de-DE" );
}
BUT: If anyone has a solution using getter and setter I would appreciate the anwer!

using katex, '&' alignment symbol displays as 'amp;'

I am using katex to render math.
https://github.com/Khan/KaTeX
Generally, to get this to work I link to the files katex.min.js and katex.min.css from a cdn, which is one of the ways the directions suggest.
I wrap what needs to be rendered in tags and give all the same class. For example:
<span class='math'>\begin{bmatrix}a & b \\c & d\end{bmatrix}</span>
And inside a script tag I apply the following:
var math = document.getElementsByClassName('math');
for (var i = 0; i < math.length; i++) {
katex.render(math[i].innerHTML, math[i]);
}
So, my implementation works but there is a problem in what katex returns. The output of the above gives me:
This exact same question is asked here:
https://github.com/j13z/reveal.js-math-katex-plugin/issues/2
But I can't understand any of it.
The solution is to use element.textContent, not element.innerHTML.
If I use a form like what follows, the matrix will be rendered properly.
var math = document.getElementsByClassName('math');
for (var i = 0; i < math.length; i++) {
katex.render(math[i].textContent, math[i]); // <--element.textContent
}
A solution that works for me is the following (it is more of a hack rather than a fix):
<script type="text/javascript">
//first we define a function
function replaceAmp(str,replaceWhat,replaceTo){
replaceWhat = replaceWhat.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
var re = new RegExp(replaceWhat, 'g');
return str.replace(re,replaceTo);
}
//next we use this function to replace all occurences of 'amp;' with ""
var katexText = $(this).html();
var html = katex.renderToString(String.raw``+katexText+``, {
throwOnError: false
});
//hack to fix amp; error
var amp = '<span class="mord mathdefault">a</span><span class="mord mathdefault">m</span><span class="mord mathdefault">p</span><span class="mpunct">;</span>';
var html = replaceAmp(html, amp, "");
</script>
function convert(input) {
var input = input.replace(/amp;/g, '&'); //Find all 'amp;' and replace with '&'
input=input.replace(/&&/g, '&'); //Find all '&&' and replace with '&'. For leveling 10&x+ &3&y+&125&z = 34232
var html = katex.renderToString(input, {
throwOnError: false});
return html
}
Which version are you using?
Edit the src/utils.js and comment line number 51 to 55 after updated run in terminal npm run build command.

Input range slider not working on iOS Safari when clicking on track

I have a pretty straight-forward range input slider. It works pretty well on all browsers except on iOS Safari.
The main problem I have is when I click on the slider track, it doesn't move the slider. It merely highlights the slider. It works fine when dragging the thumb. Any ideas on how to fix this?
<div class="slider-wrap">
<div id="subtractBtn"></div>
<input type="range" class="slider">
<div id="addBtn"></div>
</div>
For those still looking for a javascript only fix like I did. I ended up just making a "polyfill" for this; it relies on the max attribute of the slider and determines the best step to force the input range on iOS. You can thank me later :)
var diagramSlider = document.querySelector(".diagram-bar");
function iosPolyfill(e) {
var val = (e.pageX - diagramSlider.getBoundingClientRect().left) /
(diagramSlider.getBoundingClientRect().right - diagramSlider.getBoundingClientRect().left),
max = diagramSlider.getAttribute("max"),
segment = 1 / (max - 1),
segmentArr = [];
max++;
for (var i = 0; i < max; i++) {
segmentArr.push(segment * i);
}
var segCopy = segmentArr.slice(),
ind = segmentArr.sort((a, b) => Math.abs(val - a) - Math.abs(val - b))[0];
diagramSlider.value = segCopy.indexOf(ind) + 1;
}
if (!!navigator.platform.match(/iPhone|iPod|iPad/)) {
diagramSlider.addEventListener("touchend", iosPolyfill, {passive: true});
}
<input type="range" max="6" min="1" value="1" name="diagram selector" class="diagram-bar" />
Add the CSS property, -webkit-tap-highlight-color: transparent to the CSS of the element or the complete html page. This will remove the troublesome highlight effect on an element when it is tapped on a mobile device.
Enhanced version of the solution presented by Cameron Gilbert. This implementation works for sliders with a min value set to a negative number and optional a step size set.
For those not working with typescript I leave it to you to convert to plain javascript.
if (!!navigator.platform.match(/iPhone|iPad|iPod/)) {
mySlider.addEventListener(
"touchend",
(touchEvent: TouchEvent) => {
var element = touchEvent.srcElement as HTMLInputElement;
if (element.min && element.max && touchEvent.changedTouches && touchEvent.changedTouches.length > 0) {
const max = Number(element.max);
const min = Number(element.min);
let step = 1;
if (element.step) {
step = Number(element.step);
}
//Calculate the complete range of the slider.
const range = max - min;
const boundingClientRect = element.getBoundingClientRect();
const touch = touchEvent.changedTouches[0];
//Calculate the slider value
const sliderValue = (touch.pageX - boundingClientRect.left) / (boundingClientRect.right - boundingClientRect.left) * range + min;
//Find the closest valid slider value in respect of the step size
for (let i = min; i < max; i += step) {
if (i >= sliderValue) {
const previousValue = i - step;
const previousDifference = sliderValue - previousValue;
const currentDifference = i - sliderValue;
if (previousDifference > currentDifference) {
//The sliderValue is closer to the previous value than the current value.
element.value = previousValue.toString();
} else {
element.value = i.toString();
}
//Trigger the change event.
element.dispatchEvent(new Event("change"));
break;
}
}
}
},
{
passive: true
}
);
}
Safari 5.1 + should support type "range" fully - so it's weird it's not working.
did you try adding min/max/step values ? what about trying to use only the pure HTML attribute without any classes that might interfere - try pasting this code and run it on a Safari browser
<input type="range" min="0" max="3.14" step="any">
it should be working - if it does, it's probably something related to your css, if not try using one of the pure HTML examples here:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/range
Try using jQuery Mobile? The workaround is obnoxious, and I'm pretty sure there's no way to use the native interface with standard HTML. It appears from other threads, you could do an elaborate CSS/JS solution.

Prevent CKEditor filtering Radiant Tags (non-valid HTML tags)

I'm using CKEditor with refinerycms (rails CMS) I've also added basic support for radius tags (they are the tags used in Radiant, another rails CMS) so I'm able to list some elements from the model in the page just inserting a code.
The problem is that the radius tags mimic html:
<r:product_listing category="products" list_as="grid"/>
When using CKEditor to modify the page contents it thinks the radius tags are invalid HTML, which is correct and the expected behaviour, but I can't find the way to tell CKEditor to just ignore those tags.
Any ideas?
Thanks in advance
EDIT: Turned out that the tag was being filtered by the sanitize method in rails being called by RefineryCMS.
What kind of issues do you have with custom tags? And on which browsers?
I checked that CKEditor preserves this tag, but wraps entire content with it. To avoid that you have to edit CKEDITOR.dtd, namely:
CKEDITOR.dtd.$empty[ 'r:product_listing' ] = 1;
But that still may not be enough. To have better support you'd need to make more changes in this object - especially important is to define what can be its parents and that it's an inline tag. For example:
CKEDITOR.dtd.p[ 'r:product_listing' ] = 1; // it is allowed in <p> tag
CKEDITOR.dtd.$inline[ 'r:product_listing' ] = 1;
This still may not be enough - for example you'll most likely won't have copy&paste support.
So, if you need more reliable support I'd try a little bit different way. Using CKEDITOR.dataProcessor you can transform this tag into some normal one when data are loaded into editor and when data are retrieved transform it back to that tag.
Example solution:
// We still need this, because this tag has to be parsed correctly.
CKEDITOR.dtd.p[ 'r:product_listing' ] = 1;
CKEDITOR.dtd.$inline[ 'r:product_listing' ] = 1;
CKEDITOR.dtd.$empty[ 'r:product_listing' ] = 1;
CKEDITOR.replace( 'editor1', {
on: {
instanceReady: function( evt ) {
var editor = evt.editor;
// Add filter for html->data transformation.
editor.dataProcessor.dataFilter.addRules( {
elements: {
'r:product_listing': function( element ) {
// Span isn't self closing element - change that.
element.isEmpty = false;
// Save original element name in data-saved-name attribute.
element.attributes[ 'data-saved-name' ] = element.name;
// Change name to span.
element.name = 'span';
// Push zero width space, because empty span would be removed.
element.children.push( new CKEDITOR.htmlParser.text( '\u200b' ) );
}
}
} );
// Add filter for data->html transformation.
editor.dataProcessor.htmlFilter.addRules( {
elements: {
span: function( element ) {
// Restore everything.
if ( element.attributes[ 'data-saved-name' ] ) {
element.isEmpty = true;
element.children = [];
element.name = element.attributes[ 'data-saved-name' ];
delete element.attributes[ 'data-saved-name' ]
}
}
}
} );
}
}
} );
Now r:product_listing element will be transformed into span with zero-width space inside. Inside editor there will be a normal span, but in source mode and in data got by editor#getData() method you'll see original r:product_listing tag.
I think that this solution should be the safest one. E.g. copy and pasting works.
u can also add as protected source, so no filtering or parsing will be done.
config.protectedSource.push(/<r:product_listing[\s\S]*?\/>/g);
just add these line to your config.js ([\s\S]*? is for any random content)
check out http://docs.ckeditor.com/#!/api/CKEDITOR.config-cfg-protectedSource

how to copy link name to title

i wanna ask how to change title in
name
so i want to make link name copy to title automatic
so if i make this code
title link
to
title link
how to do that in php or javascript
i know some in php
but need to make all words in link at database or make for every link variable $
can some one help me in that?
I'd suggest:
function textToTitle(elem, attr) {
if (!elem || !attr) {
// if function's called without an element/node,
// or without a string (an attribute such as 'title',
// 'data-customAttribute', etc...) then returns false and quits
return false;
}
else {
// if elem is a node use that node, otherwise assume it's a
// a string containing the id of an element, search for that element
// and use that
elem = elem.nodeType == 1 ? elem : document.getElementById(elem);
// gets the text of the element (innerText for IE)
var text = elem.textContent || elem.innerText;
// sets the attribute
elem.setAttribute(attr, text);
}
}
var link = document.getElementsByTagName('a');
for (var i = 0, len = link.length; i < len; i++) {
textToTitle(link[i], 'title');
}
JS Fiddle demo.
And since it seems traditional to offer a concise jQuery option:
$('a').attr('title', function() { return $(this).text(); });
JS Fiddle demo.
If you don't want to use a library:
var allLinks = document.getElementsByTagName('a');
for(var i = 0; i < allLinks.length; i++){
allLinks[i].title = allLinks[i].innerHTML;
}
Since you wanted to do all this to one element on the page, consider using something like this:
var allLinks = document.getElementById('myelement').getElementsByTagName('a'); // gets all the link elements out of #myelement
for ( int i = 0; i < allLinks.length; i++ ){
allLinks[i].title = allLinks[i].innerHTML;
}
Actually, this is roughly the same as before but we are changing the input elements.
Or, assuming you use jQuery, you could do something like this:
$('a').each(function(){ // runs through each link element on the page
$(this).attr('title', $(this).html()); // and changes the title to the text within itself ($(this).html())
});
In JQuery you can change an attribute by knowing the current tag and using the .attr() feature. Something like $('a').attr('title', 'new_title'); http://api.jquery.com/attr/

Resources