What is the best way to create an index for a user-provided value in a textbox

Looking for guidance on how to set an index to user-provided values in a textbox, append them to a table in a new row, and display that index in the first column of every row. I am unfamiliar with this type of functionality.

$(document).ready(function(){
  
$('#addbtn').click(function(){
 
  var s = $.trim($('#user').val());
  var i = 0;
  var c = 1;
  var count = i+c;
if(s !=''){
  $('#result').attr('src','http://www.clipartbest.com/cliparts/abT/y4b/abTy4bcL7.png');
$('#usertbl').append('<tr height=\"30\">'+'<td>'+count+'</td>'+'<td>'+s+'</td>'+'<td>'+'</td>'+'</tr>');
}
$('#user').val(' ');

  
});
  
});
table,tr,th,td{
border:1px solid #dddddd;
border-collapse:collapse;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="user"/>
<button id="addbtn">Add</button><span><img src="http://pix.iemoji.com/images/emoji/apple/ios-9/256/cross-mark.png" id="result" height="50" width="50"/></span>
<table style="width:100%;" id="usertbl">
<tr height="30">
<th width="34%">Serial Number</th>
<th width="33%">User NAme</th>
<th width="33%">Content</th>
</tr>
</table>

Answer №1

$(document).ready(function(){
var counter = 1;

$('#addbtn').click(function(){
var input = $.trim($('#user').val());

if(input !=''){
$('#result').attr('src','http://www.clipartbest.com/cliparts/abT/y4b/abTy4bcL7.png');
$('#usertbl').append('<tr height=\"30\">'+'<td>'+counter+'</td>'+'<td>'+input+'</td>'+'<td>'+'</td>'+'</tr>');
counter++;
}
$('#user').val(' ');
});

$('#user').keyup(function(){
$('#result').attr('src','http://pix.iemoji.com/images/emoji/apple/ios-9/256/cross-mark.png');
});
});
table,tr,th,td{
border:1px solid #dddddd;
border-collapse:collapse;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="user"/>
<button id="addbtn">Add</button><span><img src="http://pix.iemoji.com/images/emoji/apple/ios-9/256/cross-mark.png" id="result" height="50" width="50"/></span>

<table style="width:100%;" id="usertbl">
<tr height="30">
<th width="34%">Serial Number</th>
<th width="33%">User NAme</th>
<th width="33%">Content</th>
</tr>
</table>

Declare a variable outside the click event and update it using increment when clicked.

Answer №2

Make sure to declare the variable i before using it in the click function.

For example, you can initialize i with a value of 0 like this: ie- i=0;

Answer №3

To determine the index, simply tally the rows in the table

let $table = $('#usertable');
let rowCount = $('tr', $table).length;

Here is an example: https://jsfiddle.net/5qb36k9z/

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 best way to select the initial element from my class within my component using protractor?

Can anyone help me figure out how to click on the button in this component? I need guidance on navigating through the following path: Is xpath my only option for doing this? I believe a css locator could work as well, but I am unsure of how to construct ...

The video is not displaying on my website

I recently added a video to my webpage that is 3:48 minutes long. However, even though I have the navigation bar and sound in place, the video does not seem to be displaying properly. Here is an image of how it appears: https://i.stack.imgur.com/HeN41.png ...

Working with floating point numbers in Node.js with a zero decimal place

NodeJS interprets float values with a zero after the decimal point as integers, but this behavior occurs at the language level. For example: 5.0 is considered as 5 by NodeJS. In my work with APIs, it's crucial for me to be able to send float values w ...

Error in parsing string data in Django Chart.js ajax using javascript

I'm currently working on creating a chart web page using Django and Chart.js within the views.py file of the Django framework. class ChartView(TemplateView): template_name = 'graph.html' def get_context_data(self, **kwargs): ...

Tips for successfully transferring values or parameters within the Bootstrap modal

How can I create a cancel button that triggers a modal asking "Are you sure you want to cancel the task?" and calls a function to make an API call when the user clicks "Ok"? The challenge is each user has a unique ID that needs to be passed to the API for ...

Parsing XML with jQuery - Extracting attributes

Upon receiving XML response data through an Ajax request, my goal is to extract specific attribute values by parsing the XML data using jQuery. <Room1> <Node Name='Scene1' Text='Morning'/> <Node N ...

Access the second DIV using JavaScript's getElementById method

What could be preventing me from displaying a Google map in the second DIV ID? I attempted changing my Map_canvas to Class with the same results. I am aiming to showcase a Google map in the second Div, map_canvas. The map functions within my jQueryMobile s ...

How can I implement a hover-over image change effect similar to the one seen in Gmail accounts?

I am attempting to implement a feature that allows users to change their image, similar to what can be done in a GMail account. When the user hovers over the image, an option to "change image" should appear. This may be a new concept for me because I am ...

Unexpected alteration of property value when using methods like Array.from() or insertAdjacentElement

I'm encountering an issue where a property of my class undergoes an unintended transformation. import { Draggable, DragTarget } from '../Models/eventlisteners'; import { HeroValues } from '../Models/responseModels'; import { Uti ...

Rotate a shape to form a Rhombus at the center

I used the transform CSS property to create a rhombus, but I noticed that the center point of the shape is off-center to the right rather than in the middle. Can anyone help me figure out how to fix this issue? You can view my code here. .rhombus{ width ...

Tips for Passing On Parent tabindex Value to Children

Is there a way to propagate a parent's tabindex value to all of its children without individually setting tabindex for each child? Here is an example code snippet: <div id="app"> <div tabindex="2" class="parent-sec ...

Using AngularJS date picker to set value in Spring model setter

When using AngularJS with Spring, I noticed a discrepancy in the date values between my view file and the POJO User object. In my view file, I have used an input type date to bind the "user.dateOfBirth" attribute. When I select a date, it is displayed cor ...

In what way can I successfully trigger the submission of a form when clicking on a span element, utilizing AJAX to prevent the page from refreshing? At the same time, I would like to

Can I submit a form by clicking on a span element without refreshing the page? I also want to include a regular submit button for mobile view, but it only works when directly submitting the form. Is there a way to use ajax to submit the form when clicking ...

Strategies for resolving duplicate jQuery code in my project

Trying to simplify my jQuery code that handles video selection and playback functionality. Users can click on a thumbnail or button to play a specific video, with the title of the video changing accordingly. Despite achieving the desired outcome, the cur ...

Managing Asynchronous Callbacks in JavaScript using Node.js

I am a beginner in the world of Javascript and I recently encountered a challenge with async callbacks using Node.js. My first step was setting up the Facebook webhook and sending a Webhook POST request Below is the code snippet : routes.js **Setting up ...

tips for personalizing your jQuery image preview script

Currently, I have implemented a jQuery script that allows me to preview multiple images before uploading them. Although the functionality works well, I am facing difficulties customizing it to meet my specific requirements. <script> $(document).r ...

Trouble selecting options in hierarchical data

I've been attempting to run this sample code for selecting an option from a select element with hierarchical data, but it seems to be having some issues. $scope.options = [ { id: 1, info: { label: "Item 1" } }, { id: 2, info: { label: ...

Using CSS to customize the appearance of the preview in CKEditor

After successfully integrating CKEditor into my website CMS, I am facing an issue with the Preview button not using stylesheets (CSS). Despite editing the preview.html file located in: Website/ckeditor/plugins/preview/ It appears that the CSS is being ig ...

Unsuccessful AJAX form submission failing to include file input type

"I'm having trouble getting the $_FILES variable in my PHP script when posting a simple form using AJAX." <form id="submitForm" method="post" enctype="multipart/form-data" > <input type="file" name="file" /> <input type="tex ...

Unusual occurrences within stacked MUI Popper components

Below is a sample Node component that uses a button element to anchor an MUI Popper: type Props = { children?: React.ReactNode; }; const Node = ({ children }: Props) => { const [anchor, setAnchor] = React.useState(null); return ( <div> ...