This is my problem, hope get some support for this.
This is my function.
function show(n,q)
{
for(j=1;j<=n;j++)
{
s=j.toString().length;
t=0;
for(i=s-1;i>=0;i--)
{
t+=Math.pow((Math.floor(j/Math.pow(10,i))%10),q);
}
if(t==j){document.write(t+ " ");}
else{document.write("");}
}
}
show(1000,3);
With two inputs: number n and the exponent q it will solve all the numbers smaller than n which the sum of all the q-exponented of its digits is equal to itself.
For example: q=3, n=200, we have the number 153 because: 1^3 + 5^3 + 3^3 = 153
This function is OK, but due to my bad javascript skill, I dont know how to create a form alowing to enter n and q into 2 boxes, then click button "Show" we have results in the third box.
I have tried this below code, but it does not work :(
<input id='number' type='text' />
<input id='exp' type='text' />
<button onclick='javascript:show()'>Show</button>
<div id='res' style='width:100%;height:200px'></div>
<script>
function show() {
var n=document.getElementById('number').value,
var q=document.getElementById('exp').value,
out=document.getElementById('res'),
out.innerHTML="";
for(j=1;j<=n;j++)
{
s=j.toString().length;
t=0;
for(i=s-1;i>=0;i--)
{
t+=Math.pow((Math.floor(j/Math.pow(10,i))%10),q);
}
if(t==j){
out.innerHTML+=t+ " ";
}
else{
out.innerHTML+="";
}
}
}
</script>
In additon, I want to do it myself, could you guys tell me where i can find guide for this problem.
Thanks.
Your code has some punctuation issues.
Try to replace:
var n=document.getElementById('number').value,
var q=document.getElementById('exp').value,
out=document.getElementById('res'),
out.innerHTML="";
by
var n=document.getElementById('number').value,
q=document.getElementById('exp').value,
out=document.getElementById('res');
out.innerHTML="";
The code looks fine and will do what you are trying to do. Just there are some , (Comma) instead of ; (Semi-colon) in your code. Change them and then try.
Check the solution here.
http://jsfiddle.net/JszG2/
var n=document.getElementById('number').value;
var q=document.getElementById('exp').value;
out=document.getElementById('res');
Below is solution using JQuery....
<script>
function show() {
var num = parseInt($('#number').val());
var exp = parseInt($('#exp').val());
out = $('#res');
var num = document.getElementById('number').value;
var exp = document.getElementById('exp').value;
out = document.getElementById('res');
out.innerHTML = "";
for (p = 1; p <= num; p++) {
q = p.toString().length;
v = 0;
for (i = q - 1; i >= 0; i--) {
v = v+ Math.pow((Math.floor(p / Math.pow(10, i)) % 10), exp);
}
if (v == p) {
out.innerHTML += v + " ";
}
else {
out.innerHTML += "";
}
}
}
</script>
Related
I am practicing creating a function that loops whatever number I put into the input into a times table. I used a for loop to achieve this but I ran into an issue. My for loop only runs one time and it only get my input * 10 for some reason. Can someone please help. Thank you.
function myFunction() {
var inputNumber = document.querySelector(".input-field").value;
inputNumber = parseInt(inputNumber);
if (isNaN(inputNumber) || inputNumber == "" || inputNumber == null) {
document.querySelector(".output h1").innerHTML = "Please enter a number!";
} else {
for (i = 1; i <= 10; i++) {
let product = inputNumber * i;
document.querySelector(".output").innerHTML = "<br>" + inputNumber + " * " + i + " = " + product + "<br>";
}
}
}
Looks like you update the HTML on every iteration. However, I think you want to expand the innerHTML to include all elements?
I would look into creating html elements in javascripts and adding them in html like this (draft, untested):
const element = document.createElement("div")
for (let i = 1; i < 10; i++) {
let product = inputNumer * i;
element.appendChild(document.createTextNode(`${inputNumer} ${product}`);
}
Please study this. It is using recommended event listener and a map
const arr = [...Array(11).keys()].slice(1); // numbers from 1 to 10
const h1 = document.querySelector("#output h1"),
result = document.getElementById("result"),
inputField = document.getElementById("inputField");
inputField.addEventListener("input", function() {
const inputNumber = +this.value;
console.log(inputNumber)
h1.classList.toggle("hide", inputNumber); // keep hide if ok number
result.innerHTML = inputNumber ? arr.map(i => `${inputNumber} * ${i} = ${inputNumber*i}`).join(`<br/>`) : "";
});
.hide {
display: none;
}
<input type="number" id="inputField" class=".input-field" />
<hr/>
<div id="output">
<h1 class="error hide">Please enter a number!</h1>
<div id="result">
</div>
</div>
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>
Is there a function that splits the the given string into 2 evenly and place half of each to different textboxes?
I have tried var.split and var.slice
<script>
function display()
{
var myStr = document.getElementbyId("reqnum").value;
var strArray = myStr.split(" ");
// Display array values on page
for(var i = 0; i < strArray.length; i++){
document.write("<p>" + strArray[i] + "</p>");
}
}
the expected should split the no. evenly and would display an error if the numbers are odd.
You can check the length of your input string. If it is odd then display an error.
<input type="text" id="reqnum" >
<input type="button" value="Display" onclick="display()">
<script>
function display()
{
var myStr = document.getElementById("reqnum").value;
if( !myStr || myStr.length % 2 == 1){
document.write("<p>Invalid input</p>");
}else{
var a = parseInt(myStr.substring(0, myStr.length/2));
var b = parseInt(myStr.substring(myStr.length/2, myStr.length));
document.write("<p>" + a + "</p>");
document.write("<p>" + b + "</p>");
document.write("<p> Result after multiplication : " + (a*b) + "</p>");
}
}
</script>
you can convert the numbers to string and then you can do the following.
var num = "1234567890"
var num1
var num2
if (num.length % 2 == 0) {
num1 = num.slice(0, (num.length / 2))
num2 = num.slice((num.length / 2))
} else {
console.log("Number contains odd number of digits")
}
console.log("Num1 " + num1 + " and Num2 " + num2)
use the Slice method, documentation is here.
For your slicing in half:
let half1, half2;
if( myStr.length % 2 == 0 ){
half1 = myStr.slice(0, (myStr.length / 2));
half2 = myStr.slice( (myStr.length / 2), myStr.length );
} else {
// error code
}
function splitToEqual(num){
num = num.toString()
return [num.substring(0, num.length / 2), num.substring(num.length / 2, num.length)]
}
console.log(splitToEqual(1234567890))
Have you tried using slice and length String methods?
Ie.
const string = '1234567890';
const length = string.length;
const res1 = string.slice(0,length/2);
const res2 = string.slice(length/2);
console.log(res1,res2);
Based on your request, I created the following piece of code :-)
Hope it helps.
var inputBox, warning, fBox, sBox;
function inputBoxChanged(e) {
var text = e.currentTarget.value;
if (text.length % 2 != 0) {
warning.innerText = "Value needs to be even sized";
fBox.value = "";
sBox.value = "";
} else {
warning.innerText = "";
var splitPos = text.length / 2;
fBox.value = text.slice(0, splitPos);
sBox.value = text.slice(splitPos, text.length);
}
}
document.addEventListener("DOMContentLoaded", function (e) {
inputBox = document.getElementById("input");
warning = document.getElementById("warning");
fBox = document.getElementById("first");
sBox = document.getElementById("second");
inputBox.addEventListener("change", inputBoxChanged);
});
<html>
<body>
<input id="input" type="text"/>
<span id="warning"></span>
<hr/>
<input id="first" type="text" readonly/>
<input id="second" type="text"readonly/>
</body>
</html>
Use substring() function as
var substring=string.substring(strating_index,end_index);
index will start from 0
var str="1234567890"
var substr=str.substring(0,str.length/2);
var substr2=str.substring(strlength/2,strlength);
$("#ID1").val(substr);
$('#ID2').val(substr2);
I have managed to dynamically display the sum of 6 line-cost DOM elements from a php file. Unfortunately, when trying to calculate the delivery charge, my JavaScript methods regarding to the deliveryCharge implementation fails to display anything on the page. With the sub-total methods working and displaying perfectly, I tried to troubleshoot the problem by providing innerHTML with a constant value of both a string and an int- both times yielded nothing to be displayed on screen.
I have displayed both the working part of the sub-total calculation method as well as the non-working part of the delivery-charge calculation. Would the problem lie within an incorrect way of using innerHTML, be a calculation error or a different error entirely?
function calcST(){
var i;
var sum = 0; // initialize the sum
let p = document.getElementsByTagName("line_cost");
for (i = 0; i < p.length; i++) {
if (!isNaN(Number(p[i].innerHTML))) {
sum = Number(sum + Number(p[i].innerHTML)); // p[i].innerHTML gives you the value
}
}
setST(sum, "sub_total");
}
function setST(sum, item_id){
let i = document.getElementById(item_id);
i.innerHTML = sum;
calcDelivCharge();
}
function getST() {
let i = document.getElementById("sub_total");
let v = i.innerHTML;
return v;
}
function calcDelivCharge(){
var delCharge;
var e = getST();
if(e < 100){
delcharge = e*0.10
}else{
delcharge = 0;
}
setDelivCharge("delivery_charge", delCharge);
}
function setDelivCharge(item_id, delCharge){
let i = document.getElementById(item_id);
i.innerHTML = delCharge;
calculateTAX();
}
function getDelivCharge() {
let i = document.getElementById("delivery_charge");
let v = i.innerHTML;
return v;
}
I managed to find that the DOM was not ready loading before the getST() method was called. This can be fixed with the following code:
if(document.getElementById("sub_total") != null){
let i = document.getElementById("sub_total");
let v = i.innerHTML;
return v;
}
Unfortunately, delivery-charge is seen as 'unidentified'. Why does this appear when the getST() method is altered?
Well, if you're HTML is like
<line_cost>
<div>30</div>
<div>40</div>
...
</line_cost>
You can do this:
function calcSubtotal() {
const costs = document.querySelector("line_cost").children;
let sum = 0;
for( let i = 0 ; i < costs.length ; i ++) {
sum += parseInt(costs[i].innerHTML);
}
setST(sum, "sub_total");
}
// Subtotal getter and setter
function setST(sum, item_id) {
document.getElementById(item_id).innerHTML = sum.toFixed(2);
calcDeliveryCharge();
}
function getSubTotal() {
return document.getElementById("sub_total").innerHTML;
}
function calcDeliveryCharge() {
const subTotal = getSubTotal();
setDeliveryCharge("delivery_charge", subTotal < 100 ? subTotal * 0.10 : 0);
}
function setDeliveryCharge(item_id, deliveryCharge){
document.getElementById(item_id).innerHTML = deliveryCharge.toFixed(2);
//calculateTAX();
}
function getDeliveryCharge() {
return document.getElementById("delivery_charge").innerHTML;
}
calcSubtotal();
calcDeliveryCharge();
<line_cost>
<div>5</div>
<div>4</div>
<div>3</div>
<div>20</div>
</line_cost>
<br/>
<div>
<span>Sub Total: $
<span id="sub_total"></span>
</span>
<br/>
<span>Delivery Charge: $
<span id="delivery_charge"></span>
</span>
</div>
Otherwise, if you have:
<div>
<line_cost>30</line_cost>
<line_cost>40</line_cost>
...
</div>
Then do this:
function calcSubtotal() {
const costs = document.querySelectorAll("line_cost");
let sum = 0
for( let i = 0 ; i < costs.length ; i ++) {
sum += parseFloat(costs[i].innerHTML);
}
setST(sum, "sub_total");
}
// Subtotal getter and setter
function setST(sum, item_id) {
document.getElementById(item_id).innerHTML = sum.toFixed(2);
calcDeliveryCharge();
}
function getSubTotal() {
return document.getElementById("sub_total").innerHTML;
}
function calcDeliveryCharge() {
const subTotal = getSubTotal();
setDeliveryCharge("delivery_charge", subTotal < 100 ? subTotal * 0.10 : 0);
}
function setDeliveryCharge(item_id, deliveryCharge){
document.getElementById(item_id).innerHTML = deliveryCharge.toFixed(2);
//calculateTAX();
}
function getDeliveryCharge() {
return document.getElementById("delivery_charge").innerHTML;
}
calcSubtotal();
calcDeliveryCharge();
line_cost {
display: block;
}
<div>
<line_cost>25</line_cost>
<line_cost>34</line_cost>
<line_cost>43</line_cost>
<line_cost>250</line_cost>
</div>
<br/>
<div>
<span>Sub Total: $
<span id="sub_total"></span>
</span>
<br/>
<span>Delivery Charge: $
<span id="delivery_charge"></span>
</span>
</div>
enter image description here
How can I convert each alternate character of a string lowercase to uppercase and string uppercase to lowercase in Jquery?
You can check if the character of the string is uppercase by comparing the ASCII code. If it's between 65 & 90, the character is in uppercase.
Then by applying toUpperCase & toLowerCase methods will transform uppercase alphabets into lowercase and vice-versa.
function isUpperCase(c) {
return c >= 65 && c <= 90;
}
var string = "AaBbCcDd *+-";
var updatedString = string.split("").map(c => isUpperCase(c.charCodeAt(0)) ? c.toLowerCase() : c.toUpperCase()).join("");
console.log("Original String:: " + string);
console.log("Transformed String:: " + updatedString);
You can use this code alternate character
function alternate(changeString) {
var charArray = changeString.toLowerCase().split("");
for (var i = 1; i < charArray.length; i += 2) {
charArray[i] = charArray[i].toUpperCase();
}
return charArray.join("");
};
var text = "Test";
console.log(alternate(text));
For the transformation, you can use the following:
function isLowerCase(character) {
return "abcdefghijklmnopqrstuvwxyz".indexOf(character) >= 0;
}
function convertChar(character) {
return isLowerCase(character) ? character.toUpperCase() : character.toLowerCase();
}
function convert(str) {
var result = "";
for(var i = 0; i < str.length; i++) {
result += convertChar(str[i]);
}
}
A complete example here: (although it isn't exact the same that is in your pic)
function isLowerCase(character) {
return "abcdefghijklmnopqrstuvwxyz".indexOf(character) >= 0;
}
function convertChar(character) {
return isLowerCase(character) ? character.toUpperCase() : character.toLowerCase();
}
function convert(str) {
var result = "";
for(var i = 0; i < str.length; i++) {
result += convertChar(str[i]);
}
return result;
}
$('#text').on('input', function(){
$('#display').val(convert(this.value));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>input</label><input id="text" />
<label>display</label><input id="display" disabled />
Please refer below code may be it will help you,
Keyup event will work each character
$(document).ready(function(){
var upperCase= new RegExp('[A-Z]');
var lowerCase= new RegExp('[a-z]');
$("#text").keyup(function(){
var l =this.value.length;
var s =this.value;
var r =new Array();
for(var i=0;i<l;i++){
if(upperCase.test(s[i])){
r.push(s[i].toString().toLowerCase());
}
if(lowerCase.test(s[i])){
r.push(s[i].toString().toUpperCase());
}
}
$("#res").val(r.toString().replace(/\,/g, '').trim());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text">
<br>
Result:<input type="text" id="res">