A guide on alternating text input between two colored boxes using HTML

Currently, I have a code that can create two boxes and four buttons. However, only one button, the start button, triggers a popup requesting a name input. Once you enter a name, it will appear in the first box.

<html>
  <head>
    <script>
      function myTask1() {
        var sentence = prompt("Please enter a name");
        var arrSentence = sentence.split(" ");
        if (arrSentence != null) {
          document.getElementById("answer1").innerHTML = arrSentence.sort(); //utilizing Array.sort() method 
        }
        console.log(sentence);
        return sentence;
      }

      function myFunction() {
        var x = document.getElementById()
      }

    </script>
    <style> </style>
  </head>

  <body>
    <p><button type="button" onclick="myTask1()">Click me!</button></p> 
    <button type="button" onclick="ClearFields();">Clear</button> 
    <button type="button" onclick="myFunction()"> --> </button> 
    <button type="button" onclick="myTask4()"><-- </button> 
      <div clas="box" style="background-color:red; height:200px; margin:20px auto;">
        <center>
          <p id="answer1"></p>
          <center>
        </div>
        <div class="box1" style="background-color:grey; height:200px; margin:20px auto;"> </div>
  </body>
</html>

https://i.sstatic.net/qFBKg.png

Answer №1

I have created a sample code for you. Assuming that you are new to programming since the question is quite basic. But starting something new is always exciting. You can search for solutions online, and often the best programmers are skilled at using Google effectively. However, I believe by demonstrating the solution, you will grasp the underlying structure. Make an effort to comprehend each line of the code and try rewriting it from scratch as practice.

Code: https://github.com/Bunpasi/stackoverflow-answers/blob/master/js-listbox-selector/index.html

Key points to observe: - The script is placed in the footer to prevent affecting page loading time. - All code is enclosed within an anonymous function to avoid global function declarations. - The spelling correction was made from clas to class. - Event listeners are used instead of inline event attributes. - Logic duplication for both boxes is avoided by utilizing a single function applicable to both scenarios.

Upon understanding the code, there are areas where you can enhance it: - Ensure selection persistence after updates by storing this data as well. Instead of just an array of IDs, consider converting it into an array of objects with additional crucial information like selection status. - Transfer the style definitions from individual elements to the header section.

Do not get disheartened by any negative feedback received.

All the best!

Update

If you wish to relocate names consistently, follow these steps:

This line identifies all selected elements:

var selectedElements = boxes[fromId].querySelectorAll('.list_item.selected');

Adjust the selector to exclude selected:

var selectedElements = boxes[fromId].querySelectorAll('.list_item');

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

Using the double class within the .solution environment and adjusting the label of the .solution environment using CSS styling

Currently constructing a book with the use of quarto, where the inclusion of theorems, lemmas, corollaries, and other elements is necessary. In the quarto documentation, as seen here, it is advised to utilize the proof, remark, and solution environments fo ...

Unresolved Issue: Phonegap App Unable to Display JPG Images

As I develop an iOS application using PhoneGap, I have encountered an issue with displaying images. While PNG images show up perfectly fine, JPG images are not loading at all. Instead of the images, question marks appear. <div> <img src="http://w ...

What is the best way to incorporate this custom file upload button, created with vanilla JavaScript, into a React application?

Hey there! I have successfully implemented a custom file upload button using HTML, CSS, and JS. Now, I want to recreate the same design in React. Can someone guide me on how to achieve this in React? HTML Code: <br> <!-- actual upload which is h ...

The index.html file is not displaying correctly on a servlet 3.0 configuration with Tomcat

I am currently working on a basic web application using Servlet 3.0 with Tomcat 7.0.25, and deploying the application as a war file named mywebapp.war. The structure of the war file is as follows: mywebapp/index.html mywebapp/META-INF/MANIFEST.MF myweba ...

Is it possible to utilize a WordPress page as a CSS stylesheet?

Is there a way to customize my WordPress theme's CSS through a Page in the backend rather than editing the default style.css file? I've seen it as a page template before but I'm having trouble figuring it out on my own. I'm currently r ...

Is there a way for me to obtain the present value of the chosen button in the list below?

I am working with a group of three buttons labeled English, Hindi, and Urdu. How can I retrieve the value of the selected button in a JavaScript function? <div class="btn-group" data-toggle="buttons"> <label class="btn btn-primary active"> ...

How can I transform each word to resemble this format?

let sentence = "Hello+world + like+ this + name,bla"; sentence = sentence.replace(/\+\s\+/g, function(match){ return "*" + match.trim() + "*"; }); alert(sentence); // Output will be " *Hello*+*world*+like*+this*+name,*bla* "; How can I ...

Tips for inserting an object into an array

Here's the data I received: { 0:{modifierId: 4, modifierName: 'Garlic', modifierPrice: 60 } 1:{modifierId: 1, modifierName: 'Tartar ', modifierPrice: 60} 2:{modifierId: 3, modifierName: 'Herb ', modifierPrice: 60} item ...

The functionality of $_GET has suddenly ceased when attempting to delete records

My web application's delete user function has suddenly stopped working, even though I haven't made any changes to it. This has left me feeling quite puzzled. I have PHP Console installed in Chrome (as well as the app), but it hasn't shown an ...

Separate .env configurations tailored for development and production environments

Managing different content in my .env files is crucial as I work with both next.js and node.js. The settings vary between development and deployment environments. During development: DOMAIN_URL=https://localhost:3000 GOOGLE_CLIENT_ID='abc' For ...

Is there a way to access and click this image link using Selenium if it doesn't have an id attribute assigned

I am struggling to find a way to click and navigate to the href destination without an apparent id. The link in href may change unexpectedly, so I need a flexible solution for this. Can you provide code that would help me achieve this? <ul style="dis ...

Concern regarding the duration setting in the date-picker

Is there a specific "campaign duration" rule where you must select a date between the first and last day of the month? If you choose a date outside of this range, such as a date from the next month, the Backend API will return an "Input param error." Curr ...

Trackball's controls are not responding correctly

Recently, I have been using trackball controls and I've come across a strange bug. When I pan and then zoom out from my new position, the controls start to behave erratically, pulling towards the origin (the further I pan, the worse the issue becomes) ...

AngularJS - ensure that only authenticated users are allowed to access specific routes

Within my application, I have an authService that manages the isAuthenticated flag when a user is logged in. Each time there is a route change, a listener is triggered by the $routeChangeStart event to verify if the user is authenticated using authService. ...

Utilize CSS exclusively to position the div

Trying to achieve a specific layout, which can be better understood by checking out this fiddle: https://jsfiddle.net/zbh8ewqg/ The goal is to align the #inner div in such a way that its top matches with the top of the #outer div. While this might be fe ...

What is the best way to achieve this in Node.js/Express using Redis? Essentially, it involves saving a callback value to a variable

Here is the data structure I have set up in redis. I am looking to retrieve all values from the list and their corresponding information from other sets. Data structure : lpush mylist test1 lpush mylist test2 lpush mylist test3 set test1 "test1 value1" ...

What is the best way to fill in columns with data, adding one entry per column each time and repeating the process in a loop?

I am looking to display multiple posts on a page within 3 columns: column 1 | column 2 | column 3 | The desired outcome is: column 1 | column 2 | column 3 | post1 post2 post3 post4 post5 post6 ... For instance, the HTML code appe ...

Display pop-up notification box in Yii2 when receiving an AJAX request

I am currently working with this jquery code in one of my view files $('#ticket-ticket_impact_id').change(function() { var priority = $('#ticket-ticket_priority_id :selected').val(); var impact = $('#ticket-ticket_impact_id : ...

What could be the reason my Bootstrap webpage is not optimized for mobile devices?

My website is currently hosted at "nateshmbhat.github.io". I have implemented mdboostrp's row and col for the structure of my website, but unfortunately, it is not very mobile-friendly as it displays a lot of unnecessary background space. If you woul ...

I am unable to properly align the image within the div

I'm having trouble centering an image on my website. Can someone help me figure out what I need to change or add in order to get the image centered? #img-wrap { width:450px; clear:both; display:block } #img-wrap img { margin:0 auto; text- ...