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>';
}
}
}
});
Related
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()"/>
var currentmix = document.getElementById('custommix').value.split(",");
var additionalprice = 0;
for (i = 0; i < currentmix.length; i++) {
if (currentmix[i] != "") {
var mixinpriceid = "mixinprice"+currentmix[i];
additionalprice += parseFloat(document.getElementById(mixinpriceid).value));
}
}
This code is not working :(
I know the expression
parseFloat(document.getElementById(mixinpriceid).value)
is giving me the right number on each iteration of the loop
But it is not affecting the variable "additionalprice" outside the for loop. Any ways to do this???????
There's a additional parentheses in this statement, please check
additionalprice += parseFloat(document.getElementById(mixinpriceid).value));
Sathish is correct, you have an extra parenthesis. This snippet will show the code will work without it.
var currentmix = "12345";
var additionalprice = 0;
for (i = 0; i < currentmix.length; i++) {
if (currentmix[i] != "") {
var mixinpriceid = "mixinprice" + currentmix[i];
additionalprice += parseFloat(document.getElementById(mixinpriceid).value);
console.log(additionalprice);
}
}
console.log("Final Value: " + additionalprice);
<input id="mixinprice1" value="100">mixinprice1</input>
<input id="mixinprice2" value="200">mixinprice2</input>
<input id="mixinprice3" value="300">mixinprice3</input>
<input id="mixinprice4" value="400">mixinprice4</input>
<input id="mixinprice5" value="500">mixinprice5</input>
i have a textbox1 which input by user and textbox2 for user to input numbers which can automatically generate textbox1 value into multiple string such as example below:
Txtbox1 = ABC12345
Txtbox2 = 3
Result will be
ABC12345-1
ABC12345-2
ABC12345-3
You can try using something like this below, but kinda hard to make it 100% as you want, since you haven't shown any HTML.
$("[id^=Txbox]").keyup(function() {
var empty = $("[id^=Txbox]").filter(function() {
return $.trim($(this).val()).length == 0
}).length == 0;
if (empty) {
var str = $("#Txbox1").val();
var number = $("#Txbox2").val();
var arr = [];
for (i = 0; i < number; i++) {
arr.push(str + "-" + i)
}
console.log(arr)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="Txbox1" />
<input id="Txbox2" type="number" />
You can just use button and apply click event.
function getString() {
var finalString = [];
var t = $("#textbox1").val()
var n = $("#textbox2").val();
if (t.toString().trim() != "") {
for (i = 0; i < n; i++) {
finalString.push(t + "-" + (i + 1))
}
}
console.log(finalString)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Text : <input type="text" id="textbox1"><br><br> Number : <input type="text" id="textbox2">
<button type="button" onClick="getString()" id="textbox1">Get</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
I have the function below. It gets the values from checked boxes and transfer it to a textbox. It is working... but only if the form has 2 or more checkboxes.
<script type="text/javascript">
function sendValue()
{
var all_values = '';
boxes = document.DataRequest.itens.length
for (i = 0; i < boxes; i++)
{
if (document.DataRequest.itens[i].checked)
{
all_values = all_values + document.DataRequest.itens[i].value + ","
}
}
window.opener.document.getElementById('emailto').value = all_values;
self.close();
}
</script>
<form name="DataRequest">
<input name="itens" type="checkbox" value="name1">
<input name="itens" type="checkbox" value="name2">
</form>
Am I missing something to make this work with only 1 checkbox?
When there is one item. it does not return array
function sendValue()
{
var all_values = '';
boxes = document.DataRequest.itens.length
if(boxes>1)
{
for (i = 0; i < boxes; i++)
{
if (document.DataRequest.itens[i].checked)
{
all_values = all_values + document.DataRequest.itens[i].value + ","
}
}
}
else
{
if (document.DataRequest.itens.checked)
{
all_values = document.DataRequest.itens.value
}
}
window.opener.document.getElementById('emailto').value = all_values;
self.close();
}
First, you need to give different names to your inputs :
<form name="DataRequest">
<input name="item1" type="checkbox" value="name1">
<input name="item2" type="checkbox" value="name2">
</form>
Using the same name to your inputs is technically possible in your case but a terrible practice as the name is normally what's identify for a form the different inputs.
Then, to access your inputs, you must use a different syntax. More than one version are possible but you can do this :
var boxes = document.forms['DataRequest'].getElementsByTagName('input');
var tokens = [];
for (var i=0; i<boxes.length; i++) {
if (boxes[i].checked) tokens.push(boxes[i].name+'='+boxes[i].value);
}
var all_values = tokens.join(',');
Note that the use of join avoids the trailing comma.
not sure how much compatibility you need with IE 6 - 8, but if that's not required you can use
function serializeChecked() {
var values = [];
var checked_boxes = document.querySelectorAll('form[name="DataRequest"] input[checked]');
for (var i = 0, l = checked_boxes.length; i < l; i++) {
values.push(checked_boxes[i].getAtrribute('value'))
}
return values.join(',');
}
function sendValue() {
window.opener.document.getElementById('emailto').value = serializeChecked();
}
If you do require IE support, use document.DataRequest.getElementsByTagName('input') instead of QSA and iterate through them to collect the values if they have the checked attribute.