2

I have this code:

<textarea class="mapCode">
<    area shape="rect" coords="" href="http://www.sitehere" target="_self">
</textarea>

How can I use jQuery to insert/update values into the coords attribute even if it's not empty?

Right now I'm using...

return $(this).text().replace("coords=\"\"", 'coords="'+selection.x1+','+selection.y1+','+selection.x2+','+selection.y2+'"');

But of course that only works one time since it's always looking for an empty coords="" attribute.

j08691
  • 204,283
  • 31
  • 260
  • 272
Eric
  • 23
  • 2
  • As a side note: http://stackoverflow.com/a/1732454/1414562 – A. Wolff Jan 05 '15 at 18:52
  • True. However, in this case the parsed HTML is very limited, making RegEx a feasible and especially fast option to solve this problem (see also the second answer to the posted question: http://stackoverflow.com/a/1733489/1595029) – irruputuncu Jan 05 '15 at 19:04
  • @irruputuncu ya in this case regex should be enough – A. Wolff Jan 05 '15 at 19:09

3 Answers3

1

You should use a regular expression with a wildcard in your replace call:

$(this).text().replace(/coords=".*"/gi, 'coords="..."');

This will work with both an empty and a set coords attribute.

irruputuncu
  • 1,460
  • 1
  • 11
  • 24
0

You can wrap textarea content in a jQuery object then use any relevant method to update it, e.g:

var $content = $('<div/>').html($('.mapCode').val());
$content.find('area').attr('coords', selection.x1+','+selection.y1+','+selection.x2+','+selection.y2);

$('.mapCode').val($content.html());

-DEMO-

A. Wolff
  • 74,033
  • 9
  • 94
  • 155
-1
<textarea class="mapCode">
   <area id="myArea" shape="rect" coords="" href="http://www.sitehere" target="_self">
</textarea>

JavaScript:

$(function () {
    var myArea = $('#myArea');
    myArea.attr('coords', selection.x1+','+selection.y1+','+selection.x2+','+selection.y2);

});​
Mike W
  • 308
  • 3
  • 5