0

Can anyone give me a better way (or best practice way) of doing the following in jQuery:

I have control elements on a page for example:

<input id="generate-log" /> Enter the id you wish to process
...

and a handler for the form change:

// the next line gets generated, just written here for simplicity
var url = '/report/log/XidX/csv';

$(function() {
    $("#generate-log").change(function() {
        var id  = $(this).val();
        var loadUrl = url.replace('XidX', id);
        // ... do some ajax with loadUrl...
    });
});

the url is generated as part of the template with id as XidX

The above works fine, but to me it seems that generating the url with XidX and then replacing it in JS seems a bit clumsy. Is there a neater way to do this or am I just being overly pedantic?

Thanks

Edit:

Thanks for comments. I think there is no right/wrong answer here.

mogoman
  • 2,286
  • 24
  • 28
  • Have a look at http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format/4673436#4673436 – ThiefMaster Nov 19 '11 at 21:37
  • Wait, you have a JavaScript variable you don't have control over? Or is that actually coded in the HTML somewhere? – Levi Morrison Nov 19 '11 at 21:38
  • I wouldn't worry too much about it. You could do it differently but there's no point. My question is how will the users know what ID to actually enter? – Christian Nov 19 '11 at 22:52
  • @ChristianVarga thanks for the reply - that's basically what I needed to know. I have full control of the url generation - it is generated by Zend Framework using $this->url(...) - however what generates the url and how isn't important. – mogoman Nov 20 '11 at 15:55
  • @ThiefMaster - thanks for the suggestion, that is actually a nice way of doing it. – mogoman Nov 20 '11 at 15:58
  • mogoman, Arif RH's answer is "prettier" than your implementation. I am all for avoiding unecessary stress and creating a new variable just to change it right after is a waste of processing (var id = $(this).val() ... just to drop it in). – zequinha-bsb Nov 20 '11 at 16:36

1 Answers1

1

if you have a fixed format for the url, i think this little code could work :

$(function() {
   var loadUrl;
   $("#generate-log").change(function() {
      loadUrl = '/report/log/'+$(this).val()+'/csv';        
      // ... do some ajax with loadUrl...
   });  
});

Tell me, is that you want or i missunderstood your question.

Arif RH
  • 155
  • 8