faize
faize

Reputation: 59

How to add value to an input rather than replacing the input with new value using jquery

I am getting the current input id and storing it in a variable and selecting that input to add whatever the previous input value that was entered by the user.

$("#" + current_cursor_input).prev().val("value added");

However the prev() function does not really add a new value, it just replaces the old one, same as how the code below works

 $("#" + current_cursor_input).val("value added");

I have seen previous StackOverflow answers and the answers no longer work, such as this

Upvotes: 0

Views: 123

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

To do this you can provide a function to val() which accepts the current value as an argument. You can then concatenate it with the new value you want to add on, something like this:

$("#" + current_cursor_input).val((i, v) => v + " value added");

Upvotes: 0

user3310334
user3310334

Reputation:

First get the previous value, then add to it:

var previousValue = $("#" + current_cursor_input).val();
$("#" + current_cursor_input).val(previousValue + "value added");

Upvotes: 1

Related Questions