Can someone assist me in streamlining a few parts of my JavaScript code

I have written some pretty complicated JavaScript code to dynamically create multiple input fields and dropdown boxes based on a number entered by the user in a text field.
Here's a basic overview: the script checks if a number is being used, then determines whether it is less than five, and finally identifies which specific number it is. I then duplicated the text field and corresponding operations based on the identified number. Clearly, my JavaScript skills (and grammar) need some work.
Here is the code snippet:

function calculator() {
var boxNumber = document.getElementById('boxNumber').value;
var boxInt = parseInt(boxNumber);
var limit = new Number(5);

if (Math.floor(boxInt) == boxInt) {

    if (boxInt <= limit) {

        x = boxInt;

        if (x == 5){

            document.getElementById('opSpace').innerHTML = "<br /><input /><p></p><select><option>Add</option><option>Sub</option><option>Mul</option><option>Div</option></select><br /><input /><p></p><select><option>Add</option><option>Sub</option><option>Mul</option><option>Div</option></select><br /><input /><p></p><select><option>Add</option><option>Sub</option><option>Mul</option><option>Div</option></select><br /><input /><p></p><select><option>Add</option><option>Sub</option><option>Mul</option><option>Div</option></select>"

        }

        else {

            if (x == 4) {

                document.getElementById('opSpace').innerHTML = "<br /><input /><p></p><select><option>Add</option><option>Sub</option><option>Mul</option><option>Div</option></select><br /><input /><p></p><select><option>Add</option><option>Sub</option><option>Mul</option><option>Div</option></select><br /><input /><p></p><select><option>Add</option><option>Sub</option><option>Mul</option><option>Div</option></select><br /><input /><p></p><select><option>Add</option><option>Sub</option><option>Mul</option><option>Div</option></select>"

            }

            else {

                if (x == 3) {

                    document.getElementById('opSpace').innerHTML = "<br /><input /><p></p><select><option>Add</option><option>Sub</option><option>Mul</option><option>Div</option></select><br /><input /><p></p><select><option>Add</option><option>Sub</option><option>Mul</option><option>Div</option></select><br /><input /><p></p><select><option>Add</option><option>Sub</option><option>Mul</option><option>Div</option></select>"

            }

                else {

                    if (x == 2) {

                        document.getElementById('opSpace').innerHTML = "<br /><input /><p></p><select><option>Add</option><option>Sub</option><option>Mul</option><option>Div</option></select><br /><input /><p></p><select><option>Add</option><option>Sub</option><option>Mul</option><option>Div</option></select>"

                    }

                    else {

                    if (x == 1) {

                        document.getElementById('opSpace').innerHTML = "<br /><input /><p></p><select><option>Add</option><option>Sub</option><option>Mul</option><option>Div</option></select>"

                    }

                    else {

                        alert("Please enter a positive number")

                    }
                    }

                }

            }

        }

    }

    else {
    alert("Please enter a number less than 5")
    }
}

else {
    alert("Invalid entry. Please enter a valid number.")
}
}

This code serves as the foundation for a calculator where the text fields determine the numbers to operate on and the drop-down menus define the operations to perform. Any assistance or guidance would be greatly appreciated.

Answer №1

let simpleCalculator = () => {
    let numInput = document.getElementById('numInput').value;
    let parsedNum = parseInt(numInput, 10);
    let maxLimit = 5;

    if (Math.floor(parsedNum) === parsedNum) {
        if (parsedNum <= maxLimit && parsedNum > 0) {
            let outputHtml = '';
            for (let index = 0; index < parsedNum; index++) {
                outputHtml += "<br /><input /><p></p><select><option>Add</option><option>Sub</option><option>Mul</option><option>Div</option></select>";
            }
            document.getElementById('operationSpace').innerHTML = outputHtml;
        } else {
            alert("Please enter a positive number within the limit");
        }
    } else {
        alert("Enter an integer less than or equal to 5");
    }
}

Answer №2

function createCalculator() {
    var userInput = document.getElementById('userInput').value;
    var parsedInt = Math.floor( parseInt(userInput, 10) );
    var maxLimit = 5;
    var htmlContent = '<br /><input /><p></p><select><option>Add</option><option>Sub</option><option>Mul</option><option>Div</option></select>';

    function repeatString(str, num) {
        return new Array(num + 1).join(str);
    }

    if ( !isNaN(parsedInt) && parsedInt <= maxLimit && parsedInt > 0 ) {
        document.getElementById('operationSpace').innerHTML = repeatString( htmlContent, parsedInt );
    } else if (parsedInt < 0) {
        alert('Please use a number between 0 and ' + maxLimit);
    }
}

Answer №3

Something similar to this:

if(y>threshold)
{
     ... display error message...
}
else if(y<= 0)
{
     ... display error message...
}
else
{
    var element = document.getElementById('outputArea');
    element.innerHTML = '';
    for(var j = 0; j<y; j++)
    {
        element.innerHTML += "<br /><input /><p></p><select><option>Add</option><option>Sub</option><option>Mul</option><option>Div</option></select>";
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enforce a limit of two decimal places on input fields using jQuery

Looking to limit an input field so that users can only enter numbers with a maximum of two decimals. Is it possible to achieve this using jQuery? Any way I could utilize the jQuery toFixed() function for this purpose? Thank you in advance! ...

Making an ajax request to update the value of a specific key in an object

I am currently working with a firebase database that contains multiple collections. Using the code provided, I have managed to successfully retrieve an array that consists of all attractions with an area_id that matches the area_id of e.target. However, t ...

Why is the Mongoose ObjectID causing issues when used as a parameter in a function?

Attempted passing a Mongoose ObjectID to a function using an onclick(). Below is the shortened code snippet: <a onclick="Like({{_id}}, {{likes}}, {{dislikes}});" class="btn btn-like"></a> <p id="{{_id}}"> {{likes}} likes </p> < ...

Setting a displacement/normal map for only one face of a cylinder

My current setup involves creating a cylinder using the following code: var geometry = new THREE.CylinderGeometry( 50, 50, 2, 128 ); The resulting shape is a flat cylinder resembling a coin. However, when I apply a displacementMap and normalMap, I notice ...

Is it possible to pause code execution using async await?

As an experiment to understand async/await, I implemented the init function in a convoluted manner: function init() { console.log(1) accountsStore.getAccounts().then(() => { categoriesStore.getCategories().then(() => { she ...

Avoid clicking in areas outside the perimeter of the blue circle in the SVG

Is there a way to restrict clicking outside the blue circle? The goal is to only allow opening by clicking on the svg itself, This includes everything, even white space inside the svg. How can this be achieved in the code? The current behavior is that ...

What is the method for HTML inline handlers to retrieve the global window object and the variables contained within it?

During my coding test, I encountered an interesting scenario. I had a function called write and used a button with an inline onclick handler to trigger the write() function. function write(text) { alert(text) } <button onclick='write("Some tex ...

Check the test library to confirm that the aria-expanded value is set to false

I need assistance with testing a flyout component using test-library to verify the aria-expanded attribute value. After clicking on a flyoutItem, I want to ensure that the value of aria-expanded is set to false. Is there a more efficient way for me to ac ...

Disable automatic matrix updates for all meshes in the 3D scene using Three.js

In my current project, I am working with a scene that includes multiple OBJ meshes and I am looking to deactivate matrixAutoUpdate for all of them. These OBJ objects are comprised of numerous child meshes, making it challenging for me to figure out how t ...

Is there a way to prevent continuous repetition of JavaScript animated text?

I'm working on a code that displays letters and words one by one, but I can't figure out how to stop it from repeating. Can someone help me with this? <div id="changeText"></div> <script type="text/javascript"> var te ...

Automated scrolling in Chrome is ineffective without initial manual scrolling

In order to create a smooth user experience for mobile users when the side-drawer menu is open, I have implemented overflow: hidden and height: 100vh on the App container (excluding the drawer) to prevent scrolling while the drawer is visible. Typically, ...

Should the autonomous function be halted upon user interaction?

I am working on a carousel that automatically runs, but I also want it to reset its timer if a user interacts with the controls. The current setup does work to some extent, but when interacting with the control-dot, the timer is not reset which leads to un ...

Learn the process of adjusting opacity for a specific color in CSS

At the moment, this is the code I'm using to apply a color to an element using jss. const styleSheet = theme => ({ root: { backgroundColor: theme.colors.red, }, }) I am interested in finding out if there is a way to add opacity based o ...

Arrange the array of days and months in JavaScript

Attempting to rearrange a date Array from newest to oldest has proven challenging as the list.sort function only rearranges based on the initial number. The Array in question is as follows: var MyArray = ["13 Jun", "09 Jun", "25 Aug", "30 Jun", "13 Aug"]; ...

`Modified regions determined by cursor location`

I am working with a split layout featuring two columns, and I need the ability to make each column separately scrollable. Due to using a specialized scroll-to function, I cannot use overflow-y: scroll; or overflow: auto;. I am looking for alternative solut ...

Javascript tree structures that enable the drag-and-drop of multiple items

At the moment, our application utilizes the ExtJS tree view. We now have a need for users to be able to select multiple nodes (which the tree view already supports through a pluggable selection model) and then drag these selections to another section of th ...

Divide a PDF document into individual files using QR code identifiers

I need assistance with organizing a scanned pdf that includes multiple answer scripts from students for a specific exam. Each student's answer script ends with a qrcode that serves as a unique identifier for the student. Is there a way to divide the ...

Looking to implement a star rating feature in Vue.js 2?

My perspective is as follows : <div class="col-md-8"> ... <star-rating :value="3"></star-rating> ... </div> This is how my star-rating component looks like : <template> <span class="rating"> &l ...

Exploring the spinning globe using ThreeJS

Is there a way to rotate an object in three-dimensional space using THREEJs? I've been trying the code below but it doesn't seem to work. Can anyone spot what I might be doing incorrectly? object.matrixAutoUpdate = false; const matrix = object ...

Tips for transmitting media stream from Angular code to Facemesh.js

Is there a way for me to replace the camera function and pass my own mediastream from another angular module? Src: const customMediaStream = getCustomMediaStream(); // Some function to get custom media stream const camera = new Camera(videoElement, { on ...