I would like to live format an input box with Numeral.js.
I tried something like this.
$('#exchangeInputFirst').keyup(function () {
//eur formatting
numeral.language('sk');
$('#exchangeInputFirst').val(numeral($('#exchangeInputFirst').val()).format('0,0.00$');
//to HUF format $('#exchangeInputSecond').val($('#exchangeInputFirst').val()*$('#first').html());
numeral.language('hu');
var string = numeral($('#exchangeInputSecond').val()).format('0,0.00$');
$('#exchangeInputSecond').val(string);
});
The second function is working perfectly (to HUF format), but the first not.
I think you are missing the numeral language file:
<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/1.5.3/languages.min.js"></script>
I cannot reproduce your situation unless I do not include the languages js file. Try your example and hit a key on the first input box:
var a = false;
$('#exchangeInputFirst, #exchangeInputSecond').click(function () {
$(this).caret(0);
});
$('#exchangeInputFirst, #exchangeInputSecond').keyup(function(){
if(a == false){
$(this).val('');
a = true
} else {
numeral.language($(this).data('language'));
$(this).val(numeral($(this).val()).format('0,0.00$'));
$(this).caret(0);
}
});
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/1.5.3/numeral.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/1.5.3/languages.min.js"></script>
<script src="http://zikro.gr/dbg/html/jquery.caret/dist/jquery.caret-1.5.2.min.js"></script>
<input type="text" data-language="sk" id="exchangeInputFirst">
<input type="text" data-language="hu" id="exchangeInputSecond">
UPDATE
You also have a problem with the cursor position. You can solve this by using this jQuery plugin acdvorak/jquery.caret to set the caret position to the beggining of the input each time characters are typed like this:
$(this).val(numeral($(this).val()).format('0,0.00$'));
$(this).caret(0);
Also, I have included the language in input's data like data-language="sk" and now you can read it directly in the keyup event like this:
numeral.language($(this).data('language'));
See my updated snippet. It should now works as you want.
Related
I have a few input fields that use onKeyUp="script" to return data the moment something is entered.
As a shortcut, I would like to be able to add a value to one of the fields when data is entered from another location AND trigger the script.
I can use document.getElementById("myID").value = MyValue; to add a specific value to the input box, or .addEventListener(); to watch another input field.
This part works well.
However, I have not been able to trigger anything equivalent to onKeyUp, which will happen either when:
1. You press/release a key while the input field is in focus.
2. You focus the input and release a key AFTER the script has added a value.
3. You enter the input field via [TAB] AFTER the script has added a value.
Adding .keyup(); or .keypress(); have had no effect.
I've been able to use .focus(); to focus and then change the input, but this does not have the same effect as pressing [TAB]
What can I do to trigger the onKeyUp for this field, even if the data was not manually typed?
ADDITIONAL INFO
This part works...
<input type="text" id="box1" onKeyUp="script1();">
<div id="result1" "> (script places result here) </div>
Add value from another location - Option 1
<input type="text" id="Test1">
<button type="button" onclick="TestScript()"> TEST</button>
<script type='text/javascript'>
function TestScript() {
var test1=document.getElementById("Test1").value;
document.getElementById("box1").value = test1;
document.getElementById("box1").keyup();
return false;
}
</script>
Add value from another location - Option 2
<script type='text/javascript'>
window.onload = function () {
document.getElementsByName("box2")[0].addEventListener('change', TestScript2);
function TestScript2(){
var test2=document.getElementById("box2").value;
document.getElementById("box1").value = test2;
}}
</script>
Both of these options will copy the value to the correct location, but I have not been able to get either to trigger the onKeyUp so that the original script realizes something has changed.
Non working Fiddle example: https://jsfiddle.net/mj8g4xa2/4/
Trigger keyup programatically in;
JAVASCRIPT:
Call onkeyup() on the element.
Create a new keyup event and dispatch it using the element. Note: The source here doesn't support IE. Refer this answer for cross-browser support. Also createEvent is deprecated (MDN Docs for reference).
JQUERY:
$("#elem").keyup();
$("#elem").trigger('keyup');
Change events fire only when the input blurs, according to the MDN Docs.
Also, you should have got Uncaught TypeError: element.keyup is not a function error in your console.
var elem = document.getElementById("data");
function triggerKeyUpEvent()
{
var e = document.createEvent('HTMLEvents');
e.initEvent("keyup",false,true);
elem.dispatchEvent(e);
}
function perform()
{
console.log("KeyUp");
}
function add()
{
elem.value = String.fromCharCode(Math.random().toFixed(2)*100).repeat(5);
elem.onkeyup();
triggerKeyUpEvent();
}
<input id="data" onkeyup="perform()">
<button id="add" onclick="add()">Add Random Data</button>
To fix your JSFiddle update the following code:
var elem = document.getElementById("sim1");
function triggerKeyUpEvent() {
var e = document.createEvent('HTMLEvents');
e.initEvent("keyup",false,true);
elem.dispatchEvent(e);
}
function add() {
var sim1=document.getElementById("sim1").value;
document.getElementById("box1").value = sim1;
elem.onkeyup();
triggerKeyUpEvent()
}
by replacing the line elem.dispatchEvent(e) with box1.dispatchEvent(e)
And the line elem.onkeyup() with box1.onkeyup()
Lastly, it would seem that you don't need to call triggerKeyUpEvent as when I removed it, it still works.
Here's the udpated JSFiddle
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have my input Field and is using onKeyup and onKeyPress to return number & characters and then to move to the next field.
<input name="aendcodeM" id="aendcodeM" type="text" size="25" maxlength="4" onKeyPress="return numchar(event)" onKeyup="autotab(this, document.form1.bendcodeM)"/>
<input name="bendcodeM" id="bendcodeM" type="text" size="25" maxlength="4" onKeyPress="return numchar(event)" onKeyup="autotab(this, document.form1.bndwdM)"/>
I am trying to use feature of auto-capitalization also for which the code witten as -
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("input").keyup(function() {
var val = $(this).val()
$(this).val(val.toUpperCase())
})
})
</script>
<script>
$(document).ready(function() {
$("textarea").keyup(function() {
var val = $(this).val()
$(this).val(val.toUpperCase())
})
})
</script>
<script>
$(input[type="text"]).on('keypress', function() {
var $this = $(this), value = $this.val();
if (value.length === 1) {
$this.val( value.charAt(0).toUpperCase() );
}
});
</script>
But is of no use since the characters not getting automatically capitalized as desire. Any help in this regard is obliged please.
Thanks & Reagrds
Use css text-transform: uppercase for your input's text & textarea elements as:
input, textarea{
text-transform: uppercase;
}
This will work for you.
Many errors in your code:
why calling function when it isn't initialized?
Uncaught ReferenceError: autotab is not defined error in demo.
<input name="aendcodeM" id="aendcodeM" type="text" size="25" maxlength="4" onKeyPress="return numchar(event)" onKeyup="autotab(this, document.form1.bendcodeM)"/>
^^^^^ ^^^^
Here also ' is missing:
$('input[type="text"]').on('keypress', function() {
^ ^
Working DEMO
How to check Error in console
You should be using only one $(document).ready( ... ) in your Javascript.
Working demo of your code (fixed)
JS:
$(document).ready(function() {
$("input, textarea").keyup(function() {
var val = $(this).val()
$(this).val(val.toUpperCase());
});
$('input[type="text"]').on('keypress', function() {
var $this = $(this), value = $this.val();
if (value.length === 1) {
$this.val( value.charAt(0).toUpperCase() );
}
});
});
Check the demo
Jquery Code
$('[type=text]').keyup(function(){
if($(this).val()!=''){
$(this).val( $(this).val().toUpperCase());
}
});
Doing it that way is unnecessary. I strongly suggest you force uppercase by using the text-transform CSS property.
CSS
input{
text-transform: uppercase;
}
This will force clients to render text in uppercase at all times.
However
Be careful as the values are not. When you proccess your action it is important at that point you convert your value to uppercase either client side or server side.
try this
$( "#aendcodeM" ).bind( "input", function() {
$("#aendcodeM").val($("#aendcodeM").val().toUpperCase());
});
two things
You have to put semi-colon and also check if this is pointing properly
var val = $(this).val();//notice semicolon here
$(this).val(val.toUpperCase());//notice semicolon here
Here is your problem. You need to understand the concepts better. You are trying to register event handler both in javascript and jquery. autocad and numchar functions are not defined and since these are event handlers using javscript, when they get hit it wont work.
Find below the code and also check with this fiddle http://jsfiddle.net/wishy/qbfkhz88/
<input name="aendcodeM" id="aendcodeM" type="text" size="25" maxlength="4" />
<input name="bendcodeM" id="bendcodeM" type="text" size="25" maxlength="4" />
and javascript is
$(document).ready(function() {
$("input").keyup(function() {
var val = $(this).val();
$(this).val(val.toUpperCase());
});
});
$("textarea").keyup(function() {
var valtext = $(this).val()
$(this).val(valtext.toUpperCase())
});
Demo
The above code is works on all the textarea of the page.Firstly we will take take the value of textarea where user is start typing then make it Upper case using inbuilt function of jquery and assign to the textarea.
Sometimes i found that when you use variable name same as function name or same as any keyword, then it throws error
so try to do one thing. Also use ids.
$(document).ready(function() {
$("#text_area").keyup(function() {
var valtext = $(this).val()
$(this).val(valtext.toUpperCase())
})
})
Just have a test with this. May be this is the scenario happening on your case
Also use ids.
see the fiddle http://jsfiddle.net/36bqfms6/
I'm trying to prevent user from inserting * in a textbox.
This is what I was trying to do, but here it only detects * if this is the only inserted character. For example texts like: *, etc.
When allowed characters are mixed with *, then it cannot detect it. For example inputs such as: *hjh, etc..
and maybe how to make it replace only * with "" and not the whole field?
<script type="text/javascript">
function testField(field) {
var regExpr = new RegExp("[^*]");
if(!regExpr.test(field.value)) {
field.value = "";
}
}
</script>
<input type="text" id="searchGamesKeyword" class="searchGamesTextBox"
name="searchGamesKeyword" onblur="testField(this);" />
You forgot to anchor your regexp to the start and end of the string: new RegExp("[^*]")
Try this: var regExpr = /^[^*]*$/ -- it asks for zero or more instances of any character except * anchored at the start and end of the string. Maybe /^[^*]+$/ would be better (note +) if you want to force one or more instances of any character except *.
How about this:
function testField(field) {
field.value = field.value.replace(/\*/g,"");
}
Called from onblur=testField(this) as shown in the question it will take the current value of the field and replace any and all asterisks with an empty string, leaving all other characters untouched. So, e.g., "ab*cde*" would become "abcde".
The g on the end of /\*/g is a flag meaning to match globally - without this flag it would just replace the first match.
The reason your code didn't work is that your regex of [^*] will match (i.e., return true from .test()) if there is a non-asterisk character anywhere in the string.
<script type="text/javascript">
function testField(field, event) {
if (event.charCode == 42) {
event.preventDefault();
}
}
</script>
<input type="text" id="searchGamesKeyword" class="searchGamesTextBox"
name="searchGamesKeyword" onkeypress="javascript:testField(this, event);" />
This should prevent people typing * and copy and pasting it to. Remember to check on the back-end to, because people may have JS disabled in their browsers.
Javascript:
function testField(f)
{
var o='',i,v=f.value;
for(i=0;i<v.length;i++) if(v[i]!='*')o+=v[i];
f.value=o;
}
HTML:
<input type="text" id="searchGamesKeyword" class="searchGamesTextBox" name="searchGamesKeyword" onkeyup="testField(this);" onchange="testField(this);" />
DEMO: http://jsfiddle.net/martinschaer/Sbg6w/ (manually optimized and minified ;))
EDIT:
Using a flag (c) you can avoid having the caret positioned at the end if you try to edit what you've typed so far. Like this:
function testField(f)
{
var t,c,i=0,o='',x="value",v=f[x],l=v.length;
while(i<l){t=v[i++];if(t!='*')o+=t;else c=1}
if(c)f[x]=o
}
Test it here: http://jsfiddle.net/martinschaer/Sbg6w/
This is my code:
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery.field.js" type="text/javascript"></script>
<script src="js/jquery.calculation.js" type="text/javascript"></script>
<script>
$(function() {
$('input[name^=sum]').keyup(function() {
var sum1 = parseFloat($('input[name=sum1]').val()) || 0;
var sum2 = parseFloat($('input[name=sum2]').val()) || 0;
var sum3 = parseFloat($('input[name=sum3]').val()) || 0;
$('#c_card_amount').val(sum1*sum3/100);
$('#total_inc_charges').val((sum1*sum3/100)+sum1);
});
});
</script>
In the input fields I would like to show the numbers in 1,000.00 format.
How can I format the numbers like this? Right now after the calculation numbers sometimes gets messed up like 452.25600000001. I would like to avoid that as well. Would be nice to rule the numbers properly.
Thank you for your help.
I recommend that you use NumberFormatter. Also you can see this question.
I would recommend you to try jQuery Format as mentioned in this question: Format numbers in javascript.
Below is an example of jQuery Format:
$.format.locale({
number: {
groupingSeparator: ',',
decimalSeparator: '.'
}
});
$.format.number(1000, '#,###.00'); // result: 1,000.00
$.format.number(452.25600000001, '#,###.00'); // result: 452.26
I would recommend you to use javascipt instead of jQuery. While jQuery made life more easy but don't forget that jQuery can be too large and your user have to load it on page while browsing.
Read this article for your answer http://www.mredkj.com/javascript/numberFormat.html
I'm not a JS expert but i think what i'm trying to do is pretty simple (at least in jQuery)
I've got 3 select
<select id="faq" class="onchance_fill">...</select>
<select id="pages" class="onchance_fill">...</select>
<select id="faq" class="onchance_fill">...</select>
and an input (it's a tinyMCE one in advlink plugin)
<input type="text" onchange="selectByValue(this.form,'linklisthref',this.value);" value="" class="mceFocus" name="href" id="href" style="width: 260px;">
I want that each time i change a value in one of the 3 select, that this value of the option, will be placed in the input.
In Jquery, it would be something like :
$('.ajax_onchance_fill').change(function() {
data = $('.ajax_onchance_fill').val();
$('#href').text(data);
});
But i can't use it. So what is the equivalent in plain Javascript ?
Thanks
I would advice you keep using Jquery as it speeds up this kind of thing but in pure JavaScript i think what you want looks something like this...
<script type="text/javascript">
function load() {
var elements = document.getElementsByClassName('onchance_fill');
for(e in elements){
elements[e].onchange = function(){
document.getElementById('href').value = this.value;
}
}
}
</script>
document.getElementsByClassName("ajax_onchance_fill").onchange = function() {
getElementById('href').value = this.options[this.selectedIndex].text;
};
Though I am not sure exactly if it'll work since getElementsByClassName returns more than 1 element.
Try this:
$('.ajax_onchance_fill').change(function() {
var data = $(this).val();
$('#mytextboxid').val(data);
});
Okay, so I realize this thread is well over 8 years old, so this answer isn't so much for the OP (who probably figured it out long ago) as it is for someone else who might be curious about this particular topic.
All that said, here's a relatively simple and reliable way you could pull it off in vanilla JS:
/**
* Since we need to listen to all three ajax_onchance_fill elements,
* we'll use event delegation.
*
*/
const targetLink = document.getElementById('href');
document.addEventListener('change', function(e) {
if (!!Element.prototype.matches) { // Let's make sure that matches method is supported...
if (e.target.matches('.ajax_onchance_fill')) {
targetLink.textContent = e.target.value;
}
} else { // and if not, we'll just use classList.contains...
if (e.target.classList.contains('ajax_onchance_fill')) {
targetLink.textContent = e.target.value;
}
}
});