$('form').submit(function(){
const $favDevices = $("#favDevices")
const unvalidated = $favDevices.val()
const validated = unvalidated
.split("n")
.map(line => `${line}-VALIDATE`)
.join("")
$favDevices.val(validated)
})
Solution 1 :
Solution 2 :
The value from the textarea is a string. You need to split the string into lines, add -VALIDATED
to the end of each line, then recombine it into a single string.
I usually use a regular expression like this to split into lines:
let lines = $("#favDevices").val().split(/(?:rn|r|n)/);
Then map
is useful for processing each line:
lines = lines.map(line => line + "-VALIDATED");
Then join
recombines into a single string; choose your delimiter, I usually use a single n
.
const str = lines.join("n");
Live Example:
const str =
$("#favDevices").val().split(/(?:rn|r|n)/)
.map(line => line + "-VALIDATED")
.join("n");
console.log(JSON.stringify(str));
<textarea id="favDevices" class="t">Laptop
Computer
PlayStation 4</textarea>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
In a comment you’ve said:
But I want to replace those content inside of textarea to
device-VALIDATED
so the new value of device isdevice-VALIDATED
You’d add a fourth step: Writing back to the textarea
:
$("#favDevices").val(str);
Live Example:
const favDevices = $("#favDevices");
const str =
favDevices.val().split(/(?:rn|r|n)/)
.map(line => line + "-VALIDATED")
.join("n");
favDevices.val(str);
<textarea id="favDevices" class="t">Laptop
Computer
PlayStation 4</textarea>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Problem :
How can I replace the one content inside of textarea. I have a textarea for the user’s favorite devices.
<textarea id="favDevices" class="t"></textarea>
Let’s say users give this three devices:
Laptop
Computer
PlayStation 4
After submitting it (using the jquery ajax) I want to replace one of the content to device-VALIDATED
. So the results would be
Laptop-VALIDATED
Computer-VALIDATED
PlayStation 4-VALIDATED
I try figure out how can I do it using this code:
$('form').submit(function(){
f = $("#favDevices").val().split("n")
for(i in f){
device = f[i];
// function here to send data to back end
f.replace(device, device + "-VALIDATED")
}
})
Comments
Comment posted by T.J. Crowder
“After submitting it…”
Comment posted by T.J. Crowder
Ah, if only line breaks were that simple, cross-browser/OS… 🙂
Comment posted by John Albert Flores
But I want to replace those content inside of textarea to
Comment posted by T.J. Crowder
@JohnAlbertFlores – Then use