简体   繁体   中英

Jquery - On input, Get the value of a span inside a td using span class

I am trying to get the value of a spam changed by the user (using contenteditable), through its class. The spam is inside a <td> in a table.

I tried let newItemName = $(variantId).children(".item-description").text(); and also let newItemName = $(variantId).find('span.item-description').text(); which both return an empty string to newItemName variable.

Any ideas why I'm getting an empty string instead of the users input?

This is my JS:

let variantId;
$(document).on('click', ".tbl-itemClass", function () {
    variantId = $(this).attr('id');
    $(variantId).prop('contenteditable', true);

}).
    on('input', function () {
        //let newItemName = $(variantId).children(".item-description").text();
        let newItemName = $(variantId).find('span.item-description').text();
    });

This is my .csHtml (don't think it makes a difference, I'm using razor page, Asp.Net)

<tbody>
@foreach (var item in Model)
{
    <tr currentitemid=" @item.Id">
        <td class="tbl-itemClass desc" id="@("description"+ item.Id)" varianttype="@ViewBag.VariantType" >
            <span class="spnSpc">&nbsp;&nbsp;&nbsp;</span>
            <span style="width:90%; padding:1px 5px 1px 2px;" **class="item-description"** contenteditable> @item.Description </span>
        </td>
        
        <td class="tbl-itemClass ">//more code here
        </td>
    </tr>
}

@item.Description s value is a color (ie: 'red'). When the user changes that value (ie: 'redX'), this code runs, but returns an empty string instead of 'redX'. Thanks!

You select the element again with the variantId variable. But that is only a string and won't select the element, because the string doesn't contain the # when selecting elements with an id.

variantId = '#'+$(this).attr('id');

Now variantId will be #+your_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM