Reputation: 921
I have a field and when I paste some content in it, the content gets validated and added line by line to another hidden field. My content can be a number of mobile number separated by new line and when you paste them in to the visible field, each line gets validated and added to another hidden field which is used to pass the value to the backend.
e.g.
12345
54321
34567
They way I use to add the value to the hidden field can be seen in the following piece of code:
$('#recipients').val($('#recipients').val().length <= 0 ? output.join("\n") : $('#recipients').val() + "\n" + output.join("\n"));
in above code 'output' is a line (a number) from the content the user paste and the recipients is the hidden field.
This line gets called as many as my content lines. But when I check the performance this line takes a lot of cpu load (when the number of lines are too high) and creates a lag on doing the job (browser hanging).
So can this line of code be rewritten in a more efficient way?
Thanks,
Upvotes: 0
Views: 110
Reputation: 782488
Here's how to cache the result of a selector in a variable:
var $recip = $("#recipients");
var $recipval = $recip.val();
var new_out = output.join("\n");
$recip.val($recipval.length == 0 ? new_out : $recipval + "\n" + new_out);
You can also bypass jQuery, to get a little more boost:
var recip = $("#recipients")[0];
var recipval = recip.value;
var new_out = output.join("\n");
recip.value = recipval.length == 0 ? new_out : recipval + "\n" + new_out;
new_out
doesn't affect performance, it just makes the code easier to understand.
Upvotes: 2