$ (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>
Run codeHide result

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

+4
source share
4 answers

Use jQuery( html, attributes )to create HTML elements, this will save you from the mess of quotes and potential problems.

$('.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>
Run codeHide result
+5
source

Your attribute values ​​arent quoted, so they end in space. Hashes are half the battle:

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

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

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

:

$('.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>
<li class="ed_name">Akshay Verma(Aks)</li>
Hide result
+1

Your code works exactly as it should. $('.ed_name')refers to the list item ( <li></li>), and .text()-Akshay Verma(Aks)

0
source

Source: https://habr.com/ru/post/1675152/


All Articles