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

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!

Related

prevent word counting of multiple spaces between words in textarea (html / javascript)

I have a textarea id="task", which has a word counter id="count" connected. The counter is set to count spaces between words, so a word is only accounted for if one puts a space after it. However, if for whatever reason one finds themself in a frenzy of hitting the spacebar, each and every space is then counted as a word which thwarts the final count. Below is the code for you to see for yourselves.
What I am asking is as follows:
1) Is there a way to count only one space after each word and ignore multiple spaces?
2) Can I prevent multiple spaces in the textarea?
Since I am suspecting that the solution dwells within the realm of javascript, I kindly ask for your help as I am still a noob. I will be grateful for any suggestions, be it 1) or 2).
HTML:
<div class="options">
Task:
<textarea type="text" rows="10" cols="97" name="task" id="task" onkeypress="onTestChange01();"
autocorrect="off" spellcheck="false"></textarea>
<p>Word count: <textarea cols="10" name="count" id="count" readonly>0</textarea></p>
</div>
JAVASCRIPT:
// WORD COUNTER FUNCTION
var count = document.getElementById('count');
var input = document.getElementById('task');
input.addEventListener('keyup', function(e){
wordCounter(e.target.value);
});
function wordCounter(text) {
var text = input.value;
var wordCount = 0;
for (var i = 0; i <= text.length; i++) {
if (text.charAt(i) == ' ') {
wordCount++;
}
}
count.innerText = wordCount;
}
I tried fiddling with the JS function and its values.
Also, I found a function to change multiple spaces to one space, which did not work as expected and it disrupted the original function and the counting.
Finally, I tried preventing 'space' altogether in the textarea properties but all in vain.
Looking forward to your ideas. Thanks.
tk

Swift - Split text based on arabic combined characters

Dears,
I have arabic sentence like this stentence
أكل الولد التفاحة
how can i split the sentence based on UNCONNECTED characters to be like this :
أ-
كل
ا-
لو-
لد
ا-
لتفا-
حة
I put - to explain what i mean.
I just need to split the text into array based on that
How can i do that using swift code for ios ?
Update:
I dont care for the spaces.
"أكل" for example is one word and doesn't contain spaces.I want to split based on UNCONNECTED characters.
So "أكل" consist from two objects : "أ" and "كل"
الولد : three objects "ا" and "لو" and "لد"
Use the below code:
let a = "أكل الولد التفاحة".split(separator: " ")
You can replace spaces with "-" using replacing occurences function.
let text = "أكل الولد التفاحة".replacingOccurrences(of: " ", with: "-", options: NSString.CompareOptions.literal, range: nil) ?? ""
I don't know how accepted answer helps to fix the issue.
Apple already provided Natural Language Framework to handle such a things which more trustworthy
When you work with natural language text, it’s often useful to tokenize the text into individual words. Using NLTokenizer to enumerate words, rather than simply splitting components by whitespace, ensures correct behavior in multiple scripts and languages. For example, neither Chinese nor Japanese uses spaces to delimit words.
Here is example
let text = """
All human beings are born free and equal in dignity and rights.
They are endowed with reason and conscience and should act towards one another in a spirit of brotherhood.
"""
let tokenizer = NLTokenizer(unit: .word)
tokenizer.string = text
tokenizer.enumerateTokens(in: text.startIndex..<text.endIndex) { tokenRange, _ in
print(text[tokenRange])
return true
}
Here is link of Apple docs
Hope it is helpful
There is two box you can just click in first. Content automatically paste click convert. Output data automatically copied with spaces I used for this quran
<h1>Allah</h1>
<center>
<textarea id="field" onclick="paste(this)" style="font-size: xxx-large;min-width: 90%; min-height: 200px;"> </textarea>
<center>
</center>
</br>
<textarea id="field2" style="font-size: xxx-large;min-width: 95%; min-height: 200px;"> </textarea>
</center>
<center>
<br>
<button onclick="myFunction()" style="font-size: xx-large;min-width: 20%;">Convert</button>
</center>
<script >
function myFunction(){
var string = document.getElementById("field").value;
// Option 1
string.split('');
// Option 2
console.log(string);
// Option 3
Array.from(string);
// Option 4
var bb = Object.assign([], string);
console.log(bb);
cleanArray = bb.filter(function () { return true });
var filtered = bb.filter(function (el) {
return el != null; });
console.log(filtered);
var bb = bb.toString();
console.log(bb);
bb = bb.replace(",","");
var stringWithoutCommas = bb.replace(/,/g, ' ');
console.log(stringWithoutCommas);
document.execCommand(stringWithoutCommas)
document.getElementById("field2").value = stringWithoutCommas;
var copyTextarea = document.querySelector('#field2');
copyTextarea.focus();
copyTextarea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
};
/*
var copyTextareaBtn = document.querySelector('#newr');
copyTextareaBtn.addEventListener('click', function(event) {
var copyTextarea = document.querySelector('#field2');
copyTextarea.focus();
copyTextarea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
});
*/
async function paste(input) {
document.getElementById("field2").value = "";
const text = await navigator.clipboard.readText();
input.value = text;
}
</script>
Try this:
"أكل الولد التفاحة".map {String($0)}

How do I get the ASP.Net MVC Password HTML Helper to show characters as I type?

I'm using the Password HTML Helper in MVC5 to hide the social security number as it is entered.
#Html.Password("s", null, new { #maxlength = 9, autocomplete = "off" })
The problem I see with it is you just see dots as you type. Is there any way the helper behavior can be modified to show the characters you are typing in for a second or two then have them transformed to dots? That behavior would let the user confirm they are typing in the correct character. If the helper behavior cannot be modified is there another way to accomplish this?
I found this fiddle maybe you can use this as an option
http://jsfiddle.net/Ngtp7/
$(function(){
$(".showpassword").each(function(index,input) {
var $input = $(input);
$('<label class="showpasswordlabel"/>').append(
$("<input type='checkbox' class='showpasswordcheckbox' />").click(function() {
var change = $(this).is(":checked") ? "text" : "password";
var rep = $("<input type='" + change + "' />")
.attr("id", $input.attr("id"))
.attr("name", $input.attr("name"))
.attr('class', $input.attr('class'))
.val($input.val())
.insertBefore($input);
$input.remove();
$input = rep;
})
).append($("<span/>").text("Show password")).insertAfter($input);
});
});

set maxlength in 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.

Open Source Projects for i18n à la Facebook

Facebook has this unique and clever approach to localization of their site: translators (in their case users that help to translate the site voluntarily) can simply click on the not-yet-translated strings – which are marked with a green bottom border – in their natural context on the site. See http://www.facebook.com/translations/.
Now, if you ever had to deal with the translation of a website, you'll be well aware of how odd and funny some of these translations can be when using tools like poedit where the translator isn't fully aware of the spot the translated string will lated appear in on the website.
Example: Please translate "Home". In German, for instance, the start page of a website would be "Home" while the house you live in is "Heim". Now, you as the translator basically have to guess which context this term is likely to appear in on the website and translate accordingly. Chances are, you're new website on home furniture now translates as "Home-Einrichtung" which sounds ridiculous to any German.
So, my question boils down to:
Do you know any open source PHP projects that work on something like this? I'm basically looking for a framework that allows you to put your internationalized website in "translation mode" and make strings clickable and translatable e.g. through a Javascript modal.
I'm not so much looking for a full-fledged and ready-made solution, but would love to know about similar projects that I can contribute code to.
Thanks in advance!
If you want to roll your own with jquery & jquery browserLanguage, this might get you going.
Tag all translatable text's contain elements with class="i18n", and include jquery, jquery browserLanguage, and your i18n script.
1. the internationalization javascript
— this needs to accept translations via ajax from your server, like:
var i18n = {};
i18n.bank = new Array();
i18n.t = function ( text, tl=$.browserLanguage ) {
var r = false;
$.ajax({
url: "/i18n_t.php?type=request&from="+ escape(text) +"&tl="+ tl,
success: function(){ i18n.bank[text] = this; r = true; }
});
return r;
};
2. php i18n translation service
— now we need to serve up translations, and accept them
the database will look like a bunch of tables, one for each language.
// SCHEMA for each language:
CREATE TABLE `en`
(
`id` INT PRIMARY KEY AUTO INCREMENT NOT NULL,
`from` VARCHAR(500) NOT NULL,
`to` VARCHAR(500) NOT NULL
)
the php will need some connection and db manipulation.. for now this may do:
//Connect to the database
$connection = mysql_connect('host (usually localhost)', 'mysql_username' , 'mysql_password');
$selection = mysql_select_db('mysql_database', $connection);
function table_exists($tablename, $database = false) {
if(!$database) {
$res = mysql_query("SELECT DATABASE()");
$database = mysql_result($res, 0);
}
$res = mysql_query("SELECT COUNT(*) AS count FROM information_schema.tables WHERE table_schema = '$database' AND table_name = '$tablename'
");
return mysql_result($res, 0) == 1;
}
the code is simply:
<?php
// .. database stuff from above goes here ..
$type=$_GET["type"];
$from=$_GET["from"];
$to=$_GET["to"];
$tl=$_GET["tl"];
if (! table_exists($tl)) {
...
}
if ($type == "request") { // might want to set $tl="en" when ! table_exists($tl)
$find = mysql_query("SELECT to FROM `'$tl'` WHERE from='$from'");
$row = mysql_fetch_array($find);
echo $row['to'];
} elsif ($type == "suggest") {
$find = mysql_query("SELECT COUNT(*) AS count FROM `'$tl'` WHERE from='$from'");
if ( !(mysql_result($res, 0)) == 0 ) {
$ins = mysql_query("INSERT INTO `'$tl'` (from, to) VALUES ('$from','$to')");
}
}
?>
3. page translation mechanics
— finally we can tie them together in your webpages with some further jquery:
i18n.suggest = function (from) { // post user translation to our php
$.ajax({
url: "/i18n_t.php?type=suggest&from='+from+'&to="+ escape( $('#i18n_s').contents() ) +"&tl="+ $.browserLanguage,
success: function(){ $('#i18n_t_div').html('<em>Thanks!</em>').delay(334).fadeOut().remove(); }
});
};
$(document).ready(function() {
i18n.t("submit");
i18n.t("Thanks!");
$('.i18n').click( function(event) { //add an onClick event for all i18n spans
$('#i18n_t_div').remove;
$(this).parent().append(
'<div id="i18n_t_div"><form class="i18n_t_form">
<input type="text" id="i18n_s" name="suggestion" value="+$(this).contents()+" />
<input type="button" value="'+ i18n.bank[ "submit" ] +'" onclick="i18n.suggest( '+$(this).contents()+' )" />
</form></div>'
);
}).each(function(){
var c = $(this).contents(); //now load initial translations for browser language for all the internationalized content on the page
if ( i18n.t(c) ){
$(this).html(i18n.bank[c]);
}
});
});
Mind you I don't have a server to test this on... and I don't actually code php. :D It will take some debugging but the scaffolding should be correct.

Resources