Retrieving two values from a 2-dimensional array but displaying only one

Hey there, I'm trying to extract the first word from an array I've created and then display its antonym upon clicking a "flip" button. Basically, I want to fetch the 0th and 1st elements but only reveal the 0th one initially until the user clicks the button (which should switch 0 with 1). The current code is functional, but it currently appends both words to #input.

Below is my JavaScript code:

var words = [];
words[0] = ['Budding','Accomplished']; 
words[1] = ['Curious','Certain']; 
words[2] = ['Realistic','Idealistic']; 
words[3] = ['Practical','Imaginative']; 

function random_sort () {
      return (0.5 - Math.random() );
}

words.sort(random_sort);

var i = 0,
    n = words.length;

$("#forward").data('dir', 1);
$("#back").data('dir', -1);

$("#forward, #back").on('click', function() {
    i = (i + $(this).data('dir') + n) % n;
    $("#input").hide().html(words[i]).fadeIn(100);
    $(words[i][1]).hide();
});

$("#back").trigger('click');

Here's the corresponding HTML code:

<object id="back" type="image/svg+xml" data="images/arrow.svg"></object>
<p id="input"></p>
<object id="forward" type="image/svg+xml" data="images/arrow.svg"></object>

<img id="flip" src="images/fliptext.svg">

I would greatly appreciate any assistance. Thank you!

Answer №1

The issue lies with the code

$("#input2").hide().html(words[i]).fadeIn(100);
, specifically with html(words[i]). This line of code is equivalent to html(['Budding','Accomplished']), which concatenates the array before adding it to the html.

To resolve this, change the code to

$("#input2").hide().html(words[i][0]).fadeIn(100);
, where words[i][0] selects the word at index 0 in the array.

var words = [];
words[0] = ['Budding','Accomplished']; 
words[1] = ['Curious','Certain']; 
words[2] = ['Realistic','Idealistic']; 
words[3] = ['Practicle','Imaginative']; 

var i=0;
$("#input").hide().html(words[i]).fadeIn(100);
$("#input2").hide().html(words[i][0]).fadeIn(100);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<strong>Wrong</strong><div id="input"> </div><br>
<strong>Right</strong><div id="input2"> </div>

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

Retrieve the chosen option from the Bootstrap 3 select dropdown

Utilizing the Bootstrap 3 framework, I am incorporating a select element with the selectpicker class. My goal is to capture the data selected by the user using the jquery onchange event for my selectpicker. While I am confident in retrieving data from a tr ...

Issue with dynamic dropdown selection causing element to not display

My code is designed to call the addpoc() method on button click, which generates a set of input boxes and a dropdown. When the dropdown option personal/workmail is selected, an input box should appear based on the selection. The issue arises after the init ...

Avoid inserting line breaks when utilizing ngFor

I am using ngFor to iterate through a list of images like this: <div class="image-holder" *ngFor="let image of datasource"> <img src="{{image.url}}" height="150" /> </div> Below is the corresponding CSS code: .image-holder { di ...

Using the Enter key to submit HTML forms

I created a custom console using HTML, CSS, and JavaScript. The input doesn't show up when I press enter, I have to click the send button. How can I make it send on enter press? Here is the code, please assist me: /* code goes below*/ <!DOCTY ...

Styling various versions of a <button> using Styled Components

In my app, I have a basic colored button that needs to change its color depending on the UI state: const StyledButton = styled.button` & { border: 0; color: white; cursor: pointer; } &:hover { background-color: ${(props) => ...

It is not possible to access fields in Firestore using Node.js

Exploring the limits of my Firestore database access with a test function: exports.testfunction = functions.https.onRequest(async (request, response) => { try{ const docRef = firestore.collection("Stocks").doc("Automobile" ...

Node.js Discord Bot | Config File Manipulation for Improved Functionality

Currently, I am facing a challenge with understanding how my NodeJS bot can effectively read and write data to a config.json file. Additionally, I am unsure about how to identify arguments that are passed along with a Bot Command. With that in mind, I have ...

Having trouble with implementing the .addclass function in a dice roller project

I'm looking to have the element with id=die load initially, and then on a button click event labeled "click me," apply the corresponding CSS class such as 'die1,' 'die2,' and so forth. function roll() { var die = Math.floor(Ma ...

Is it possible to create my TypeORM entities in TypeScript even though my application is written in JavaScript?

While I find it easier to write typeorm entities in TypeScript format, my entire application is written in JavaScript. Even though both languages compile the same way, I'm wondering if this mixed approach could potentially lead to any issues. Thank yo ...

Stop the page from refreshing when submitting a form

Why is e.preventDefault() not working when attached to the form? Every time I press the save button, the page reloads upon submission. I have another Form component that functions perfectly fine, but I cannot seem to fix this one. Any ideas on what mista ...

Unexpected behavior observed when executing JavaScript Promise.all code

My current issue involves retrieving data from a mySQL DB by using the following code. Within the database, there are multiple tables including an Activity table with a channelId field, a Channel table with a userId field, and a User table with a userName ...

What is the best way to create underlined text that is either left-aligned or centered?

I am looking to replicate this specific style of decoration in a full width container. My goal is to have it aligned to the left of the text and restricted to a maximum width. https://i.stack.imgur.com/H8DXT.png ...

Binding Vue element data to an HTML property is a powerful feature that allows

I'm having trouble binding selected rows to an array. I've attempted to bind data from a v-for loop to the value of my input, using v-bind:value="row.id" or value={{row.id}}, but neither seem to be working. <tbody> <tr v-for="row in g ...

Transforming an array into a JSON structure that resembles a tree

Below is an array that I am attempting to convert into a JSON object: Array ( [0] => 102 [id] => 102 [1] => [attribution] => [2] => image [type] => image [3] => [latitude] => [4] => [ ...

Having trouble updating the dropdown value in a React child component

There are two main components in my code: App component: class App extends Component { constructor(props) { super(props); this.state = { selectedScale: "WholeTone" }; this.handleScaleSelect = this.handleScaleSelect.bind(this); } ...

What is the local date format for the Ionic DatePicker?

I have successfully implemented a DatePicker in my Ionic Project, but the date is displaying in the wrong time format. Here is my function: showDatePicker(){ this.datePicker.show({ date: new Date(), mode: 'date', allowOldDates: fal ...

Transitioning to mobile-friendly web design

Just completed my very first page for a personal portfolio website. As a novice in web development, I made the width of my site 1600px to match the background image. Now, my goal is to make the page responsive. However, when I adjusted the width to 100%, ...

Dividing an Image into segments using Javascript

I'm currently working on a basic Jigsaw puzzle project. To achieve this, I am required to divide the image I've selected into 20 separate pieces. I was wondering if there is a method in Javascript that can automatically cut an image into 20 equal ...

Is there a way to update the value of an <input> element dynamically?

There is an input in a datalist that I am working with. <input type="text" value="1" id="txtcount"> I am trying to obtain the new value of the input when the text changes. I attempted to use the following code, but it did not work as expected. &l ...

Nav Dropdown Beyond Container Bounds

I'm working on implementing a flexbox navigation menu with dropdowns for certain items. However, I've encountered an issue where the dropdown lists are appearing to the right of the container on hover, rather than below it as expected for a typic ...