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

Submitting the ajax form multiple times

Here is the code I am using within the Yii framework: The view form: view.php <div class="form"> <?php $form = $this->beginWidget('CActiveForm',array( 'id'=>'user-profile', 'action&apo ...

What is the best way to determine if any of the list items (li's) have been marked as selected?

<div id='identifier'> <ul id='list'> <li id='1' class="">a</li> <li id='2' class="">a</li> <li id='3' class="">a</li> <li id='4' class=" ...

Switching the markLine in vega lite to a markBar causes it to lose its sorting arrangement

I have created the following data visualization: data = [{"student_name": "student 0", "e": "100.15", "d": "127.81"}, {"student_name": "student 1", "e": "100.30", "d": "189.94"}, {"student_name": "student 2", "e": "100.15", "d": "105.33"}, {"student_nam ...

Implementing text wrapping within input elements for optimal print.css layout

Can you help me with a print.css issue I'm experiencing? I am currently working on my print stylesheet and I've encountered a challenge where I need to word wrap input fields to ensure all the text is displayed correctly. Despite trying various ...

Tips for enabling scrolling on mobile devices

Hello there, I'm facing an issue with scrolling on my website when viewed on mobile devices. Even though I have set the div height to 100%, it appears as 'auto' on mobile screens. As a result, when the text exceeds the screen height, it bec ...

Guide to sending parameters to the getInitialProps function in the _app.js file within Next.js by extracting them from the URL

Shown below is the getInitialProps function for my custom MyApp. MyApp.getInitialProps = async ({ctx}) => { const { siteHeaderCollection } = await getHeaderData(ctx.query.lang) const { siteFooterCollection } = await getFooterData(ctx.query.lang) ...

Sending an object from ng-repeat to a different page for the purpose of showcasing its contents

Currently, I am immersed in a project that involves MySQL, Angular, Express, and Node. Within this project, I have an array of objects displayed using ng-repeat. The goal is to allow users to click on a specific item and navigate to another page where they ...

Dynamic Search Feature Using AJAX on Key Press

Currently, I have developed an AJAX search function that retrieves keyword values upon key up and triggers the script. The objective is to update the content area with results in alphabetical order as the user types each key. However, the issue I am facin ...

Tips for fixing the async/await problem in JavaScript

Here is the code I've been working on: let icsFileData = []; icsFileData = filterAttachmentArray.map(async(file) => { let buff = new Buffer(file.data, 'base64'); let text = buff.toString('ascii'); const data = await ical ...

Guide on how to conditionally render Container Classes

Initially, the designer provided me with this: Essentially, a category is passed from the previous screen. Through some UI interactions, I have to render this screen repeatedly. The flow goes like this: you choose a category, if it has subCategories, allo ...

Using React to Render a Component with Local Storage Information

I'm in the process of developing a history list component for a form within a react application and encountering difficulties with local storage. The goal is to display a list of previous user inputs from the local storage data. My current approach i ...

"Navigate back to a previous page in Vue Router without having to

I am currently exploring the option of creating a back button in my Vue.js application using vue-router that mimics the behavior of the browser's native back button. The challenge I'm facing is that when using history mode for the router and tryi ...

What is the best way to arrange an unordered list in a horizontal layout?

I have four lists that I want to display side by side. The first row should show a Doctor and Patient side by side, the second row should show a Pharma Company and Employee side by side. However, in my code, this layout is not working as intended. .tree ...

Create a file object using content with the help of JavaScript

I am working with a file containing specific data const ics = 'BEGIN:VCALENDAR\n' + 'VERSION:2.0\n' + 'CALSCALE:GREGORIAN\n' + 'METHOD:PUBLISH\n' + 'END:VCALENDAR\n'; I am trying t ...

Iterating over an array of objects and executing asynchronous operations

I am currently working with NextJS and managing an array of assets (images) within my state. The task at hand is to post these images to the API. To accomplish this, I have a specific object that handles the posting process using the following syntax: let ...

How can we rearrange the positions of three items in an array?

I am dealing with a function that returns an array of objects structured like this const allGreen = _.filter( sidebarLinks, side => !isServicePage(side.slug.current) ); https://i.stack.imgur.com/dR8FL.png I am attempting to rearrange the positions of ...

"The 'BillInvoice' object must be assigned a primary key value before it is ready for this relationship" - Error Message

There is an issue in my Django project related to the creation of a BillInvoice and its associated BillLineItem instances. The error message I'm receiving states: "'BillInvoice' instance needs to have a primary key value before this re ...

Alter the displayed content of the component based on the tab that is selected

How can I change the content of a div outside of v-tabs based on the selected tab? I want to use the tabs as a navigation bar and not contain the content within the tabs. Do I need to use v-router within the component and give each tab a different href? M ...

How can I apply a jquery method to a variable when JavaScript already has a method with the same name?

Is it possible to call the .which function on a character without needing to differentiate between browser types by using the jQuery .which method, which supposedly normalizes for browser discrepancies? I know that the inherent javascript method is also ...

Having trouble with Node.js and jQuery on my local machine

My Node.js API is designed to create a post with simplicity: var express = require('express'); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var app = express(); var Posts = require('./mode ...