Home > Software engineering >  jQuery attr() Method add html tag
jQuery attr() Method add html tag

Time:11-14

I have a search input tag, and I wanted to set a placeholder. In place holder I need to keep a magnify icon, how to do it in jquery? below is the code I tried

$('.gridjs-head .gridjs-search .gridjs-search-input').attr("placeholder", "<i class='mdi mdi-magnify'></i>&nbsp;Search...")

I needed to use this path because I'm using grid.js to render table in my django project

CodePudding user response:

Please try below code:

$('.gridjs-head .gridjs-search .gridjs-search-input').attr("placeholder", $.parseHTML("&#61442;")[0].data);

CodePudding user response:

Since you cannot include html code inside a placeholder attribute you can't use the css class strategy to style its text.

Using the unicode character sequence it's the key.

I showed in this demo two ways to embed it inside the placeholder attribute:

  • defined in the html as &#xf0349;
  • set via javascript converting the unicode to string before composing the string

When bypassing the css class strategy, you are expected to set the font-family as Material Design Icons that I did defining a rule for input::placeholder.

This demo uses the input element test that the javascript retrieves using the id selector. You should just replace it with your selector .gridjs-head .gridjs-search .gridjs-search-input but since I used vanilla js instead of jQuery, it would require you to loop for each element returned in the collection before invoking .setAttribute()

const toBaseDecimal = parseInt("f0349", 16);
const toString = String.fromCodePoint(toBaseDecimal);
document.getElementById('test').setAttribute("placeholder", `${toString} Search`);
input::placeholder {    
    opacity: .5;
    color: red;    
    padding-left: 10px;    
    font-family: "Material Design Icons";
}

div{
  margin-bottom: 1rem;
}
<link href="//cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
  <label for="test">This placeholder was set with javascript:</label>
  <br>  
  <input type="text" id="test">  
</div>

<div>
  <label for="test2">This placeholder was set via html:</label>
  <br>
  <input type="text" id="test2" placeholder="&#xf0349; Search">  
</div>

<div>
  <label for="test3">This is the icon via css:</label>
  <br>
  <i class='mdi mdi-magnify'></i>
</div>

  • Related