Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(this).text() excludes text after space

$('.ed_name').replaceWith(function() {
  return '<input placeholder=' + $(this).text() + ' value=' + $(this).html() + ' class="ed_inp">'
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="ed_name">Akshay Verma(Aks)</li>
</ul>

It returns only "Akshay" not "Akshay Verma(Aks)". I tried .html() method also. can anyone answer why this is happening??

like image 498
Rutuja Kurle Avatar asked Feb 05 '23 15:02

Rutuja Kurle


2 Answers

Use jQuery( html, attributes ) to create HTML elements, it will save you from quotes mess and potential issues.

$('.ed_name').replaceWith(function() {
  return $('<input />', {
    "placeholder": $(this).text(),
    "value": $(this).html(),
    "class": "ed_inp"
  });

  //'<input placeholder="' + $(this).text() + '" value="' + $(this).html() + '" class="ed_inp">'
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="ed_name">Akshay Verma(Aks)</li>
</ul>
like image 102
Satpal Avatar answered Feb 07 '23 13:02

Satpal


Your attribute values aren’t quoted, so they’ll end at a space. Here’s half a fix:

$('.ed_name').replaceWith(function () {
    return '<input placeholder="'+$(this).text()+'" value="'+$(this).html()+'" class="ed_inp">'
});

but the right way is to create an element, not HTML:

$('.ed_name').replaceWith(function () {
    return $('<input />', {
        placeholder: $(this).text(),
        value: $(this).html(),
        class: 'ed_inp',
    });
});
like image 38
Ry- Avatar answered Feb 07 '23 12:02

Ry-