Characters inserting in wrong index of the string - javascript

I am trying to insert additional characters in a specific string.
function sample(x) {
if (x.value.length > 2 && x.value.length < 5) {
var first = x.value.substring(0, 2) + "'";
var second = x.value.substring(2, x.value.length) + "''";
x.value = first + "" + second ; }
}
<input id="txt" type="text" placeholder="onkeypress" onkeypress="sample(this)" value="" /><br />
<input id="txt1" type="text" placeholder="onchange" onchange="sample(this)" value="" />
By using onchange attribute in htmlinput, the code runs perfectly. But can this also run with onkeypress attribute? If value of inputs is 1006, the result should be 10'06''. Help. Thanks.

Try this:
You need to replace the quotes('/") before manipulating the string. Also use keyup event. Refer this to understand the purpose of each events. onkeyup is fired when the key is released
function sample(x) {
x.value = x.value.replace(/[\'\"]/g, '');
if (x.value.length > 2 && x.value.length < 5) {
var first = x.value.substring(0, 2) + "'";
var second = x.value.substring(2, x.value.length) + "''";
x.value = first + "" + second;
}
}
<input id="txt" type="text" placeholder="onkeypress" onkeyup="sample(this)" value="" />
<br/>
<input id="txt1" type="text" placeholder="onchange" onchange="sample(this)" value="" />

I see this was already correctly answered, but here's my take.
Adding a timeout to formatting function would give user a chance to enter 4 characters before formatting kicks in and potentially confuses user:
function sample(x) {
setTimeout(function() {
if (x.value.length > 2 && x.value.length < 5) {
var first = x.value.substring(0, 2) + "'";
var second = x.value.substring(2, x.value.length) + "\"";
x.value = first + second;
}
}, 1500); // this is the timeout value in milliseconds
}
Please see this CodePen for a working example:
http://codepen.io/Tiketti/pen/YyVRwb?editors=101

The difference between onchange and onkeypress is,
onchange detects the change in length and values when control is released from element
onkeypress detects the change in length on keypress but change in value on another key press. The length starts from 0 it means if I enter 4567, while typing 7, the length is 0,1,2,3 but value is 456 even the 7 is present in input. But when you press 8 it shows 4567.
You can see that happening here http://codepen.io/anon/pen/XmRydE
function sample(x) {
console.log(x.value);
console.log(x.value.length);
if (x.value.length > 2 && x.value.length < 5) {
var first = x.value.substring(0, 2) + "'";
var second = x.value.substring(2, x.value.length) + "''";
x.value = first + "" + second ; }
}
function sampleKeyPress(x) {
console.log(x.value);
console.log(x.value.length);
if (x.value.length >= 4 && x.value.length < 5) {
var first = x.value.substring(0, 2) + "'";
var second = x.value.substring(2, x.value.length) + "''";
x.value = first + "" + second ; }
}
<input id="txt" type="text" placeholder="onkeypress" onkeypress="sampleKeyPress(this)" value="" /><br />
<input id="txt1" type="text" placeholder="onchange" onchange="sample(this)" value="" />

Related

Display times table up to 12 based on the users input

it seems to think ttinput is a string when I console.log the variable it says "". All else seems to working I just can't figure out how to have ttinput as a number.
document.getElementById("enter").addEventListener("click", ttcalc)
var ttinput = document.getElementById("table").value;
var ttoutput;
function ttcalc(){
var display = "";
for(var i = 1; i <= 12; i++){
ttoutput = ttinput * i;
display += ttinput + "*" + i + "=" + ttoutput + "<br>"
console.log(ttoutput, ttinput, i);
}
document.getElementById("output").innerHTML = display;
}
this is my html
<form>
<h1>Enter what times table you wish to see</h1>
<input type="number" id="table"><br>
</form>
<button id="enter">Show Times Table</button>
</div>
The problem is that the value of
var ttinput = document.getElementById("table").value;
is read on page load (while the input field is empty). If you move that line of code inside your function it will read the value of the input field after the button is clicked.
If you want to be sure the value entered is a number you can use the parseInt() function and then check if the result is a number with the isNaN() function like this:
var ttinput = parseInt(document.getElementById("table").value);
and then use isNaN():
if( !isNaN(ttinput) ) {
// ttinput is a number
} else {
// ttinput is not a number
}
More here: parseInt and isNaN.
Check example below:
document.getElementById("enter").addEventListener("click", ttcalc)
function ttcalc() {
var ttinput = parseInt(document.getElementById("table").value);
var ttoutput;
var display = "";
if( !isNaN(ttinput) ) {
for(var i = 1; i <= 12; i++) {
ttoutput = ttinput * i;
display += ttinput + "*" + i + "=" + ttoutput + "<br>"
console.log(ttoutput, ttinput, i);
}
document.getElementById("output").innerHTML = display;
} else {
console.log("value is not a number");
}
}
<button id="enter">Enter</button>
<input type="text" id="table" value="">
<div id="output"></div>

how to print based on value entered

so If I entered 10, number 10 should be printed ten times
function function_name(number) {
for (var counter = 1; counter <= number; counter++) {
document.write("the number is" + number);
}
}
<label for="number">Enter number: </label>
<input name="number" id="number" />
Looks like you just need to:
Add a button to your HTML
Add a click handler to your button that will activate your function
function writeTimes(number) {
for (var counter = 1; counter <= number; counter++) {
document.write("the number is" + number);
}
}
function doTheThing() {
var input = document.getElementById("my-input"); //get the input element
var numberOfTimes = input.value; //get the number of times
writeTimes( numberOfTimes ); //call your function
}
<label for="number">Enter number: </label>
<input id="my-input" name="number" id="number" />
<button onclick="doTheThing()">Go</button>
// This function *does* something. Give it a name that reflects it's behavior.
// You can always rename it later if you change what it does.
//
function spamNumber(number) {
// Use let instead of var, it's replacement for var with less wtf behavior
//
for (let counter = 1; counter <= number; counter++) {
// I don't care for document.write. It's totally unusable in production code.
// But sure, why not? At least add a line break so the outputs
// don't smush together.
//
document.write("the number is " + number + '<br/>');
}
}
// Find the input element so we can add a listener
//
document.querySelector('input')
// Listening in this case only to keydowns that occur while input has focus.
//
.addEventListener('keydown', function onKeydown(evt) {
if (event.key === 'Enter') {
// evt.target is the input element, number in it's value property.
// Force value to integer in case someone inputs garbage. We can
// fail silently and move on.
//
spamNumber( parseInt(evt.target.value) || 0)
}
})
// Now type in your number and press Enter
<label for="number">Enter number: </label>
<input name="number" id="number" />
From your question and comments , i think you are looking for this:
onload = function (){
var result = document.getElementById('result');
var number = document.getElementById('number');
number.oninput = function (){
if(number.value == "0" || number.value.length == ""){result.innerHTML="";}else{}
var counter = "";
var repeat =number.value;
while (repeat > 0) {
repeat--;
var str =" (the number is " + parseInt(number.value)+" )";
result.innerHTML= str.repeat(number.value);
}
return counter;
number.onpropertychange = number.oninput;
number.onchange = number.oninput;
}};
<label for="number">Enter number: </label>
<input name="number" id="number" /><br />
<span id=result></span>

For loop with user input javascript

So basically I have a for loop and I am trying to get it to run x amount of times. Depending on what the user inputs. The issue I am having is how to get the user input and also make sure that its a number not any other type of input. making them try again if its wrong.
It's simple really
Input Number : <input id="numberinput" onkeypress="return event.charCode >= 48 && event.charCode <= 57" />
<button id="btn" onclick="doAction()">
Send
</button>
<script>
var doAction = function () {
var input = document.getElementById('numberinput');
var times = parseint(input.value);
for(var i = 0; i < times; i++) {
//do whatever you need to do
}
}
</script>
In HTML5 you can use <input type="number"> to restrict an input to numeric characters only.
For older browsers, that are not HTML5-compatible, use <input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input>. This utilizes Javascript to make sure that only numeric input is accepted into the input box.
Check out the snippet below for both solutions in action:
Javascript-based:<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input>
<br><br>
HTML5 solution (preferred):<input type="number">
Fiddle
HTML
<input type="number" id="myInput">
<button id="myButton">Run Loop</button>
Javascript
$('body').on('click', '#myButton', function() {
var input = $('#myInput').val();
for(var i = 0; i < input; i++) {
alert('You have written inside input field: ' + input + ". This is Alert #" + (i+1))
}
});
To get the value from the input, you can use the value property of the input element.
To make sure the input is a number, you can specify type="number" if HTML5 is supported as mentioned in Angelos Chalaris's answer.
document.getElementById('btn').onclick = function(){
var totalIterations = parseInt(document.getElementById('input').value);
var output = document.getElementById('output');
output.innerHTML = '';
for(var i = 1; i <= totalIterations; i ++) {
var item = document.createElement('div');
item.innerHTML = i;
output.appendChild(item);
}
};
<input id="input" type="number"/>
<input id="btn" type="button" value="Do loop"/>
<div id="output"></div>
Here is an example using user input dialog:
var input, parsedInput = 0;
do {
input = prompt("Please enter valid number", "1");
parsedInput = parseInt(input);
} while(isNaN(parsedInput) || parsedInput < 0);
// keep trying on invalid input or negative number
for( i=0; i< parsedInput ; i++){
console.log("loop " + i);
}
HTML:
<input type="text" name="somefield" id="someid" value="10" />
JS:
var userInput = document.getElementById('someid').value;
if( Number.isInteger(parseInt(userInput)) )
{
// do something
}
Also, Number.isInteger() does not work on Internet explorer 11 or earlier.

this parameter not passing expected element

I have a dynamic set of input fields being generated. They all get named sequentially and each has an onFocus() handler. Just before each Input element is a div with a corresponding Id where I grab a dollar value from.
<input type="hidden" name="balance" value="2500.0" />
<div id="invoiceAmount0">$500.00</div>
<input type="text" size="8" id="invoiceBalance0" name="invoiceBalance0" value="" onfocus="setBalance(this)" />
<div id="invoiceAmount1">$500.00</div>
<input type="text" size="8" id="invoiceBalance1" name="invoiceBalance1" value="" onfocus="setBalance(this)" />
<div id="invoiceAmount2">$500.00</div>
<input type="text" size="8" id="invoiceBalance2" name="invoiceBalance2" value="" onfocus="setBalance(this)" />
The JS onFocus handler is as follows:
function setBalance(e) //e should be an input field element
{
var balance = document.PaymentForm.balance.value;
var remainder = balance;
var index = 0;
var paymentField = document.getElementById('invoiceBalance'+index); //get the first input payment element
while (paymentField != null && paymentField != e) //start with the first field and calculate the remaining balance
{
var paymentApplied = paymentField.value.replace(/[^0-9\.]+/g,"");
remainder = remainder - paymentApplied;
index++;
paymentField = document.getElementById('invoiceBalance'+index);
}
while (e == paymentField) //set the selected elements value
{
var invoiceBalance = document.getElementById('in'+index).innerHTML.replace(/[^0-9\.]+/g,"");
if (parseFloat(remainder) > parseFloat(invoiceBalance))
e.value = parseFloat(invoiceBalance).toFixed(2).toLocaleString();
else
e.value = parseFloat(remainder).toFixed(2).toLocaleString();
index++;
paymentField = document.getElementById('invoiceBalance'+index);
}
while (paymentField != null) //blank out the rest of the input fields
{
paymentField.value = '';
index++;
paymentField = document.getElementById('invoiceBalance'+index);
}
e.select();
}
The concept here is to calculate the remaining balance and set the input field's value as the user focuses the fields.
The problem is that The "this" parameter is always set to the first Input element "invoiceBalance0". I'm expecting it to be set to the element referring to it in it's onFocus handler.
What am I not seeing?
I'm unable to duplicate the error you describe, but I did notice what appears to be a typo:
var invoiceBalance = document.getElementById('in'+index).innerHTML.replace(/[^0-9\.]+/g,"");
looks like it should be
var invoiceBalance = document.getElementById('invoiceAmount'+index).innerHTML.replace(/[^0-9\.]+/g,"");
function setBalance(e) //e should be an input field element
{
var balance = document.querySelector('[name="balance"]').value;
var remainder = balance;
var index = 0;
var paymentField = document.getElementById('invoiceBalance' + index); //get the first input payment element
while (paymentField != null && paymentField != e) //start with the first field and calculate the remaining balance
{
var paymentApplied = paymentField.value.replace(/[^0-9\.]+/g, "");
remainder = remainder - paymentApplied;
index++;
paymentField = document.getElementById('invoiceBalance' + index);
}
while (e == paymentField) //set the selected elements value
{
var invoiceBalance = document.getElementById('invoiceAmount' + index).innerHTML.replace(/[^0-9\.]+/g, "");
if (parseFloat(remainder) > parseFloat(invoiceBalance))
e.value = parseFloat(invoiceBalance).toFixed(2).toLocaleString();
else
e.value = parseFloat(remainder).toFixed(2).toLocaleString();
index++;
paymentField = document.getElementById('invoiceBalance' + index);
}
while (paymentField != null) //blank out the rest of the input fields
{
paymentField.value = '';
index++;
paymentField = document.getElementById('invoiceBalance' + index);
}
e.select();
}
<input type="hidden" name="balance" value="2500.0" />
<div id="invoiceAmount0">$500.00</div>
<input type="text" size="8" id="invoiceBalance0" name="invoiceBalance0" value="" onfocus="setBalance(this)" />
<div id="invoiceAmount1">$500.00</div>
<input type="text" size="8" id="invoiceBalance1" name="invoiceBalance1" value="" onfocus="setBalance(this)" />
<div id="invoiceAmount2">$500.00</div>
<input type="text" size="8" id="invoiceBalance2" name="invoiceBalance2" value="" onfocus="setBalance(this)" />
It's work after changing this line :
var invoiceBalance = document.getElementById('in'+index).innerHTML.replace(/[^0-9\.]+/g,"")
To :
var invoiceBalance = document.getElementById('invoiceBalance'+index).innerHTML.replace(/[^
0-9\.]+/g,"");
that because you don't have an id like in[index] but this form invoiceBalance[index], hope that will help See
Working Fiddle.

How to check number being entered in textbox dynamically?

i have 5 textbox like
<input type ="text" size="3" name="r"><br>
<input type ="text" size="3" id="1" onchange="vali(this.id)" name="I"><br>
<input type ="text" size="3" name="a"><br>
<input type ="text" size="3" name="s"><br>
<input type ="text" size="3" name="e">
function vali(d){
if(document.getElementById(d).value <0 || document.getElementById(d).value >=30)}
I want user should enter only max 2 digits on each field between 0 & 30. I'm not able to restrict user to enter only 2 digits in field, for example when user enters 151, 15 should come on 1st field and then focus will go on 2nd field automatically and remaining digits will be entered in 2nd field and will be there till the user enters another digit. After entering focus will come on field 3 like this. Also I need to check to each field contain a number between 0 and 30 which I'm checking in above code.
Also when user submit the form all field should be checked for value between (0 to 30) If there is any field present alert bos should pop up else go to next page.i m not able to do this part .this is my form part above the 5 input field
<form name="detail" action ="selectjzone.jsp" onsubmit="return validate(this)">
and edited part is
if (num < 0) {
alert("The value enteres for " +" " + document.getElementById(obj.id).name + " " + "is outside the range0 to 30" );
return false;
} else if (num > 30) {
alert("The value enteres for " +" " + document.getElementById(obj.id).name + " "+ "is outside the range0 to 30" );
return false;
}
return true;
}
Here's a start at how to validate the field and move any extra to the next field:
Working demo here: http://jsfiddle.net/jfriend00/vpTq5/
HTML:
<input id="a" type ="text" size="3" onkeyup="validate(this, 'b')" name="r"><br>
<input id="b" type ="text" size="3" onkeyup="validate(this, 'c')" name="I"><br>
<input id="c" type ="text" size="3" onkeyup="validate(this, 'd')" name="a"><br>
<input id="d" type ="text" size="3" onkeyup="validate(this, 'e')" name="s"><br>
<input id="e" type ="text" size="3" onkeyup="validate(this)" name="e">
Javascript:
function validate(obj, next) {
// fetch value and remove any non-digits
// you could write more code to prevent typing of non-digits
var orig = obj.value;
var mod = orig.replace(/\D/g, "");
var nextObj;
// check length and put excess in next field
if (mod.length > 2) {
// shorten the current value
obj.value = mod.substring(0,2);
if (next) {
// put leftover into following value
var nextObj = document.getElementById(next);
if (!nextObj.value) {
nextObj.value = mod.substring(2);
nextObj.focus();
}
}
} else {
// only set this if necessary to prevent losing cursor position
if (orig != mod) {
obj.value = mod;
}
}
// convert to number and check value of the number
var num = Number(obj.value);
// don't know what you want to do here if the two digit value is out of range
if (num < 0) {
obj.value = "0";
} else if (num > 30) {
obj.value = "30";
}
}
Some notes:
Id values on HTML objects cannot start with a digit. They must start with a letter.
You will have to decide what behavior you want when a number greater than 30 is entered.
Keep in mind that input field values are strings. If you want to treat them like a number, you have to convert them to be numeric.
With more code, you can actually prevent the typing of non-numeric keys and you can move the focus before the 3rd value is typed.
There are ways to get data into fields that does not trigger onkeyup (copy/paste, drag/drop) so you will have to validate at other times too.
If you can use a framework like jQuery, this can be done in a simpler way.
Here is the code for automatic focusing on next field when you keep on typing,
you need to take of validating number between 0 & 30. Hope this helps,
<script>
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function chkEvent(e){
var keyCode = (isNN) ? e.which : e.keyCode;
if(e.shiftKey==1 && keyCode == 9) return false;
if(e.shiftKey==1 || keyCode == 9 || keyCode == 16) return false;
return true;
}
function autoTab(current,to, e) {
var keyCode = (isNN) ? e.which : e.keyCode;
var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
if(current.getAttribute && current.value.length == current.getAttribute("maxlength") && !containsElement(filter,keyCode)) to.focus();
function containsElement(arr, ele) {
var found = false, index = 0;
while(!found && index < arr.length) if(arr[index] == ele) found = true; else index++;
return found;
}
return true;
}
</script>
<input type ="text" size="3" maxlength="2" name="r" onkeyup="if(chkEvent(event)){return autoTab(this, document.getElementById('1'), event);}"><br>
<input type ="text" size="3" maxlength="2" id="1" onkeyup="if(chkEvent(event)){return autoTab(this, document.getElementById('a'), event);}" name="I"><br>
<input type ="text" size="3" maxlength="2" id="a" name="a" onkeyup="if(chkEvent(event)){return autoTab(this, document.getElementById('s'), event);}"><br>
<input type ="text" size="3" maxlength="2" id="s" name="s" onkeyup="if(chkEvent(event)){return autoTab(this, document.getElementById('e'), event);}"><br>
<input type ="text" size="3" maxlength="2" id="e" name="e" >
Here is pure javascript solution is it like what you wanted at all?
http://jsfiddle.net/rfyC8/
Code:
var ieEvents = !!document.attachEvent,
addEvent = ieEvents ? "attachEvent" : "addEventListener",
keyUp = ieEvents ? "onkeyup" : "keyup";
function validator( e ) {
var sib, intValue, val = this.value;
if( val.length >= 2 ) {
intValue = parseInt( val, 10 );
if( isNaN( intValue ) || intValue < 0 || intValue > 30 ) {
this.value = "";
return false;
}
sib = this.nextSibling;
while( sib && sib.className != "textfield" ) {
sib = sib.nextSibling;
}
if( sib ) {
sib.focus();
}
else {
return false;
}
}
}
document.getElementById("textfields")[addEvent]( keyUp,
function(){
var e = arguments[0] || window.event,
target = e.target || e.srcElement;
if( target.className == "textfield" ) {
validator.call( target, e );
}
},
false
);
Use maxlength attribute to limit number of input
maxlength="2"
After settting the above you can use onkeyup event to check the length and change focus
$('#target').keyup(function () {
var maxlength = $(this).attr('maxlength');
if ($(this).val().trim().length == maxlength){
//change focus to next input
//change focus to next input
var inputs = $(this).closest('form').find(':input');
inputs.eq(inputs.index(this) + 1).focus();
}
});

Categories

Resources