Input field limit 9 char and after 3 char automaticly ads "-" - javascript

<input id="myText" type="text" placeholder="XXX-XXX-XXX" /></input>
<script type="text/javascript">
document.getElementById("myText").value.substr(0, 9).match(/.{1,3}/g).join("-");
</script>

There are a few problems with your current JavaScript. First, your script will only run once when the page is loaded, meaning any input you enter into myText after that will never be processed. Consider binding to an event of myText - for example, the onkeyup event.
Another problem is that your JavaScript doesn't take into account existing dashes when splitting the value of myText into 3-character parts - this results in undesirable behaviour, where more and more dashes will be added to the value, at seemingly random positions.
Lastly, as mentioned by Tushar in the comments, you need to set the value of myText to the new, processed value you create. Otherwise this value ends up being unused and discarded, and your code appears to do nothing.
Putting this all together, the fixed code might look like:
var textInput = document.getElementById("myText");
textInput.onkeyup = function()
{
var dashlessInput = textInput.value.replace(/-/g, "");
textInput.value = dashlessInput.substr(0, 9).match(/.{1,3}/g).join("-");
};
<input id="myText" type="text" placeholder="XXX-XXX-XXX" /></input>
Hope this helps! Let me know if you have any questions.
For future reference - try to clearly state what your question by explaining what you want to achieve, and specifically indicating what problems you're facing. This way, you're more likely to attract good answers rather than downvotes.

Related

Using &letter; notation in JavaScript doesn't write greek letters

When I set an input box value with the "value" attribute in HTML to a greek letter, it shows the greek letter correctly. But when I change the "value" attribute with JavaScript, it uses the "&letter;" format. What can I do so that JavaScript behaves just as HTML?
HTML: <input type="text" id="input" value = "ε"> works fine.
JavaScript: document.getElementById("input").value = "ε"; shows ε but not the greek letter
The problem you're facing occurs because of the way you're setting the input. Javascript is (correctly) treating your ε as an ordinary string, because you haven't told it that it's anything else.
If this were an element like p, or span or any other contextual text element, you could simply do
myElem.innerHTML = "ε";
However, since you want to set this to be the input's value, you can't use innerHTML, because it wouldn't make any sense. What you need to do is something like this.
function htmlDecode(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
document.getElementById("myInput").value = htmlDecode("ε");
<input type="text" id="myInput" name="myInput" value="">
The function I used was originally posted in this SO answer. Be sure to read the rest of it, to see the other uses.

JavaScript is taking only the first word in a sentence

am stuck over a small issue here.
I want to set the value of a input using JavaScript but jQuery is not displaying the full sentence.
var name = "Richard Keep";
But when I use try to do this
$('input#nameid').val(name)
to this input
<input type="text" id="nameid">
the value is set to Richard alone instead of Richard Keep.
How do I make the jQuery echo the entire string and not just the first word in a string? Thanks
EDIT:
<td id="To_be_collected_port" onclick="requestPopup()" class="tr-selected">
<div class="pop-td To_be_collected_port">
</div>
this is the content am fetching
</td>
This will display this only.
var str = $('#To_be_collected_port').text();
then
$('.xyz').html("<input type=\"text\" name=\"text\" id=\"selected-service-text\" value="+str+">");
You're missing escaped double quotes around the value attribute:
value="+str+"
should be:
value=\""+str+"\"
Fiddle - works now
Explanation of why it was displaying "this"
This means your input tag is effectively composing to this:
<input type="text" ... value=this is the content am fetching>
value = "this"
is, the, content, am, fetching = attributes without any value
That is odd behaviour. Here are a few things you can try
1) add a console log just before putting the value in the field. if it does not properly show the entire name then you probably have some code manipulating the variable.
console.log(name);
$('input#nameid').val(name);
2) stupid suggestion but is your input field visually not to small? Maybe it added the entire name but you just don't see it.
3) use an onchange event on the field to check if something was changed after you updated the input field.

How to programmatically escape quotes? [duplicate]

This question already has answers here:
Escape quotes in JavaScript
(13 answers)
Closed 8 years ago.
this should be simple but I can't figure it out.
I want to let user edit a value. To do so, upon click, the value changes into a textbox. However, if the user puts a quote mark in the user input within the text box the value="" attribute of the text box closes prematurely and the quote mark and anything after it gets lost. Escape (deprecated) and encodeURI merely replace the quote mark with asci does which don't look good in the textbox.
Would appreciate anyone's solution to this problem:
Here is javascript:
function editText() {
var text = document.getElementById('text').innerHTML;
var edittext = '<input type="text" size=60 name="name" id="name" value="'+text+'"><input type="button" value="Save" onclick="storeText(\'name\');">';
document.getElementById('text').innerHTML = edittext
return false;
}
html:
Text: <span id="text" onclick="editText()";>He said "that's cool"</span>
jsfiddle
http://jsfiddle.net/2s9v2/6/
UPDATE:
Contrary to what those who marked this as a duplicate say, the duplicate question does not provide an answer to my question. They might want to re-read my question and the so-called duplicate and mentally register the word "programmatic" in my question and actually look at the code in the duplicate relaive to the code here.... Just saying.
I ended up changing the textbox to a textarea as a workaround as there does not seem to be a straightfoward way to programmatically escape a quote within a textbox.
The answer from Merlin below is a possible approach but calling the second function is more complex than just replacing textbox with textarea. In any case, I could not get that to work but I thank Merlin for his answer and upvoted it.
Try: text.replace(/"/g,""")
Ideally, though, you should be creating the elements with createElement, at which point you can do elem.value = text with no need for escaping.
Why not just set the value directly instead of rebuilding the input?
document.getElementById('name').value = edittext
Of course, this assumes that the input element with id=name already exists in your DOM, but I see no particular reason you could not ensure that it is already there (either writing directly in HTML or generating in Javascript on page load).
Update: It seems that the OP wants the element to be dynamically created in the onClick, by turning the text that is currently in a div into an input field with the contents of that div as its value.
I believe the following might do the trick, assuming id is unique as it should be.
function editText() {
var text = document.getElementById('text').innerHTML;
var edittext = '<input type="text" size=60 name="name" id="name" value="" /><input type="button" value="Save" onclick="storeText(\'name\');">';
document.getElementById('text').innerHTML = edittext;
document.getElementById('name').value = text;
document.getElementById('text').onclick = function() {}; //
return false;
}
Note that you will need to disable the onClick inside the above function as well, and then re-enable it inside storeText, because otherwise every click will cause extra buttons to be added.
Update 2: Here is a fully working example without parameter passing (for simplicity).
<html>
<body>
<script>
function editText() {
var text = document.getElementById('text').innerHTML;
var edittext = '<input type="text" size=60 name="name" id="name" value="" /><input type="button" value="Save" onclick="storeText();">';
document.getElementById('text').innerHTML = edittext;
document.getElementById('name').value = text;
document.getElementById('text').onclick = function() {};
return false;
}
function storeText() {
document.getElementById('text').innerHTML = document.getElementById('name').value;
document.getElementById('text').onclick = "editText();";
}
</script>
<div id="text" onclick="editText();">HelloWorld</div>
</body>
</html>

Getting <textarea> value with jQuery not working as expected

There are quire a few "jQuery getting element value" questions on here, but I was unable to find one that helped in my situation. Please read before marking as a duplicate, although I am more than happyto be pointed to another question which successfully answers my question.
I have the following <textarea>
<textarea id="comment_text" class="comment" onblur="if(this.value == '') { this.value = 'Comment...'; nocomLeft() }" onfocus="if(this.value == 'Comment...') { this.value = ''; comLeft() }">Comment...</textarea>
This adds placeholder text, removes it when it has focus, and adds it backs again if nothing is entered.
Now at various points, like when I click a button, I do:
var comment = $('#comment_text').text();
Which no matter what returns the value Comment... even if I have typed in the text area, clicked somewhere else to remove the focus, and can clearly see my new text still in the text area - $('#comment_text').text()' always comes backComment...`
I am stumped, all help appreciated.
Thanks
Use .val()
$('#comment_text').val();
Also, save some JS, and use the placeholder attribute.
.val() would be the proper method to call. So in your example, it would be
var comment = $('#comment_text').val();
Note that you can even set the text of the textarea by doing something like
var comment = $('#comment_text').val('this is a test');
Try using the .val() method
$('#comment_text').val();

How to identify if user is typing in RTL or LTR language?

I want imitate google's input,
It automatically change input's typing direction based on the language you're typing in.
How can I identify if user is typing in RTL or LTR language?
It must work cross-browser.
You should use the attribute dir="auto"
e.g.
<html dir="auto">
This way the browser will look at the first strongly typed character and adjust the text automatically.
For reference, here is the W3C documentation on this: http://www.w3.org/International/tutorials/new-bidi-xhtml/qa-html-dir
If you want to mimic Google's directionality recognition algorithm, you will need to listen to input change, recognize whether the character inserted was RTL or LTR (or neutral) and change the textbox's dir="" attribute accordingly.
Google's algorithm, for the most part, seems to calculate the majority of strong characters in the string and decide the directionality from that. If you type RTL it will switch the context to RTL, and if you then switch to LTR for the same paragraph, it may switch the context again to LTR if those characters outnumber the RTL ones.
For comparison, Facebook uses a direction algorithm as well, but it is slightly different - it seems to use the first strong character to decide the direction of the paragraph rather than the overall number.
(For the record, Google also seems to have several algorithms for this; Gmail behaves slightly differently than Google Hangouts which is different than how the input in Google search is aligning itself. In these things, there are mostly no "right" or "wrong" answers but rather what fits your use case)
Whichever method you choose to implement, you first need to identify what the user is typing. There are several ways to do this, but I would recommend the following:
Read a little about Unicode BiDirectional Algorithm (especially about "strong" type characters) http://unicode.org/reports/tr9/
Find a good way to identify strong characters in your context. An example of a regex to do that can be found in MediaWiki's Language file (where group 1 is LTR and group 2 is RTL): https://github.com/wikimedia/mediawiki/blob/6f19bac69546b8a5cc06f91a81e364bf905dee7f/languages/Language.php#L174
You can create a JavaScript method that listens to the user's input, uses the regex above to identify which strong character is used (either by first character or by counting them all, whichever works best for your use and scale) -- and change the textbox's dir="" attribute accordingly.
Make sure you later display the submitted text with the correct alignment later, so you may have to either use something to store the alignment you picked or to re-recognize whenever you render it. Either way, don't forget that the display needs the same dir="" attribute as well.
Too late but maybe it can help someone one day.
This function will add direction attribute to the input field based on the first inputed character, and when user clears input text the function will detect the new language of text again.
$.fn.set_input_direction = function()
{
$(this).off('keypress').on('keypress',function(e){
_this = $(this);
setTimeout(function()
{
if(_this.val().length > 1){
return;
} else {
var rtl_regex = /[\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC]/;
var is_rtl = rtl_regex.test(String.fromCharCode(e.which));
var direction = is_rtl ? 'rtl' : 'ltr';
_this.css({'direction' : direction});
}
});
});
};
To use it:
$('input').set_input_direction();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script>
function checkRTL(s) {
var ltrChars = 'A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02B8\u0300-\u0590\u0800-\u1FFF' + '\u2C00-\uFB1C\uFDFE-\uFE6F\uFEFD-\uFFFF',
rtlChars = '\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC',
rtlDirCheck = new RegExp('^[^' + ltrChars + ']*[' + rtlChars + ']');
return rtlDirCheck.test(s);
};
// BIND KEYPRESS
var input = $('input').on('keypress', keypress)[0];
function keypress(e) {
// need to wait for the character
setTimeout(function () {
var isRTL = checkRTL(String.fromCharCode(e.charCode)),
dir = isRTL ? 'RTL' : 'LTR';
input.style.direction = dir;
}, 0);
}
</script>
</head>
</body>
<h1>Auto Direction
<sup>(RTL | LTR)</sup>
</h1>
<input type="text" onkeypress="keypress()" placeholder="Type something…" />
</body>
</html>

Categories

Resources