Create a button toggle feature to dynamically display data for a specific record within an ng-repeat loop

Currently, I am facing an issue while implementing a start and stop timer in JavaScript for a list of records. To display all the items, I am using ng-repeat. Each repeated element has a Start/Stop toggle button. The problem arises when there are 4 records - if I click on the start timer button for the 4th record, then the button for the first record also changes to Stop. No matter which button I click, it always toggles the first record's button.

Below is the HTML code snippet:

<ul class="list-group" data-ng-repeat="job in 
allAppliedJobsForTimeTracker">
<li class="list-group-item">{{job.title}} Hours : {{job.hours}}
<input type="button" name="btn" id='btn' value="Start" data-ng-
click="startTimeTracker(job)" onclick="to_start()";> </li>
</ul>

And here is the script code:

<script language=javascript>
var h=0;
var m=0;
var s=0;

function to_start(){
    switch(document.getElementById('btn').value){
        case 'Stop':
            window.clearInterval(tm); // Stop the timer
            document.getElementById('btn').value='Start';
            break;
        case 'Start':
            tm = window.setInterval('disp()', 1000);
            document.getElementById('btn').value='Stop';
            break;
    }
}

function disp(){
    // Format the output by adding 0 if it is single digit //
    if(s < 10){var s1='0' + s;}
    else{var s1=s;}
    if(m < 10){var m1='0' + m;}
    else{var m1=m;}
    if(h < 10){var h1='0' + h;}
    else{var h1=h;}
    
    // Display the output //
    var str = h1 + ':' + m1 +':' + s1 ;
    document.getElementById('n1').innerHTML=str;
    
    // Calculate the stopwatch //
    if(s < 59){ 
        s = s + 1;
    } else {
        s = 0;
        m = m + 1;
        if(m == 60){
            m = 0;
            h = h + 1;
        } // end if  m == 60
    }// end if else s < 59
    // end of calculation for next display
}
</script>

I want to change the button only for the clicked record row, not for the first record. Does anyone know how I can achieve this?

Answer №1

You are accessing the first instance of btn. Instead of using getElementById, try utilizing event.target. Here is an example:

<input 
  type="button" 
  name="btn" 
  id="btn" 
  value="Start" 
  data-ng-click="startTimeTracker(job)" 
  onclick="to_start(event)" 
/>

function to_start(event) {
  switch(event.target.value) {
    case 'Stop':
      window.clearInterval(tm); // stop the timer 
      event.target.value='Start';
      break;
    case 'Start':
      tm=window.setInterval('disp()',1000);
      event.target.value='Stop';
      break;
  }
}

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

What is the process for deleting an event in Vue?

My Vue instance currently includes the following code: async mounted () { document.addEventListener('paste', this.onPasteEvent) }, beforeDestroy () { document.removeEventListener('paste', this.onPasteEvent) }, methods: { onPasteEv ...

Guide to automatically update mysql posts every second

Utilizing ajax, I am able to save user posts/comments into a mysql table without the need for a page refresh. Initially, there is this <div id="posts-container"></div> Next, I attempted to use Jquery load() to iterate through a table and disp ...

Utilizing jQuery BBQ for Seamless Transitions – From Fading to Sliding and More

This is my first time posting a question here, even though I am an active user of stackoverflow. I have developed a website using jQuery BBQ to load pages through AJAX while still maintaining the ability to track history with the back button and other fun ...

Unable to retrieve JSON data using jQuery

When working with jQuery to retrieve JSON data, I encountered an issue. After storing the data in a variable named "ajaxResponse," attempting to access specific data points resulted in an error stating that ajaxResponse.blah is not defined. Interestingly, ...

Error encountered while adding x-ray-scraper to project using Npm

I am currently working on a Vue application and utilizing the x-ray-scraper library. However, when I attempt to run npm run serve in the terminal to preview the application locally, I encounter the following error: This dependency was not found: * _http_c ...

Navigate to a different page using a sliding transition

Currently, I am working on a project using jquery-mobile where I need to redirect to another page after clicking on an image with a delay. This is what I have done so far: setTimeout(function(){ window.location.href = "myPage.html"; }, 1000); While t ...

Refresh the browser tab's content

How can I reload the specific content of a browser tab? I am looking for a solution that does not rely solely on jQuery (although I prefer it if there are more options available). Here is what I need: I have a page with many links to other pages (the fo ...

Utilizing Node.js to Retrieve Data from MySQL

Hi there, I'm new to NodeJS and I'm curious about how to fetch a MySQL query like we do in PHP. $query = mysql_query("SELECT * FROM accounts"); while($fetch = mysql_fetch_array($query)) { echo $fetch['Username']; } How would this be ...

What is the best method for transmitting the filename using Plupload?

I've been trying to solve this issue for a while now. My problem seems straightforward – I want to send the filename along with the file as a multipart request in Plupload, but so far, I haven't had any success. The main thing I'm missin ...

What is the best way to retrieve nested reference data all at once from a Firestore document?

I have two distinct collections stored within my Firestore database. The first collection is users, and it can be visualized as shown here: https://i.stack.imgur.com/AKlyM.png The second collection is posts, represented by the following structure: http ...

Cloned bootstrap nav tabs are controlled just like the original version

I have a unique scenario where I need to generate a series of "cards" with tabs on top (each card having tabs). To accomplish this, my plan was to use a template element that I can clone and then populate. Everything seems to work fine, except for the tabs ...

JavaScript function is not identifiable

I am currently developing a tic-tac-toe game with 9 buttons that will display either an X or O image depending on the boolean value of the variable isX. The main container for these buttons is a div element with the id 'stage' and each button ha ...

"Adjusting Material UI Select Size - A Guide to Resizing Your

Struggling with getting Material UI selects to work properly with height and width using 'vh' and 'vw', as well as adjusting text size with 'vh'. The boxes have the correct size, but the label text is no longer centered due t ...

Struggling to make an AJAX form function properly

I'm running into an issue while setting up a basic AJAX form. My goal is to have a message display on the same page upon successful login using a PHP form through AJAX, but currently, I get redirected to the PHP file after form submission. Can anyone ...

Automatically close the menu in ReactJS when transitioning to a new page

I have created a nested menu, but I am facing an issue with it. Here is the structure: Parent_Menu Parent1 > Child_Menu1 > Child_Menu2 Parent2 Currently, when I click on, for example, Child_Menu1, I am redirected to the correct page ...

What are the steps to set up Redis Store in my production environment?

I am currently in the process of setting up Redis as a session store, but for some reason it's not functioning properly. I have integrated passport.js and express-flash, however when I attempt to run the current Redis setup, it fails to work: var ses ...

Developing my React application with Material UI. The fonts I've implemented don't appear consistent on Mac operating systems

Why does the font change in Mac and iOS platforms, and how can I ensure consistency across all devices? Here is an excerpt from my index.css file: body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto&apos ...

What do you do when you need to hide a table column that has a colspan

I have been searching for a solution to my unique table structure, but I haven't found any that match my situation. When attempting to hide column A or B, the following code works perfectly: $('table td:nth-child(1),table th:nth-child(1)') ...

Using Javascript to dynamically add form fields based on the selection made in a combo box

I am in the process of creating an information submission page for a website, where various fields will need to be dynamically generated based on the selection made in a combo box. For example, if the user selects "2" from the combo box, then two addition ...

Setting the font-size in HTML/CSS to dynamically adjust and fill the entire width and height of its

I'm trying to make a <div> element adjust its size based on the browser window. Within this <div>, there is a paragraph of text: <div style="width:80%; height:80%; margin:10%;"> <p>Paragraph of text. Paragraph of text. Pa ...