428

How to set a value for a <span> tag using jQuery…

For example…

Below is my <span> tag:

<span id="submittername"></span>

In my jQuery code:

jQuery.noConflict();
    
jQuery(document).ready(function($){

    var invitee = $.ajax({
        type: "GET",
        url: "http://localhost/FormBuilder/index.php/reports/getInvitee/<?=$submitterid;?>",
        async: false
    }).responseText;

    var invitee_email=eval('(' + invitee + ')');
    var submitter_name=$.map(invitee_email.invites, function(j){ 
        return j.submitter;
    });         
    alert(submitter_name); // alerts correctly 
    $("#submittername").text(submitter_name); //but here it is not working  WHy so??????
});
robyaw
  • 2,274
  • 2
  • 22
  • 29
useranon
  • 29,318
  • 31
  • 98
  • 146

6 Answers6

849

You can do:

$("#submittername").text("testing");

or

$("#submittername").html("testing <b>1 2 3</b>");
cletus
  • 616,129
  • 168
  • 910
  • 942
  • 3
    what is the difference between .text and .html ? – ZaidRehman Jan 11 '18 at 11:56
  • 5
    @Zaid `.text()` will escape any HTML characters so that it can be displayed as text. Use `.html()` if you're inserting HTML code that you want the browser to render. More info: http://api.jquery.com/text/#text2 – Gabriel Luci Apr 18 '18 at 15:07
21

You are using jQuery(document).ready(function($) {} means here you are using jQuery instead of $. So to resolve your issue use following code.

jQuery("#submittername").text(submitter_name);

This will resolve your problem.

oers
  • 18,436
  • 13
  • 66
  • 75
17

You're looking for the wrong selector id:

 $("#submitter").text(submitter_name);

should be

 $("#submittername").text(submitter_name);
Steerpike
  • 17,163
  • 8
  • 39
  • 53
9

You can use this:

$("#submittername").html(submitter_name);
Rita Chavda
  • 191
  • 2
  • 16
8

Syntax:

$(selector).text() returns the text content.

$(selector).text(content) sets the text content.

$(selector).text(function(index, curContent)) sets text content using a function.

Source: https://www.geeksforgeeks.org/jquery-change-the-text-of-a-span-element/

NthDeveloper
  • 969
  • 8
  • 16
E Demir
  • 81
  • 1
  • 2
6

The solution that work for me is the following:

$("#spanId").text("text to show");
Jorge Santos Neill
  • 1,635
  • 13
  • 6
  • For me it worked just like -> $('.className').text('some text') // span $('.className').val('some text') // input $('.className').html('some text') // div $('.className').val('some text') // input – AllanRibas Jan 19 '22 at 05:28