So the problem here is I need an alert box with my provided code in it to show up. I have tried a lot and it is still not showing what I want it to. I will also provide a picture of what I am looking to re-create.
Here is my code:
function sumOfNumbers() {
var theNumber = document.getElementById("txtNumber").value;
if (theNumber > 0) {
var theSum = 0;
for (var i = 1; i <= theNumber; i++) {
theSum += i;
}
alert(
"The sum of all the numbers from 1 to " + theNumber + " is " + theSum + ""
);
} else {
alert("negative " + theNumber);
}
}
<input type='text' id='txtNumber'>
<input type="button" value='Calculate Sum' onclick="sumOfNumbers()"/>
For some reason, my HTML tags on the top aren't showing. Here is what the box is supposed to look like:
When I click on the "calculate sum" button, nothing will even show. Any help is greatly appreciated!
I've slightly altered your code to use an eventListener rather than an inline click handler. Your code had a few syntax errors (missing closing braces, misplaced else) that were causing the issues. I always find it helpful to use consoleLog when trying to debug, which is how I found those bugs.
let btn = document.querySelector('.btn');
btn.addEventListener('click', sumOfNumbers);
function sumOfNumbers() {
var theNumber = (document.getElementById("txtNumber").value);
if (theNumber > 0) {
var theSum = 0;
for (var i = 1; i <= theNumber; i++) {
theSum += i;
}
alert('The sum of all the numbers from 1 to ' + theNumber + ' is ' + theSum + '');
} else {
alert(`invalid input. ${theNumber} is a negative number`);
}
}
<input type='text' id='txtNumber'>
<button type="button" class="btn">Calculate</button>
You can create an N array using [ ...Array(theNumber).keys() ] and then loop through and add like so
const sumOfNumbers = () => {
const theNumber = document.querySelector("#txtNumber").value;
if(isNaN(theNumber) || (+theNumber < 0))
{
return alert(`Not valid or negative number ${theNumber}`);
}
var numArray = [ ...Array(+theNumber).keys() ];
let sum = 0;
for(let i = 0; i < numArray.length; i++)
{
let num = i + 1;
sum += num;
}
alert(`The sum of all numbers from 1 to ${theNumber} is ${sum}`);
}
<input type='text' id='txtNumber'>
<input type="button" value='Calculate Sum' onclick="sumOfNumbers()"/>
function doGetWord(){
var word = F.gword.value;
var wLength = word.length;
for(var i = 0; i < wLength; i++){
document.getElementById("dword").innerHTML += "_ "
}
}
This is a function that will write _ in a div in html, and what I want is to change them if the user types the corresponding input, for example if the first letter is supposed to be "a" then it would change the first _ to "a".
This is what I got so far:
function doGuessWord(){
dummy = F.t.value
if(dummy.length > 1){
dummy = ""
F.t.value = ""
}
for(var x = 0; x < wLength; x++){
if (substr(x, wLength) == dummy ) {
document.getElementById("dword").innerHTML += "_ "
}
else{
document.getElementById("dword").innerHTML += "dummy "
}
}
}
Could you help me out with this one?
Thanks in Advance!!
Something like this?
https://jsfiddle.net/9z66968a/3/
You will have to adapt it a bit. But you should be able to take the parseText function and pass it the params you need to return the text to insert where ever you want
There you go. I believe this is what you wanted. Feel free if you don't understand something
https://jsfiddle.net/vhsf8gpp/2/
var dashArr = [];
var dummyWord = document.getElementById('dummy');
var input = document.querySelector('input');
var counter = 0;
for(let i= 0; i<10;i++)
{
dashArr.push('_');
}
function WriteContent()
{
dummyWord.textContent = dashArr.map(d=>d).join(''); // This gets rid of the ',' inbetween the dashes
}
WriteContent();
//var charArr = [];
document.querySelector('input').addEventListener('keyup',function(){
var inputString = input.value;
dashArr[counter] = inputString.charAt(inputString.length - 1);
WriteContent();
counter++;
})
I used this post for reference.
I went through a lot of questions and couldn't solve my problem.
I need to match a number of special characters, but only once.
HTML:
<form class="FillIn Rearrange">
<input data-correctanswer="ça" type="text">,
<input data-correctanswer="ça" type="text">
<input data-correctanswer="vé" type="text">
<input data-correctanswer="bién" type="text">
</form>
This JS currently returns ALL ç, and é, but I need 1 max. of each:
var buttons = '';
$('.FillIn input').each(function () {
var corrAns = $(this).attr('data-correctanswer');
for (var i = 0; i < corrAns.length; i++) {
if (corrAns[i].match(/[éç]/g)) {
buttons += '<button>' + corrAns[i] + '</button>';
}
}
});
fiddle
Currently returns ççéé (all occurrences)
Need it to return çé (one of each).
Need a scalable solution, i.e. .match(/[éçdfga]/g) (or any extra letter)
Here's how you can do it:
var buttons = '';
function createButtons(lettersToMatch){
$('.FillIn input').each(function () {
var corrAns = $(this).attr('data-correctanswer');
for (var i = 0; i < corrAns.length; i++) {
var match = corrAns[i].match(new RegExp(lettersToMatch));
if (match) {
buttons += '<button>' + corrAns[i] + '</button>';
lettersToMatch = lettersToMatch.replace(match[0], "");
}
}
});
}
//Testing
createButtons("[éèçêïë]");
$("body").append( buttons );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="FillIn Rearrange">
<input data-correctanswer="çaï" type="text">,
<input data-correctanswer="ça" type="text">
<input data-correctanswer="vé" type="text">
<input data-correctanswer="bién" type="text">
</form>
It looks like you want to end the for loop as soon as you get a match, so throw in a break statement:
var buttons = '';
$('.FillIn input').each(function () {
var corrAns = $(this).attr('data-correctanswer');
for (var i = 0; i < corrAns.length; i++) {
if (corrAns[i].match(/[éç]/g)) {
buttons += '<button>' + corrAns[i] + '</button>';
break;
}
}
});
You simply need to remember what you have already found and not process it:
var buttons = '';
var found = []; // this remembers what we have already found
$('.FillIn input').each(function () {
var corrAns = $(this).attr('data-correctanswer');
for (var i = 0; i < corrAns.length; i++) {
var m; // hold the match
if (m = corrAns[i].match(/[éç]/)) {
// not found yet
if(found.indexOf(m[0]) == -1) {
found.push(m[0]) // remember it's been found
buttons += '<button>' + corrAns[i] + '</button>';
}
}
}
});
I am attempting to create an online solver for the maximum subarray problem.
https://en.wikipedia.org/wiki/Maximum_subarray_problem
I planned on taking user-input numbers from a textbox and converting them into an int array in JS, however my JS does not seem to be running at all.
Here is my HTML
<!DOCTYPE html>
<html>
<head>
<title> findMaxSum </title>
<script src="findMaxSum.js" type="text/javascript"></script>
</head>
<body>
<h1> findMaxSum </h1>
<form id="formarray" action="">
<p> Enter numbers with spaces, i.e. "1 2 3 4 5": </p>
<input type="text" id="array"> <br>
<button id="sum">findMaxSum!</button>
<br>
</form>
<p id="answer">The answer is: </p>
</body>
</html>
and my JS. note: the map(function(item)) part of the code is intended to break apart the string from the form into an int array.
"use strict";
function findMaxSum() {
var array = document.getElementById("array").split(" ").map(function(item) {
return parseInt(item, 10);
});
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
var loopSum = 0;
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
loopSum += array[i];
if (currentMax < loopSum) {
currentMax = loopSum;
} else if (loopSum < 0) {
loopSum = 0;
}
}
document.getElementById("answer").innerHTML = "The answer is: " + currentMax;
}
window.onload = findMaxSum;
Currently, when I type in numbers into the textbox and submit, the numbers disappear and nothing happens. Any help is greatly appreciated.
Your array variable is object. You have to split the value of <input type="text" id="array"> not the object element.
var array = document.getElementById("array");
array = array.value.split(" ").map(function (item) {
return parseInt(item, 10);
});
Or simpler:
var array = document.getElementById("array").value.split(" ").map(function (item) {
return parseInt(item, 10);
});
Change your code -
function findMaxSum() {
var array = document.getElementById("array").value.split(" ").map(function(item) {
return parseInt(item, 10);
});
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
var loopSum = 0;
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
loopSum += array[i];
if (currentMax < loopSum) {
currentMax = loopSum;
} else if (loopSum < 0) {
loopSum = 0;
}
}
document.getElementById("answer").innerHTML = "The answer is: " + currentMax;
}
window.onload = findMaxSum;
Problem is you are using button inside form, which is by default of type submit type, that is the reason why the page goes blank, it gets submitted. So either you don't use form tag or make the button as button type.
<button id="sum" type='button'>findMaxSum!</button> <!-- type attribute added -->
Below is the sample updated code, hope it helps you.
"use strict";
function findMaxSum() {
var array = document.getElementById("array").value.split(/\s/);
var max = Math.max.apply(Math, array);
document.getElementById("answer").innerHTML = "The answer is: " + max;
}
window.onload = function() {
document.getElementById("sum").onclick = findMaxSum;
};
<h1> findMaxSum </h1>
<form id="formarray" action="">
<p>Enter numbers with spaces, i.e. "1 2 3 4 5":</p>
<input type="text" id="array">
<br>
<button id="sum" type='button'>findMaxSum!</button>
<br>
</form>
<p id="answer">The answer is:</p>
To achieve the solution of the problem, you need to make following changes.
Update the event binding place
window.onload = function() {
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
};
function findMaxSum() {
// remove the update binding code from here
// logic should come here
}
Resolve a JS error
document.getElementById("array").value.split(" ")
Update the html to avoid page refresh (add type)
<button id="sum" type='button'>findMaxSum!</button>
Update the logic to address the problem
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
var counter = i+1;
while (counter < array.length) {
var loopSum = array[i];
for (var j = (i+1); j <= counter; j++) {
loopSum += array[j];
if(loopSum > currentMax) {
currentMax = loopSum;
}
}
counter++;
}
}
Here is a plunker - http://plnkr.co/edit/AoPANUgKY5gbYYWUT1KJ?p=preview
No this isn't a duplicate because all of the answers are different in other posts.
Does anyone know how to get replace something specific in a string? for example I'm trying to get rid of ALL commas that area together. Keep single commas but get rid of two only
For example:
w,h,o,,w,h,a,t,w,h,e,n,w,h,e,r,e,,t,h,e,n,,c,a,n,,b,u,t,,
I want to get rid of all instances where the double commas appear. Something kind of like:
var example = text.replace(/,,/g,' '); /*Space where ' ' is*/
If you understand what I mean. The next step is:
var text.replace(/,/g,'');
Thank you!
Code:
<html>
<head>
<script>
function decrypt() {
var input = document.getElementById("input").value;
var x = input.split(",");
var txtDisp="";
for(var i = 0; i < x.length; i++) {
if(x[i].type = "text") {
crack = 94-(x[i]-32)+32;
toTxt = String.fromCharCode(this, crack);
txtDisp = txtDisp+","+toTxt;
prep = txtDisp.replace(/,,/g,"");
}
document.getElementById("prompt").innerHTML=prep;
}
}
</script>
</head>
<body>
<textarea rows='4' cols='100' style='resize:none;' id='input'></textarea>
<br>
<input type='button' value='execute' onclick='decrypt()' />
<p id='prompt'>
</p>
</body>
</html>
P.s. this code is already posted somewhere else where I asked a question.
Why don't you do:
var text = "61,59,44,47,43,43, ,39,54,37, ,37,47,41,44, ,59,61,48, ,53,48,42,47, ,42,54,57,53,44, ,47,56,42,57,48, ,47,56,56, ,43,61,53,58, ,47,41,44, ,42,39,61,43, ,43,53,48,59,57, ,42,54,57,44,57, ,61,48,58, ,39,47,41,50,58";
example = text.split(",,").join("").split(", ,").join("");
the result is:
"w,h,ow,h,a,t,w,h,e,n,w,h,e,r,et,h,e,nc,a,nb,u,t"
I myself also tried to do it like:
example = text.replace(/,,/g,'').replace(/, ,/g,'');
the result was:
"w,h,ow,h,a,t,w,h,e,n,w,h,e,r,et,h,e,nc,a,nb,u,t"
I changed your code like this:
function decrypt() {
var val = document.getElementById("input").value;
var x = val.split(",");
var txtDisp = "";
for (var i = 0; i < x.length; i++) {
if (!isNaN(parseInt(x[i]))) {
var num = parseInt(x[i]);
crack = 94 - (num - 32) + 32;
toTxt = String.fromCharCode(this, crack);
txtDisp = txtDisp + "," + toTxt;
prep = txtDisp.replace(/,,/g, "").replace(/, ,/g, "");
}
document.getElementById("prompt").innerHTML = prep;
}
}
and it works. check this DEMO out.
Try this:
function decrypt() {
var input = document.getElementById("input").value;
var x = input.split(",");
var txtDisp = "";
for (var i = 0; i < x.length; i++) {
if (x[i] !== ' ') {
crack = 94 - (x[i] - 32) + 32;
toTxt = String.fromCharCode(this, crack);
txtDisp += "," + toTxt;
} else {
txtDisp += " ";
}
}
document.getElementById("prompt").innerHTML = txtDisp.replace(/,/g, "");
}