1

I'd love to replace a number of placeholder texts dynamically using javascript. Tried to use jquery filter and contain selector but didn't really get anywhere. Do you have an idea how these could be replaced?

<div class="container">
<h1>$$Insert text here$$</h1>
<div>
    <p>My first paragraph.</p>
    <div>$$Insert text here$$</div>
    <div>
        <input type="text" name="lname" placeholder="$$Insert text here$$"><br>
        <p>Here some other text</p>
    </div>
</div>

1
  • 2
    Why don't you use an existing template engine? Commented Nov 22, 2013 at 21:51

3 Answers 3

1

A simple example assuming if you have only one kind of place holder for study purpose:

var container = $('.container');
container.html(container.html().replace(/\$\$Insert text here\$\$/g,'mytext'))

demo: http://jsfiddle.net/Pqpfa/2/


If you are trying to implement your own template engine, here is a bit more complex example where you can have different placeholder names:

html:

<div class="container">
<h1>$$pageTitle$$</h1>
<div>
    <p>My first paragraph.</p>
    <div>$$inputName$$</div>
    <div>
        <input type="text" name="lname" placeholder="please enter $$inputName$$"><br>
        <p>Here some other text</p>
    </div>
</div>

js:

var myClass = {};
myClass.pageTitle = 'my awsome page title';
myClass.inputName = 'your name';

var replaceFunc = function(match,p1){
    if (myClass[p1]){
        return myClass[p1]
    }
}

var container = $('.container');
container.html(container.html().replace(/\$\$(.*)\$\$/g, replaceFunc))

demo: http://jsfiddle.net/kQH5F/1/

Sign up to request clarification or add additional context in comments.

Comments

0

It is better to use a template engine but you can acheve this even using pure JS

document.body.innerHTML = document.body.innerHTML.replace(new RegExp('\\$\\$Insert text here\\$\\$','g'), 'replace it with');

Demo http://jsfiddle.net/tp9NY/

Comments

0

Here is a little practical example, You could basically pass any model:

 <div class="container">
 <h1>Hi $$fname$$ $$lname$$</h1>
 <div>
 <p>My first paragraph.</p>
 <div>You are the <b>$$title$$</b> of <b> $$company$$ </b></div>
 <div>
  <input type="text" name="lname" placeholder="$$salary$$"><br/>
    <p>Call us at $$phone$$</p>
</div>
</div>


 var myobj = {
  fname: 'Alex',
  lname: 'Shilman',
  title: 'CEO',
  company: 'Interactive Aim',
  phone: '(111)111-1111',
  salary: 10000000
  },
 makeView = function(myobj){
  for (var key in myobj){
   $('div.container').html($('div.container').html().replace('$$'+key+'$$',    myobj[key]));
  }
 };  

  makeView(myobj);

JSBin working example: http://jsbin.com/Oforipom/2/edit

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.