Numeric to alphabet code is not working in Javascript - javascript

Recently I made a function called Converter. It was working perfectly in the morning and now when I am using it, the code is not being able to run when I type numeric like 3 it should print like Three but I do now know what is the problem and problem also not showing. I am new in Javascript
Here is the code
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
function abc()
{
// alert('hello');
var amt=parseInt(document.getElementById('t1'));
var d="";
var ones=Array("","One","Two","Three","four","five");
var tens=Array("","","Twenty","Thirthy","Fourthy","fifthy");
var hundreds=Array("","One hundred","Two hundred","Three hundred","Four hundred","Five hundred");
if(amt>=1&&amt<=19)
{
d=ones[amt];
}
document.getElementById('p1').innerHTML=d;
// document.write(d);
}
</script>
</head>
<body>
<input type="text" id="t1" />
<input type="button" value="Convert" onclick="abc()" />
<p id="p1"></p>
</body>
</html>

You forgot to parse the value of textbox
it should be
document.getElementById('t1').value

In addition to my comment on not grabbing the value.
Use let amt = document.getElementById('t1').value. This returns the value inside the input.
Someone made a good example for what you are trying to do here: Convert digits into words with JavaScript
var a = ['', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine ', 'ten ', 'eleven ', 'twelve ', 'thirteen ', 'fourteen ', 'fifteen ', 'sixteen ', 'seventeen ', 'eighteen ', 'nineteen '];
var b = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
function inWords(num) {
if ((num = num.toString()).length > 9) return 'overflow';
n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);
if (!n) return;
var str = '';
str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + 'crore ' : '';
str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + 'lakh ' : '';
str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + 'thousand ' : '';
str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
str += (n[5] != 0) ? ((str != '') ? 'and ' : '') + (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) + 'only ' : '';
return str;
}
document.getElementById('number').onkeyup = function() {
document.getElementById('words').innerHTML = inWords(document.getElementById('number').value);
};
<span id="words"></span>
<input id="number" type="text" />

Your bug was caused of this line: parseInt(document.getElementById('t1'));
You were trying to parseInt(html input element). There is no way to parse HTML value to int, so it was returning NaN, which cannot be converted to "Three" or any other number.
Here's working code:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
function abc()
{
var amt=document.getElementById('t1').value;
var d="";
var ones=Array("","One","Two","Three","four","five");
var tens=Array("","","Twenty","Thirthy","Fourthy","fifthy");
var hundreds=Array("","One hundred","Two hundred","Three hundred","Four hundred","Five hundred");
if(amt>=1&&amt<=19)
{
d=ones[amt];
}
document.getElementById('p1').innerHTML=d;
// document.write(d);
}
</script>
</head>
<body>
<input type="text" id="t1" />
<input type="button" value="Convert" onclick="abc()" />
<p id="p1"></p>
</body>
</html>

Related

How do I use selectors to get different variable for ifs?

I'm working on a tool for my job to auto generate task comments to streamline agent workflow. I'm trying to use a selector to differentiate between ticket types and generate a comment string accordingly.
The problem I'm running into is I can't seem to get the page to tell the the selector has changed, and it will only give the if condition and ignore the else.
I'm certain I'm missing something simple but can't seem to figure it out.
<!DOCTYPE html>
<html>
<body>
Select Ticket Type:
<label name="ticket" id="ticket"></label>
<select name="ticket" id="ticket">
<option value="1">SMB</option>
<option value="2">Complete</option>
</select>
<input type="text" id="ticketgen" placeholder="EnterTicket number" maxlength="8">
<input type="button" id="tickgen" value="Generate">
<p id="output"></p>
</body>
<script>
const txt1 = document.getElementById('ticketgen');
const btn1 = document.getElementById('tickgen');
const out1 = document.getElementById('output');
function fun1() {
var tick = document.getElementById('ticket');
var today = new Date();
var date = (today.getMonth() + 1) + '-' + today.getDate() + '-' + today.getFullYear();
var time = today.getHours() + ':' + today.getMinutes();
var dateTime = date + ' ' + time;
setInterval(1000);
if (tick = 1) {
out1.innerHTML = "Correspondence:" + ' ' + dateTime + ' ' + txt1.value + ' ' + "SMB Correspondence";
} else {
out1.innerHTML = "Correspondence:" + ' ' + dateTime + ' ' + txt1.value + ' ' + "# attempt, contacted CX #";
}
}
btn1.addEventListener('click', fun1);
</script>
</html>
A few issues to address:
your comparison needs a double equal - ==
tick itself is just an html element, you can't compare it to a number, you need to get the currently selected index
you use id=ticket twice, so when you get the html element by that ID, it grabs the first one, which is a label.
I believe this code should fix your issues
<!DOCTYPE html>
<html>
<body>
Select Ticket Type:
<label name="ticket" id="ticket-label"></label>
<select name="ticket" id="ticket">
<option value="1">SMB</option>
<option value="2">Complete</option>
</select>
<input type="text" id="ticketgen" placeholder="EnterTicket number" maxlength="8">
<input type="button" id="tickgen" value="Generate">
<p id="output"></p>
</body>
<script>
const txt1 = document.getElementById('ticketgen');
const btn1 = document.getElementById('tickgen');
const out1 = document.getElementById('output');
function fun1() {
var tick = document.getElementById('ticket');
var today = new Date();
var date = (today.getMonth()+1)+'-'+today.getDate()+'-'+today.getFullYear();
var time = today.getHours() + ':' + today.getMinutes();
var dateTime = date+' '+time;
setInterval(1000);
if (tick.selectedIndex == 0){
out1.innerHTML = "Correspondence:"+' '+dateTime+' '+txt1.value+' '+"SMB Correspondence";
} else {
out1.innerHTML = "Correspondence:"+' '+dateTime+' '+txt1.value+' '+"# attempt, contacted CX #";
}
}
btn1.addEventListener('click',fun1);
</script>
</html>
Your value for tick would be a string and you are checking it as integer. Try by changing it to, if (tick == "1").
Label attribute id is same as of select attribute. Try by changing the label id. All HTML attributes must have unique id / name.
In Plain JavaScript, you get the selected option value as follow
var e = document.getElementById("tick");
var value = e.options[e.selectedIndex].value;
Hope this helps! :)

getElementById not returning anything or problem in script?

I'm making a program that returns value from input field, then changes string of field to x result depending condition. Would really appreciate help as members here have always greatly helped me in the past. Debugger is throwing this error and of course nothing is working:
script.js:22 Uncaught TypeError: Cannot set property 'innerHTML' of null
at uberChecker (script.js:22)
at HTMLButtonElement.onclick (index.html:25)
Here is my code (beginner here):
JS:
var username = document.getElementById("myUsername").value;
var groupIs = document.getElementById("myGroup").value;
var warnings = document.getElementById("myWarning").value;
var postCount = document.getElementById("myPostCount").value;
function uberChecker() {
if ((groupIs != ('Uber' || 'uber') && postCount > '1000') && warnings === '0') {
document.querySelector("output-box").innerHTML = "You can become Uber !";
} else if (postCount < '1000' && warnings === '0') {
document.querySelector("output-box").innerHTML = (username + ' You have ' + postCount + ' posts, you do not meet the requirements');
} else if (warnings != '0' && postCount > '1000') {
document.querySelector("output-box").innerHTML = (username + ' You cannot upgrade with ' + warnings + ' warning')
} else if (postCount < '1000' && warnings != '0') {
document.querySelector("output-box").innerHTML = (username + ' you have ' + postCount + ' posts which is less than 1000 and you have ' + warnings + '% warning. You cannot upgrade');
} else {
document.querySelector("output-box").innerHTML = (username + ' You are already Uber');
}
}
HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="blue-box"></div>
<input type="text" placeholder="Type username" id="myUsername" class="user" >
<input type="text" placeholder="Type user group" id="myGroup" class="group">
<input type="text" placeholder="Type post count" id="myPostCount" class="post">
<input type="text" placeholder="Type warning level" id="myWarning" class="warning">
<div class="UsernameText">Username</div>
<div class="groupText">Group</div>
<div class="postText">Posts</div>
<div class="warningText">Warning</div>
<button type="button" onclick="uberChecker();" class="black-box">Check if you are upgradeable</button>
<div class="output-box">Result will display here</div>
<script src="script.js"></script>
</body>
</html>
put a dot before the class name.
document.querySelector(".output-box").innerHTML = "You can become Uber !";
The problem is in this line
document.querySelector("output-box").innerHTML
querySelector function takes a selector
just change it to
document.querySelector(".output-box").innerHTML
And it will work
The problem are these statements: document.querySelector("output-box")
You are looking for an element here instead of a class. You need to add a dot (.) in front of the classname so that the querySelector works properly:
document.querySelector(".output-box")
Try following code, this will remove all error:
There are two issues in your code:
1 - You are declaring variables before creating input fields.
2 - You are using querySelector in wrong way.
Put js before end of body tag.
var username = document.getElementById("myUsername").value;
var groupIs = document.getElementById("myGroup").value;
var warnings = document.getElementById("myWarning").value;
var postCount = document.getElementById("myPostCount").value;
function uberChecker() {
if ((groupIs != ('Uber' || 'uber') && postCount > '1000') && warnings === '0') {
document.querySelector(".output-box").innerHTML = "You can become Uber !";
} else if (postCount < '1000' && warnings === '0') {
document.querySelector(".output-box").innerHTML = (username + ' You have ' + postCount + ' posts, you do not meet the requirements');
} else if (warnings != '0' && postCount > '1000') {
document.querySelector(".output-box").innerHTML = (username + ' You cannot upgrade with ' + warnings + ' warning')
} else if (postCount < '1000' && warnings != '0') {
document.querySelector(".output-box").innerHTML = (username + ' you have ' + postCount + ' posts which is less than 1000 and you have ' + warnings + '% warning. You cannot upgrade');
} else {
document.querySelector(".output-box").innerHTML = (username + ' You are already Uber');
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="blue-box"></div>
<input type="text" placeholder="Type username" id="myUsername" class="user">
<input type="text" placeholder="Type user group" id="myGroup" class="group">
<input type="text" placeholder="Type post count" id="myPostCount" class="post">
<input type="text" placeholder="Type warning level" id="myWarning" class="warning">
<div class="UsernameText">Username</div>
<div class="groupText">Group</div>
<div class="postText">Posts</div>
<div class="warningText">Warning</div>
<button type="button" onclick="uberChecker();" class="black-box">Check if you are upgradeable</button>
<div class="output-box">Result will display here</div>
<script src="script.js"></script>
</body>
</html>
Change selector condition from ("output-box") to (".output-box")

Validate user input with whitespace

How to in real-time format user input? For example, the user puts A9364470240ZGS001 to the input field, and using JavaScript format it in the input field in real-time to be like: A 936 447 02 40 ZGS 001?
<div class="childDumpFile">
<label for="ds">Dataset</label>
<input type="text" class="form-control" id="ds" name="ds" value="{{Request::get('ds') ?? ''}}">
</div>
I found the true answer. These expectations are naming as "input-mask" and if you'd like to use. You have to use 3. party libraries. Some of them listing in following sites:
Libraries 1
Libraries 2
I chose Cleave.js for your question. This is the demo:
<script src="https://nosir.github.io/cleave.js/dist/cleave.min.js"></script>
<script src="https://nosir.github.io/cleave.js/dist/cleave-phone.i18n.js"></script>
<script>
function loadFunction() {
// custom
var cleaveCustom = new Cleave('.input-custom', {
blocks: [1, 3, 3, 2, 2, 3, 3],
delimiter: ' ',
});
}
</script>
<body onload="loadFunction()">
A 936 447 02 40 ZGS 001
<div class="container">
<input class="input-custom" placeholder="Custom delimiter & blocks" />
</div>
</body>
If we suppose users have to write the characters one by one. This will work.
<body>
<input type="text" class="form-control" id="ds" name="ds" onkeypress="keyPress()" maxlength="23">
</body>
<script>
function keyPress() {
var field = document.getElementById("ds");
var text = field.value;
if(text.length == 1 || text.length == 5
|| text.length == 9 || text.length == 12
|| text.length == 15 || text.length == 19 ) {
var newText = text + " ";
field.value = newText;
}
}
</script>
Here is a little example.
<div class="childDumpFile">
<label for="ds">Dataset</label>
<input type="text" class="form-control" id="ds" name="ds">
</div>
<div class="test_ds"></div>
JS with jquery.
$("#ds").change(function(){
var ds_value = $("#ds").val();
var temp = ds_value;
temp = temp.substring(0,1) + " " + temp.substring(1, 4) + " " + temp.substring(4, 7) + " " + temp.substring(7, 9) + " " + temp.substring(9, 11) + " " + temp.substring(11, 14) + " " + temp.substring(14, 17);
$("#ds").val(temp);
$(".test_ds").html(temp);
});
Here is a demo -
https://jsfiddle.net/Kistlak/7bkdtev8
First, you need add onchange="getTimeNow()" oninput="getTimeNow()" in to input
<input type="text" class="form-control" id="ds" name="ds" value="{{Request::get('ds') ?? ''}}" onchange="getTimeNow()" oninput="getTimeNow()">
Finally, you get event input text
<script>function getTimeNow(){console.log(new Date())}</script>

new line in JS-function

I would like to get a longer string with line breaks, but it's not working with all the common commands like \n, \r\n, ... Also not with HTML-Tags for breaking a line.
I am new to the ASP-Framework and JS-Scripting and I can't find the solution on my own. Till now I didn't find the right hint on the internet, you can help me when you have a look at my specific code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>DataGen App</title>
</head>
<body>
<div>
<h3>Mitarbeiter</h3>
</div>
<div>
<input type="button" value="generateSQL" onclick="generate();" />
<p id="ma" />
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/mitarbeiter';
function formatItem(item) {
return 'INSERT INTO Mitarbeiter VALUES (' + item.Id + ', ' + item.Name + ', ' + item.Vorname + ', ' + item.Bereich + ');';
}
function generate() {
var str = "";
$.getJSON(uri)
.done(function (data) {
$.each(data, function (key, item) {
str = str + "\n" + formatItem(item);
$('#ma').text(str);
});
})
}
</script>
</body>
</html>
The line break should be generated in the last function.
Thank's a lot and have a nice week!
You can use <br> tag. The <br> tag inserts a single line break.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>DataGen App</title>
</head>
<body>
<div>
<h3>Mitarbeiter</h3>
</div>
<div>
<input type="button" value="generateSQL" onclick="generate();" />
<p id="ma" />
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/mitarbeiter';
function formatItem(item) {
return 'INSERT INTO Mitarbeiter VALUES (' + item.Id + ', ' + item.Name + ', ' + item.Vorname + ', ' + item.Bereich + ');';
}
function generate() {
var str = "";
$.getJSON(uri)
.done(function (data) {
console.log(data);
$.each(data, function (key, item) {
str = str + "<br>" + formatItem(item);
$('#ma').html(str);
});
})
}
</script>
</body>
</html>

JS Removing Labels Font Style - MVC3

I have a label which displays the number of characters used in a textbox. When the page first loads it looks fine as it is small and in italics. I am using Bootstrap for that styling.
<label id="lblCharactersRemaining"><small><em>0 Out Of 255 Characters</em></small></label>
My JavaScript checks and updates the text in this label with the number of characters a user enters, this also works fine.
The problem is that each time the JS activates the styling goes back to the default MVC type. How can I make sure that when the JS executes that it doesn't remove the Bootstrap styling?
My JS is:
<script type="text/javascript">
var maximumLength = '#System.Configuration.ConfigurationManager.AppSettings["MaximumTextBoxLength"]';
if (document.getElementById("ObjectTextBox")) {
var txtbox = document.getElementById("ObjectTextBox");
txtbox.onkeyup = function () { IsMaxLength(this); };
}
function IsMaxLength(objTxtCtrl) {
if (objTxtCtrl.getAttribute && objTxtCtrl.value.length > maximumLength) {
objTxtCtrl.value = objTxtCtrl.value.substring(0, maximumLength);
}
if (document.all) {
document.getElementById('lblCharactersRemaining').innerText = (objTxtCtrl.value.length) + ' Out Of ' + maximumLength + ' Characters';
}
else {
document.getElementById('lblCharactersRemaining').textContent = (objTxtCtrl.value.length) + ' Out Of ' + maximumLength + ' Characters';
}
if (objTxtCtrl.value.length == 0) {
document.getElementById('lblCharactersRemaining').textContent = '0 Out Of ' + maximumLength;
}
}
</script>
Try :
function IsMaxLength(objTxtCtrl) {
if (objTxtCtrl.getAttribute && objTxtCtrl.value.length > maximumLength) {
objTxtCtrl.value = objTxtCtrl.value.substring(0, maximumLength);
}
if (document.all) {
$('#lblCharactersRemaining').html('<small><em>' + objTxtCtrl.value.length + ' Out Of ' + maximumLength + ' Characters</em></small>');
}
else {
$('#lblCharactersRemaining').html('<small><em>' + objTxtCtrl.value.length + ' Out Of ' + maximumLength + ' Characters</em></small>');
}
if (objTxtCtrl.value.length == 0) {
$('#lblCharactersRemaining').html('<small><em>0 Out Of ' + maximumLength + '</em></small>');
}
}
Every time you launch the function, it deleted the tags 'small' and 'em', so just add them...
UPDATE : PS : Using Jquery language...
UPDATE AFTER COMMENT :
BOOTPLY : http://bootply.com/106485
CODE :
JS :
$('button.jquery').on('click', function(){
$('#lblCharactersRemaining').html('<small><em>0 Out Of 85200</em></small>');
});
$('button.nojquery').on('click', function(){
document.getElementById('lblCharactersRemaining').innerHTML = '<small><em>0 Out Of 666</em></small>';
});
HTML :
<label id="lblCharactersRemaining"><small><em>0 Out Of 255 Characters</em></small></label>
<button class="jquery">Change label with jquery</button>
<button class="nojquery">Change label without jquery syntax</button>

Categories