I'm writing a code where users can input any text and choose any letter to see how many times it occurred in that particular text - I'm not sure where I'm going wrong
function textOccurrences() {
var inputField1 = (document.getElementById("inputField1").value);
var inputField2 = (document.getElementById("inputField2").value);
var count = 0;
for (i = 0; i < length; i++) {
if (parseInt(search) != -1) {
count++;
var search = inputField1.indexOf(inputField2, parseInt(search) + 1);
}
document.getElementId("answer").value = inputField2 + "Occurs" + count + "times";
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> Text Occurrences </title>
<h1> Number of Character Occurrences</h1>
<script="text/javascript"> </script>
</head>
<body>
<form>
<p>Enter text: </p>
<p> <input id="inputField1" type="text" /> </p>
<p>Enter any character:</p>
<p> <input id="inputField2" type="text" /> </p>
<input type="button" value="Search" onlick="textOccurrences()" />
</p>
<p>Number of Occurrences:</p>
<p><textarea id="answer"></textarea></p>
</form>
</body>
</html>
Try this as your function.
function textOccurrences() {
var inputField1 = (document.getElementById("inputField1").value);
var inputField2 = (document.getElementById("inputField2").value);
var count = inputField1.split(inputField2).length - 1;
document.getElementId("answer").value = inputField2 + "Occurs" + count + "times";
}
You can use a regular expression:
function textOccurrences() {
var inputField1 = (document.getElementById("inputField1").value);
var inputField2 = (document.getElementById("inputField2").value);
var re = new RegExp(inputField2, "g");
var count = inputField1.match(re).length;
document.getElementById("answer").value = inputField2 + " Occurs " + count + " times";
}
Note that in your code, you have said getElementId instead of getElementById, also contributing to the error.
function textOccurrences() {
var inputField1 = (document.getElementById("inputField1").value);
var inputField2 = (document.getElementById("inputField2").value);
var reg = new RegExp(inputField2,'g');
document.getElementById("answer").value = inputField2 + "Occurs" + inputField1.match(reg).length +
"times";
}
You can try something like this
you can use regex to match any occurence of you chosen letter and then count those matches and you have to syntax errors in your html and javascript
-it is onclick NOT onlick
-and it is getElementById NOT getElementId
here is you code after editing
Javascript
function textOccurrences() {
var inputField1 = (document.getElementById("inputField1").value);
var inputField2 = (document.getElementById("inputField2").value);
console.log("hekasdlkjasd");
var re = new RegExp(inputField2, "g");
var count = inputField1.match(re).length;
document.getElementById("answer").value = inputField2 + " Occurs " + count + " times";
}
Html
<!DOCTYPE html>
<html>
<head>
<title> Text Occurrences </title>
<h1> Number of Character Occurrences</h1>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<form>
<p>Enter text: </p>
<p> <input id="inputField1" type="text" /> </p>
<p>Enter any character:</p>
<p> <input id="inputField2" type="text" /> </p>
<input type="button" value="Search" onclick="textOccurrences();" />
</p>
<p>Number of Occurrences:</p>
<p><textarea id="answer"></textarea></p>
</form>
</body>
</html>
Related
How do i loop through an array and display user input with indexes without the user input replicating?
Current output i'm getting:
Feedback 1
123456
Feedback 2
123456
The expected output for the case below should be:
Feedback 1
123
Feedback 2
456
<!DOCTYPE html>
<html>
<head>
<script src="script.js" type="text/javascript"> </script>
</head>
<body>
<h2>Feedback Form</h2><br>
<form>
Enter Feedback : <textarea rows="3" cols="20" id="feedback"></textarea><br><br>
<input type="button" value="Submit Feedback" id="create" onclick="addFeedback()"><br><br>
<input type="button" value="View Feedback" id="view" onclick="displayFeedback()"><br><br>
</form>
<div id="result"></div>
</body>
</html>
var myArray = [];
var myFeedback = document.getElementById("feedback");
var displayBox = document.getElementById("result");
function addFeedback(){
//Store feedback into array
myArray.push(myFeedback.value);
//Clear textbox
myFeedback.value = "";
//Display message
displayBox.innerHTML = "Successfully Added Feedback Details!";
}
function displayFeedback(){
displayBox.innerHTML = "";
for(var i = 0; i < myArray.length; i++){
displayBox.innerHTML += "Feedback " + (i+1) + "<br/>" + myArray.join();
}
}
Use myArray[i] instead of join. Or more modern approach:
let innerHTML = "<ul>";
myArray.forEach((value, index) => {
innerHTML += `<li>Feedback ${index+1}: <br /> ${value}</li>`;
});
innerHTML += "</ul>";
displayBox.innerHTML = innerHTML;
I put my JavaScript inside tags instead of externally(because external files weren't working) and for some reason my code is not running.
Just to be sure that it wasn't a problem with the code itself, I put a simple alert before all the code and nothing popped up.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Fahrenheit/Kelvin Converter</h1>
<div id = "first" class = "oneof">
<h2>Kelvin to Fahrenheit</h2>
<input type = "text" placeholder = "Enter Kelvin here" id = "kinput">
<button id = "ksubmit">Submit Kelvin</button><br><br>
<textarea id = "fpopup" rows = "5" cols = "50"></textarea>
</div>
<div id = "second" class = "oneof">
<h2>Fahrenheit to Kelvin</h2>
<input type = "text" placeholder = "Enter Fahrenheit here" id = "finput">
<button id = "fsubmit">Submit Fahrenheit</button><br><br>
<textarea id = "kpopup" rows = "5" cols = "50"></textarea>
</div>
<script>
alert("Hello World"); //Testing JS
if(6==6){
alert("ua");
}
function ftok(f){
k = (f − 32) * 5/9 + 273.15;
return k;
}
function ktof(k){
f = (K − 273.15) * 9/5 + 32;
return f;
}
document.getElementById("ksubmit").onclick = function() {
document.getElementById("fpopup").value = document.getElementById("kinput").value + " degrees Kelvin is " + ktof(Number(document.getElementById("kinput").value)) + " degrees Fahrenheit"
}
document.getElementById("fsubmit").onclick = function() {
document.getElementById("kpopup").value = document.getElementById("finput").value + " degrees Fahrenheit is " + ftok(Number(document.getElementById("finput").value)) + " degrees Kelvin"
}
</script>
</body>
</html>
You can use DOMContentLoaded function to make sure the HTML is ready and parsed properly. Also you have some syntax errors which i have fixed as well.
Also, You were using some weird minus and multiplication characters.
The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed
Your code is now working as expected.
Live Demo:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Fahrenheit/Kelvin Converter</h1>
<div id="first" class="oneof">
<h2>Kelvin to Fahrenheit</h2>
<input type="text" placeholder="Enter Kelvin here" id="kinput">
<button id="ksubmit">Submit Kelvin</button><br><br>
<textarea id="fpopup" rows="5" cols="50"></textarea>
</div>
<div id="second" class="oneof">
<h2>Fahrenheit to Kelvin</h2>
<input type="text" placeholder="Enter Fahrenheit here" id="finput">
<button id="fsubmit">Submit Fahrenheit</button><br><br>
<textarea id="kpopup" rows="5" cols="50"></textarea>
</div>
<script>
window.addEventListener('DOMContentLoaded', (event) => {
if (6 == 6) {
alert("ua");
}
function ftok(f) {
var k = (f - 32) * 5 / 9 + 273.15;
return k;
}
function ktof(k) {
var f = (k - 273.15) * 9 / 5 + 32;
return f;
}
document.getElementById("ksubmit").onclick = function() {
document.getElementById("fpopup").value = document.getElementById("kinput").value + " degrees Kelvin is " + ktof(Number(document.getElementById("kinput").value)) + " degrees Fahrenheit"
}
document.getElementById("fsubmit").onclick = function() {
document.getElementById("kpopup").value = document.getElementById("finput").value + " degrees Fahrenheit is " + ftok(Number(document.getElementById("finput").value)) + " degrees Kelvin"
}
})
</script>
</body>
</html>
When the user clicks the button to show all values in the array, how can I get it to add up the total of all 'amounts due'? For example, if one user enters $5, another enters $10 and another enters $25, the total would be displayed as $40.
// Code goes here
var customerarray = [];
function displaydata() {
var innerTemphtml = ' ';
for (var i = 0; i < customerarray.length; i++) {
innerTemphtml += customerarray[i].customerName + " " + customerarray[i].customerID + " " + customerarray[i].AmountDue;
}
document.getElementById('output').innerHTML = innerTemphtml;
}
function addtoarray() {
customerarray.push({
customerName: document.getElementById('custName').value,
customerID: document.getElementById('CustID').value,
AmountDue: document.getElementById('Amount').value
});
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<span>Customer Name: </span>
<input type="text" id='custName'/><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID'/><br><br>
<span>Amount: </span>
<input type="text" id='Amount'/> <br><br>
<button onClick="addtoarray();" class="button" type = "button">add to array</button>
<button onClick="displaydata()" class="button" type = "button"> Display data</button>
<p id="output"></p>
</body>
</html>
I have changed your code as per your requirement as shown below.Hopefully it will solve your problem
// Code goes here
var customerarray = [];
function displaydata() {
var total=0;
var innerTemphtml = ' ';
for (var i = 0; i < customerarray.length; i++) {
innerTemphtml += customerarray[i].customerName + " " + customerarray[i].customerID + " " + customerarray[i].AmountDue+"<br/>";
total+=parseInt(customerarray[i].AmountDue);
}
document.getElementById('output').innerHTML ="User Input Data <br/>" +innerTemphtml;
document.getElementById('total').innerHTML = "Grand Total = "+total;
}
function addtoarray() {
customerarray.push({
customerName: document.getElementById('custName').value,
customerID: document.getElementById('CustID').value,
AmountDue: document.getElementById('Amount').value
});
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<span>Customer Name: </span>
<input type="text" id='custName'/><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID'/><br><br>
<span>Amount: </span>
<input type="text" id='Amount'/> <br><br>
<button onClick="addtoarray();" class="button" type = "button">add to array</button>
<button onClick="displaydata()" class="button" type = "button"> Display data</button>
<p id="output"></p>
<p id="total"></p>
</body>
</html>
There are mutliple things you have to look. I have added a display due() for you.
And here is my js fiddle https://jsfiddle.net/jinspeter/1qxo50uz/
You have to user a number field for Amount. And also addding the amount has to parsed to Int to reject string.
<body>
<span>Customer Name: </span>
<input type="text" id='custName'/><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID'/><br><br>
<span>Amount: </span>
<input type="number" id='Amount'/> <br><br>
<button onClick="addtoarray();" class="button" type = "button">add to array</button>
<button onClick="displaydata()" class="button" type = "button"> Display data</button>
<button onClick="displayTotalDue()" class="button" type = "button"> Display Due</button>
<p id="output"></p>
</body>
var customerarray = [];
function displaydata() {
var innerTemphtml = ' ';
for (var i = 0; i < customerarray.length; i++) {
innerTemphtml += customerarray[i].customerName + " " + customerarray[i].customerID + " " + customerarray[i].AmountDue;
}
document.getElementById('output').innerHTML = innerTemphtml;
}
function displayTotalDue(){
var total =0;
customerarray.forEach(function(item){
total = total + item.AmountDue
});
var innerTemphtml = 'totalDue=' + total;
document.getElementById('output').innerHTML = innerTemphtml;
}
function addtoarray() {
customerarray.push({
customerName: document.getElementById('custName').value,
customerID: document.getElementById('CustID').value,
AmountDue: parseInt(document.getElementById('Amount').value)
});
console.log(customerarray);
}
I try to fix your code. To make it more easy to read. I put the displaydata() method inside of the addtoarray() method, so you can see the results after adding an element in the customers array. Also, I replaced the for with a forEach and added a new div for the total.
I create a node that is a p tag, which will contain the name, id and amount. This tag then will be added to the outputLabel for each element in the array. You can optimize this by just adding the additional node and not running the entire array to print the output.
// Code goes here
var customers = [];
var outputLabel = document.getElementById('output');
var totalLabel = document.getElementById('total');
var total = 0;
outputLabel.innerHTML = '<p>Customers</p>';
totalLabel.innerHTML = 'Total: 0';
function displaydata() {
outputLabel.innerHTML = '<p>Customers</p>';;
total = 0;
customers.forEach(function(customer) {
var node = document.createElement('p');
node.innerHTML = customer.customerName + ', ' +
customer.customerID + ', ' +
customer.AmountDue;
total += parseInt(customer.AmountDue);
outputLabel.appendChild(node);
});
totalLabel.innerHTML = 'Total: ' + total;
}
function addtoarray() {
customers.push({
customerName: document.getElementById('custName').value,
customerID: document.getElementById('CustID').value,
AmountDue: document.getElementById('Amount').value
});
displaydata();
}
<span>Customer Name: </span>
<input type="text" id='custName' /><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID' /><br><br>
<span>Amount: </span>
<input type="text" id='Amount' /> <br><br>
<button onClick="addtoarray();" class="button" type="button">Add to array</button>
<div id="output"></div>
<div id="total"></div>
Optimized version: for this version I moved the node (p tag) to the addtoarray() method and I capture the data from the inputs. Then I calculate the total. With this two values a call the displaydata(). This method save time running the array each time you want to print the added element.
// Code goes here
var customers = [];
var outputLabel = document.getElementById('output');
var totalLabel = document.getElementById('total');
var total = 0;
outputLabel.innerHTML = '<p>Customers</p>';
totalLabel.innerHTML = 'Total: 0';
function displaydata(node, total) {
outputLabel.appendChild(node);
totalLabel.innerHTML = 'Total: ' + total;
}
function addtoarray() {
var customerName = document.getElementById('custName').value;
var customerID = document.getElementById('CustID').value;
var amountDue = document.getElementById('Amount').value;
customers.push({
customerName: customerName,
customerID: customerID,
amountDue: amountDue
});
var node = document.createElement('p');
node.innerHTML = customerName + ', ' + customerID + ', ' + amountDue;
total += parseInt(amountDue);
displaydata(node, total);
}
<span>Customer Name: </span>
<input type="text" id='custName' /><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID' /><br><br>
<span>Amount: </span>
<input type="text" id='Amount' /> <br><br>
<button onClick="addtoarray();" class="button" type="button">Add to array</button>
<div id="output"></div>
<div id="total"></div>
Set "AmountDue" property of object to number instead of string at .push() call
Number(document.getElementById('Amount').value)
use Array.prototype.reduce() to add two elements of array at a time, return sum
let dues = customerarray.reduce((a, {AmountDue:b}) => a + b, 0);
Our company has a client that requires a specific checksum on their bar codes. I've come up with the following which allows the user to enter the distributor part number, our part number and our serial number. Right now, when you click save, it will calculate correctly for the bar code with the checksum. NOW, we have added a quantity box so that we can print x number of barcodes with our serial number incrementing by 1. (i.e. 1st serial number is 000001, next will be 000002 and so on). What I've been trying to do for the last week is alter this code so the user can input the part numbers and sn, and it will calculate each bar code up to the quantity.
This is what we would like to have:
If user enters part numbers, first serial number and quantity then clicks "Save" this should be the result. At present, this can only be achieved by entering each serial number and clicking save
*note: while the quantity can be entered, the actual value has not been used in my code...yet
So, to achieve this, I need to find a way to increment the serial numbers without dropping off the leading zeros but maintaining the length of qty.length.
I also need to figure out how to loop each new serial number through with part numbers to get the correct checksum for the bar code. After a week of staring at this, I'm hoping some fresh and experienced eyes can assist. Here is my code.
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Capture Form Fields to CSV</title>
<script type="text/javascript">
<!--
function saveValues() {
var frm = document.form1;
var str = frm.text1.value + frm.text2.value + frm.text3.value;
var dpn = frm.text1.value;
var wpn = frm.text2.value;
var wsn = frm.text3.value;
var strArray = str.split("");
var calcArray = strArray;
var total =0;
for (var i = 0; i < str.length; i++)
strArray[i] = strArray[i].charCodeAt(0);
for (var i = 0; i < strArray.length; i++){
if (strArray[i] >= 65 && strArray[i] <= 90){
calcArray[i] = (strArray[i] - 64) * (i+1)
}
else if (strArray[i] >=97 && strArray[i] <=122) {
calcArray[i] = (strArray[i] - 96) * (i+1)
}
else if (strArray[i] >=48 && strArray[i] <=57) {
calcArray[i] = (strArray[i] - 48) * (i+1)
}
else {
calcArray[i] = 1 * (i+1)
}
}
for (var i in calcArray){
total += calcArray[i];}
var mod2 = str.length - (2*(Math.floor(str.length/2)));
var mod10 = (total + mod2) - (10*(Math.floor((total + mod2)/10))) ;
var chk = mod10;
var record = ""
+ dpn + "," + wpn + "," + wsn + "," +dpn + "~" + wpn + "~" + wsn + "~" + chk + "\n";
frm.textarea1.value += record;
}
function clearText() {
document.form1.textarea1.value = "";P
form1.text1.value = "";
form1.text2.value = "";
form1.text3.value = "";
}
function csvSave() {
var a = document.createElement('a');
with (a) {
href='data:text/csv;base64,' + btoa(document.getElementById('textarea1').value);
download='csvfile.csv';
}
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
//-->
</script>
</head>
<body>
<h1>Capture Form Fields to CSV</h1>
<form name="form1" >
<p>
Distributor Part Number: <input name="text1" type="text" value="GDM1301" /><br />
Our Part Number: <input name="text2" type="text" value="PCBDM160"/><br />
Our Serial Number: <input name="text3" type="text" value="000001"/><br />
Label Quantity: <input name="qty" type="text" value="3"/>
</p>
<p>
<input name="save" type="button" value="Save"
onclick="saveValues(); return false"/>
<input name="clear" type="button" value="Clear"
onclick="clearText(); return false"/>
<button onclick="csvSave()">CSV</button>
</p>
<p>
<i>Click 'Save' to add content</i><br />
<textarea id="textarea1" cols="80" rows="20"></textarea>
</p>
</form>
</body>
</html>
i have following code
<html>
<script type="text/javascript">
function writeit()
{
var tbox = document.getElementById('a_tbox_1');
if (tbox)
{
tbox.value = '';
}
tbox = document.getElementById('a_tbox_2');
if (tbox)
{
tbox.value = '';
}
}
</script>
<form name="a_form">
Product name:
<input type="text" id="a_tbox_1" name="a_tbox" value="" />
price : <input type="text" id="a_tbox_2" name="a_tbox" value="" />
<input type="button" name="btn" value="write it" onclick="writeit()" />
</form>
</html>
main idea of program is that i should give me possibilites to write two value product name and price and click after write ii it should write these informations in some text how to do it?please help
function writeit()
{
var strValue = '';
var tbox = document.getElementById('a_tbox_1');
if (tbox)
{
//tbox.value = '';
// add:
strValue = 'name: ' + tbox.value;
}
if(strValue != '')
strValue += ', ';
tbox = document.getElementById('a_tbox_2');
if (tbox)
{
//tbox.value = '';
// add:
strValue += 'price: ' + tbox.value + ' € :)';
}
alert(strValue);
// or do whatever you want with it...
}
Your questin is not clear, but try the code below and see if its what you are looking for:
<html>
<head>
<title></title>
<script type="text/javascript">
function writeit() {
var tbox = document.getElementById('a_tbox_1'), tbox2 = document.getElementById('a_tbox_2');
if (tbox.value && tbox2.value){
alert('product = ' + tbox.value + " :: price = " + tbox2.value);
// sendData('action.php?product=' + tbox.value + '&price=' + tbox2.value); (you can send your data via ajax)
tbox.value = '';
tbox2.value = '';
return false;
}
}
</script>
</head>
<body>
<form name="a_form">
Product name: <input type="text" id="a_tbox_1" name="a_tbox" value="" />
Price : <input type="text" id="a_tbox_2" name="a_tbox" value="" />
<input type="button" name="btn" value="write it" onclick="writeit()" />
</form>
</body>
</html>