To effectively store the input values from eight labels into an array and subsequently identify the prime numbers within the array using JavaScript, follow these step-by-step instructions

As a newcomer to JavaScript, I am trying to extract the values of 8 labels (text) and store them in an array of 8 numbers. My goal is to then identify the prime numbers within this array. While I have been able to create the array and display the labels in the HTML, I am struggling with transferring the values to the array. Any assistance on this matter would be greatly appreciated. Thank you!

The code for my solver button:

$('#btn1').click(function () {
    var primes = [true, true, true, true, true, true, true, true];

    var limit = Math.sqrt(8);

    for (var i = 1; i < 8; i++) {
        if (primes[i] === true) {
            for (var j = i * i; j < 8; j += i) {
                primes[j] = false;
            }
        }
    }

    for (var i = 1; i < 8; i++) {
        if (primes[i] === true) {
            console.log(i + " " + primes[i]);
        }
    }

});

The code for the labels:

<label>1. </label> <input id="input1" type="text"><br>
<label>2. </label> <input id="input2" type="text"><br>
<label>3. </label> <input id="input3" type="text"><br>
<label>4. </label> <input id="input4" type="text"><br>
<label>5. </label> <input id="input5" type="text"><br>
<label>6. </label> <input id="input6" type="text"><br>
<label>7. </label> <input id="input7" type="text"><br>
<label>8. </label> <input id="input8" type="text"><br>

Answer №1

Code snippet to determine if a number is prime (source: ):

function checkPrime(num) {

   // If num is less than 2 or not an integer, it cannot be prime.
   if (num < 2) {return false}
   if (num != Math.round(num)) {return false}

   var isPrime = true;

   for (var i = 2; i <= Math.sqrt(num); i++) {
      if (num % i == 0) {isPrime = false}
   }

   return isPrime;
}

Code for clicking the solver button:

$('#btn1').click(function () {
    var limit = 8;   
    var primesData = {}; 

    for (var i = 1; i < limit; i++) {
        var inputValue = $('#input'+i).val(); 
        inputValue = parseInt(inputValue); 

        primesData[i] = {};
        primesData[i].value = inputValue;
        primesData[i].isPrime = isNaN(inputValue) ? false : checkPrime(inputValue);

        $('#result'+i).text(primesData[i].isPrime ? 'Prime' : 'Not Prime');
    }

    console.dir(primesData); 
    $('#container2').html(JSON.stringify(primesData)); 
});

The code for the labels (updated):

<label>1. </label> <input id="input1" type="text"><span id="result1"></span><br>
<label>2. </label> <input id="input2" type="text"><span id="result2"></span><br>
<label>3. </label> <input id="input3" type="text"><span id="result3"></span><br>
<label>4. </label> <input id="input4" type="text"><span id="result4"></span><br>
<label>5. </label> <input id="input5" type="text"><span id="result5"></span><br>
<label>6. </label> <input id="input6" type="text"><span id="result6"></span><br>
<label>7. </label> <input id="input7" type="text"><span id="result7"></span><br>
<label>8. </label> <input id="input8" type="text"><span id="result8"></span><br>

To display the output neatly:

var outputString = '<pre>';
for (var index in primesData) {
    outputString += primesData[index].value + ': ' + primesData[index].isPrime + "\n";
}
outputString += '</pre>';
$('#container2').html(outputString);

Answer №2

Instead of creating an array and looping through each element, you can simplify the process by designing a function to determine if the given label is a prime number or not. If it turns out to be a prime number, update the HTML accordingly. The PHP code snippet provided below demonstrates this concept, but the same logic applies to Javascript as well.

function is_prime($number)
{
    if ($number==1)
        return false;
    if ($number==2)
        return true;
    $sqrt = sqrt($number);
    $floor = floor($sqrt);
    for ($i=2 ; $i <= $floor ; $i++)
    {
        if ($number % $i == 0)
        {
            return false;
        }
    }
    return true;
}
$start = 1;
$labels = 8;
for($i = 1; $i <= $labels; $i++)
{
    if(is_prime($i))
    {
        echo '<label>'.$i.'. </label>'.'<input id="input'. $i.'" type="text" value=" '. $i .'">'.'<br>';
    }
}

// output

2. 2
3. 3
5. 5
7. 7

Feel free to adapt this method to suit your needs!

Answer №3

Here is the HTML code I have:

  <script>
    $(document).ready(function(){

        $('#btn1').click(function () {
            var count = 8;   // may need adjusting later
            var primes = {}; // using object instead of array

            for (var i = 1; i < count; i++) {
                var value = $('#input'+i).val(); // get input value
                value = parseInt(value); // convert from string to integer

                primes.i.value = value;
                primes.i.isPrime = isNaN(value) ? false : isPrime(value);
                $('#result'+i).text(primes.i.isPrime ? 'Prime' : 'Not Prime');
                }
        $('#container2').html(primes); // display output in console
        });

        function isPrime(n) {

        if (n < 2) {return false} // prime numbers cannot be less than 2
        if (n != Math.round(n)) {return false} // must be an integer
        var isPrime = true;

        for (var i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0) {isPrime = false}
        }

        return isPrime;
        }

    });
</script>      
</head>

<body>
    <center><h2>Prime Numbers Calculator.</h2><br></center>
    <div class="well">
        <div class="container" id="container1">
            <div class="col-md-4">
                <label>1. </label> <input id="input1" type="text"><span id="result1"></span><br>
                <label>2. </label> <input id="input2" type="text"><span id="result2"></span><br>
                <label>3. </label> <input id="input3" type="text"><span id="result3"></span><br>
                <label>4. </label> <input id="input4" type="text"><span id="result4"></span><br>
                <label>5. </label> <input id="input5" type="text"><span id="result5"></span><br>
		<label>6. </label> <input id="input6" type="text"><span id="result6"></span><br>
                <label>7. </label> <input id="input7" type="text"><span id="result7"></span><br>
                <label>8. </label> <input id="input8" type="text"><span id="result8"></span><br>
            </div>
        <div class="col-md-4">
            <div class="container" id="container2">

            </div>
        </div>
        <div class="col-md-4">
            <div class="container" id="container3">

            </div>
        </div>
        </div>
    </div>
        <center><button id="btn1" class="btn btn-primary"> Calculate</button>
        <button id="btn2" class="btn btn-primary"> Show Results</button>
        <button id="btn3" class="btn btn-primary"> Sort</button>
        <button id="btn4" class="btn btn-primary"> Clear Input</button></center>
</body>

Having trouble displaying results in a different container, need some help with that.

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

Are there any ways to pass an onClick function to a controller in React?

To prevent duplicate numbers from being generated, I added a button that, when clicked by a user, displays a message indicating that the value is being saved to avoid duplicates. However, when attempting to handle this on the server side controller, I enco ...

Displaying column values in Vuetify Table based on a condition

https://i.stack.imgur.com/wK9uU.png I'm working with a Vuetify table that has a column for URLs. I need to implement logic to display either the URL or the URL Group name based on properties in my rules array. If rules[i].urlGroup is not empty, then ...

Tips for executing forEach on a promise?

I am currently working with a function that returns a promise of an array: async function functionReturningPromiseOfUserIDs(): Promise<string[]> My question is, can I use the forEach method on the array returned by this function? async function runF ...

Having trouble serving static files with express.Router?

With my file system becoming more complex, I decided to switch from using app.use(express.static()) to utilizing express.Router(). Initially, I thought I could just replace app.use(express.static()) with router.use(express.static()), but unfortunately, thi ...

Filter out elements with identical dates from a JSONArray

One of the tasks I have is to sort a JSONArray that contains JSONObject data. The structure of the JSON looks like this: [ { "id": 582, "isTransaction": false, "toDate": "2015-08-26 16:12:00.0", "fromDate": "2015-08-24 15:11:00.0", " ...

What is the best way to apply custom styles in reactJs to toggle the visibility of Google Maps?

There are three radio buttons that correspond to school, restaurant, and store. Clicking on each button should display nearby locations of the selected type. Displaying Google Map and nearby places individually works fine without any issues. class Propert ...

Internet Explorer causing trouble with reliable Ajax dropdown selection

There are two drop-down lists on my website, where the options in one depend on the selection in the other. The Ajax code works perfectly fine in Chrome and Mozilla, but it's not functioning correctly in Internet Explorer (specifically IE9). I need so ...

Managing user access and permissions using JavaScript on the front end

I find myself in a situation where I am working on developing a single page application: The majority of the operations rely on ajax requests. Depending on the user's login status (admin, regular user, visitor), different components need to be displ ...

Leveraging the power of a JavaScript framework within the script tag

Hello there! I'm just starting out with vue.js and exploring different JavaScript frameworks. Recently, I came across an interesting example based on the documentation. import modal from 'vue-semantic-modal' export default { components ...

AngularUi Mobile Modal List Display

I attempted to implement the code from 32400236/dynamically-generate-modals-with-mobileangularui but encountered issues. I also tried using the following: <div class="access-item" ng-repeat="item in items track by $index"> <a ui-turn-on="$index" ...

Avoid reloading the page when submitting a form using @using Html.BeginForm in ASP.NET MVC

I have a webpage featuring a model that needs to be sent to the controller along with additional files that are not part of the model. I have been able to successfully submit everything, but since this is being done in a partial view, I would like to send ...

The Socket IO Client is receiving a different object than the one that was sent by the Server

My server side code is sending an object to the client side, but the object received by the client is completely different from what was sent. Let me elaborate: Code Server side code: //Setting up the example var response={}; response.models=[]; respo ...

filling out a form with data retrieved through an ajax request

After retrieving JSON data from an MVC controller, I am attempting to populate a form with this data but encountering difficulties. The returned data consists of only one row with three properties. Despite confirming that the data is being returned success ...

Upon clicking the 'Add Image' button, TINYMCE dynamically incorporates an input

I am in search of creative solutions to address an issue I'm facing. Currently, I am utilizing TINYMCE to incorporate text into my webpage. However, I would like to enhance this functionality by having a feature that allows me to add an image along w ...

Vue JS: dynamic reactive structure

As I delved into understanding the basics of reactivity and its syntax, I encountered an interesting problem. Take a look at this code snippet: const app = Vue.createApp({ data: dataFunction, methods: {method1: methodImpl} }) var dataObj = { tit ...

Navigating to the present child state with modified parameters can be achieved using the following steps

Check out this demo: https://jsfiddle.net/explorer/622qzqsc/ In the platform I'm working on, we have an advanced concept of state management, specifically for building timelines. In the template of this system, there's a code snippet (which is c ...

Discover the method for invoking a Javascript function within a Leaflet popup using HTML

Upon clicking on a marker on the leaflet map, I aim to trigger a popup box that contains five elements: Title Description Image Button (Next Image) Button (Previous Image) To achieve this, I attempted to include a custom popup for each feature ...

Setting up KCFinder integration in TinyMCE

I am utilizing TinyMCE as a text field, and I am in need of enabling image upload functionality within it. To achieve this, I am using KCFinder. However, I am encountering an issue where upon clicking on the 'Upload Images' button, only a white b ...

Tips on sending a form to the server with ajax technology

I'm struggling with sending a button id to my server through ajax in order to submit a form without having to constantly reload the page every time I click on a button. Unfortunately, it's not working as expected and I can't figure out why. ...

Is there a way to apply -webkit-line-clamp to this JavaScript content using CSS?

i have a random-posts script for my blogger website <div class="noop-random-posts"><script type="text/javascript"> var randarray = new Array(); var l=0; var flag; var numofpost=10; function nooprandomposts(json){ var total = ...