Get value from combobox and add a number to it - javascript

I am trying to get the "value" from a combo box and simply add one to it. I think I need to convert it to a integer but can't make parse work either. Next I want to put that new number into a text box.
<script type="text/javascript">
function GetNextCategoryNum(sel)
{
var NextNumber;
var number = sel.options[sel.selectedIndex].value; 
NextNumber = number ++1;
alert("Last number used " + number );
textbox = NextNumber
}
</script>

Three mistakes in your code:
1. value will return a string. So you need to change it to an integer.
2. "number ++1" is wierd. What you need is ++number. If you do not want to increase "number" but "NextNumber", then just put on number + 1.
3. What is "textbox"? if it refers to a textbox object then you need declaring it.
So what I suggest is:
<script type="text/javascript">
function GetNextCategoryNum(sel)
{
var NextNumber;
var textbox = document.getElementById("textbox");
var number = parseInt(sel.options[sel.selectedIndex].value);
NextNumber = number + 1;
alert("Last number used " + number );
textbox.value = NextNumber;
}
</script>

Related

How to create ordered list inside text area using javascript?

I have a text area where I add the number of orderlist item on click of a button.This is my code,
var addListItem = function() {
if (!this.addListItem.num) {
this.addListItem.num = 0
}
++this.addListItem.num;
var text = document.getElementById('editor').value;
console.log('text', text);
var exp = '\n' + this.addListItem.num + '.\xa0';
text = text.concat(exp);
document.getElementById('editor').value = text;
}
<div>
<button onclick="addListItem()">NumberList</button>
<textarea id="editor" col=10 rows=10></textarea>
</div>
As I have used a static variable to increment it increments on every click and so if I delete the list and create a new list again it doesn't starts from '1' and also I couldn't figure out how to update the numbers when a item is added in between.Could anyone suggest me how to fix this?
If you want a more robust solution that handles all sorts of different cases, you can use regular expressions to detect what number you're at in your list.
This solution also allows users to type in their own numbers and the button click WILL STILL WORK!
That's because this solution uses the text area content as the source of truth and doesn't track state on the side.
var addListItem = function() {
var text = document.getElementById('editor').value;
// regex to match against any new line that has a number and a period
// and extracts the number. feel free to use regex101.com to understand
// this in more depth.
var listNumberRegex = /^[0-9]+(?=\.)/gm;
var existingNums = [];
var num;
// get all the matches
while ((num = listNumberRegex.exec(text)) !== null) {
existingNums.push(num);
}
// sort the values
existingNums.sort();
// use the existing biggest number + 1 or use 1.
var addListItemNum;
if (existingNums.length > 0) {
// get last number and add 1
addListItemNum = parseInt(existingNums[existingNums.length - 1], 10) + 1;
} else {
// otherwise if there's nothing, just use 1.
addListItemNum = 1;
}
var exp = '\n' + addListItemNum + '.\xa0';
text = text.concat(exp);
document.getElementById('editor').value = text;
}
<div>
<button onclick="addListItem()">NumberList</button>
<textarea id="editor" col=10 rows=10></textarea>
</div>
understanding regular expressions is tricky, feel free to view https://regex101.com/r/gyX7oO/1 to get a better understanding of what is going on.
You can try something like this:
Logic:
On every click, get the text in textarea and split it be new line.
Now that you have line items, you need to get last sentence that starts with a numeric value. But user can enter new lines on his own to format text.
For this, loop on every line and validate it it starts with number followed by ..
If yes, use substring to fetch this number and parse it to int. If no match is found, you can return 0.
This will ensure the numbering system and you do not need a variable to hold last value.
Note: This logic assumes that last value will be the maximum. If you wish to handle that, you can just compare n and parseInt and assign maximum value
Sample:
var addListItem = function() {
var text = document.getElementById('editor').value;
var exp = '\n' + (getLastNumber(text) + 1) + '.\xa0';
text = text.concat(exp);
document.getElementById('editor').value = text;
}
function getLastNumber(str){
var list = str.split(/[\r\n]/g);
var n = 0;
list.forEach(function(s){
if(/^\d+\./.test(s)){
n = parseInt(s.substring(0, s.indexOf(".")));
}
});
return n;
}
<div>
<button onclick="addListItem()">NumberList</button>
<textarea id="editor" col=10 rows=10></textarea>
</div>
If you delete the list and create a new list again it will start from '1'.
also, counts from whatever the last number is.
var addListItem = function() {
if (!this.addListItem.num) {
this.addListItem.num = 0
}
++this.addListItem.num;
var text = document.getElementById('editor').value;
//HERE start new counting if textarea is empty
if(text.trim() == ''){
this.addListItem.num = 1; //restart counting here
}
//else check if textarea has previous numbers to proceed counting
else {
var lastLine = text.substr(text.lastIndexOf("\n") + 1).trim();
this.addListItem.num = parseInt(lastLine.slice(0, -1)) + 1; //add 1 to last number
}
console.log('text', text);
var exp = '\n' + this.addListItem.num + '.\xa0';
text = text.concat(exp);
document.getElementById('editor').value = text;
}
<div>
<button onclick="addListItem()">NumberList</button>
<textarea id="editor" col=10 rows=10></textarea>
</div>

Adding percentage to a price field incl. currency code

I'm trying to add 10% to a price field via javascript and so far i haven't been able to, and was hoping you guys would be able to help.
The field incl. currency code etc.
I did try something in this direction:
<script type="text/javascript">
$( document ).ready(function() {
var Total = $("#cashamount");
Total.val(Total.val() * 1.1);
});
</script>
But that didn't work ;(
The price field shows up like the following.
<span id="cashamount" class="additional xxlarge carrental_total_amount">48,300.00 ISK</span>
After adding the 10% to the price, it should say in this example:
<span id="cashamount" class="additional xxlarge carrental_total_amount">53,130.00 ISK</span>
Any ideas are welcome, and i would really appreciate help on this matter as i do think it's fairly simple but i'm not very well into Javascripting.
First this: (solution below)
The .val() method is primarily used to get the values of form elements
such as input, select and textarea. In the case of elements, the
.val() method returns an array containing each selected option; if no
option is selected, it returns null, jQuery docs
The .text() method cannot be used on form inputs or scripts. To set or
get the text value of input or textarea elements, use the .val()
method. To get the value of a script element, use the .html() method,
jQuery docs
So, one solution would be next:
var Total = $("#cashamount");
var totalNumber = Number(Total.text().replace(/[^0-9\.]+/g,""));
Total.text((totalNumber * 1.1).toFixed(2));
//Add currency to this
Here's JsFiddle
var x = $("#cashamount").html(); // Fetching the value
var xSplit = x.split(" "); // Splitting the currency and ammount and storing it in array.
var intAmmt = +xSplit[0].replace(/,/g , ""); // Removing comma and Making it a integer
var newAmmt = intAmmt*1.1; // Incrementing by 10%
var y = newAmmt.toLocaleString() + " " + xSplit[1]; // Adding the currency sign with a space
$("#cashamount").html(y); // Setting the html;
So you can create a function for this:
function updateVal(elem){
var x = elem.html(); // Fethching the value
var xSplit = x.split(" "); // Splitting the currency and ammount and storing it in array.
var intAmmt = +xSplit[0].replace(/,/g , ""); // Removing comma and Making it a integer
var newAmmt = intAmmt*1.1; // Incrementing by 10%
var y = newAmmt.toLocaleString() + " " + xSplit[1]; // Adding the currency sign with a space
elem.html(y); // Setting the html;
}
and use it as:
$(document).ready(function(){
updateVal($("#cashamount"))
});

how to get value of an input box in html and do operations on it

I was testing a simple code to:
Get value of an input box
Do Mathematical operations on it...
My Code:
setInterval(function(){var a=document.getElementById("myInputBox").value;var b=a+1;a.value=b;},1000);
I am trying to add 1 to the value of that input box, every 1 second.
For example, if the box has value 1 ,then after 1 second it should become 2,....and so on.....
But it gets joined with the box's value, like 11 instead of 2.
Why is that?
Try with full code & demo:
get value from inputbox is a string, so it can't calculate mathematically. so, at first convert string to numeric by using function parseInt and then calculate and put into box.
setInterval(function() {
var box = document.getElementById("myInputBox");
var r = parseInt(box.value, 10) + 1;
box.value = r;
}, 1000);
<input type="text" id="myInputBox" value="1" />
var b = parseInt(a) + 1;
a is a string, so the + is interpreted as string concatenation by default. To fix, pass a to parseInt because it returns a type integer. Now the + becomes a math operator.
Extra Credit:
var b = parseInt(a, 10) + 1;
For an extra measure of integrity, pass the second (radix) argument, ensuring base 10 is used to determine the return integer value.

Obtain numbers from a field and process them

I have a field which obtains it input through a list of links associated with numbers. (Similar to a calculator but without operators). I want to retrieve these numbers and put them through a function which divides them by 12. (A conversion from feet to inches).
First I have a list of jQuery click functions like this:
$('#a0').click(function(){
writeInput(input, one); // var one = 1;
});
Next I have the function "write Input" (This is where the numbers are displayed on a "screen")
function writeInput(field, str){
$input = $(field);
var text = $input.val($input.val() + str);
$input.text(text);
convert(text);
}
And lastly I have a function which is supposed to divide the number inputted by 12
function convert(input){
var divide = (input / 12);
$("#output").html(divide); //output is a paragraph where the number is displayed
}
When I run my code I am getting NAN output where the number should be. I have tried parseInt() and other tricks. But the closest I have come to something correct is when I got [object] [object] output.
Any help would be appreciated. Thanks!
In your code text is a jQuery object, you are using val as setter which returns a jQuery object, you should use val/text method as a getter for retrieving updated value.
function writeInput(field, str){
var text = $(field).val(function(i, v){
return v + str;
}).text(function(i, t){
return t + str
}).val();
convert(text);
}

Getting input text box value of display type "Number" in Client Side Java Script (CSJS)

I've been trying to get the value of input text box from Client Side like this:
var CKQtyToDate = XSP.getElementById("#{id:CKQtyToDate}");
var CKQtyToDate = XSP.getElementById("#{id:CKQtyToDate}");
var SLQtyToDate = XSP.getElementById("#{id:SLQtyToDate}");
var FinishingQtyToDate = XSP.getElementById("#{id:FinishingQtyToDate}");
var PackingQtyToDate = XSP.getElementById("#{id:PackingQtyToDate}");
if ((parseInt(CKQtyToDate.value)+parseInt(SLQtyToDate.value)+parseInt(FinishingQtyToDate.value)+parseInt(PackingQtyToDate.value))>parseInt(hContractQty.value))
{
alert("Total qty more than contract qty! =" + parseInt(CKQtyToDate.value)+parseInt(SLQtyToDate.value)+parseInt(FinishingQtyToDate.value)+parseInt(PackingQtyToDate.value));
return false;
}
But I'm still having the result which is only string concatenation,how can i get through this thing???
First of all, in Javascript parseInt returns NaN when parsing an empty string. So make sure to test for empty strings before doing the calculation. You can test if the string can be parsed by using !isNaN(string).
I believe that your problem is that you concatenate strings in your alert box. I will suggest that you move the calculation to a seperate variable and then concatenate the message string with this variable in the alert box:
var result = parseInt(CKQtyToDate.value)+parseInt(SLQtyToDate.value)+parseInt(FinishingQtyToDate.value)+parseInt(PackingQtyToDate.value);
if (result>parseInt(hContractQty.value))
{
alert("Total qty more than contract qty! =" + result);
return false;
}

Categories

Resources