1

I have the following code:

<div id="left">
    <ul class="cmdSelected">
        <li class="cmdTitle">Test Case D</li>
            <li class="cmdTypeE">GPP1<span hidden>143</span></li>
            <li class="cmdTypeE">GPP2<span hidden>146</span></li>               
            <li class="cmdTypeF">UDA<span hidden>0</span></li>
            <li class="cmdTypeB">Complete<span hidden>1</span></li>
    </ul>
</div>

I want to show the value "GPP1" when I click it.

$( "li.cmdTypeE" ).on("click", function() {
    var selected = $(this).text();   //Can't work properly
});

However, it will show the value "GPP1143". What can I do to fetch the value "GPP1" only?

Eoin2211
  • 911
  • 2
  • 19
  • 39
Joey
  • 446
  • 6
  • 11

3 Answers3

0

Try the following code:

<div id="left">
    <ul class="cmdSelected">
        <li class="cmdTitle">Test Case D</li>
            <li class="cmdTypeE">GPP1<span hidden>143</span></li>
            <li class="cmdTypeE">GPP2<span hidden>146</span></li>               
            <li class="cmdTypeF">UDA<span hidden>0</span></li>
            <li class="cmdTypeB">Complete<span hidden>1</span></li>
    </ul>
</div>

JS:

$(document).ready(function() {
$( "li.cmdTypeE" ).on("click", function() {
    var selected = $(this).contents().filter(function() { return this.nodeType == 3; }).text();
    console.log(selected);
    });
});

JSFiddle: https://jsfiddle.net/Lxs210La/

Based on: https://stackoverflow.com/a/5915443/814110

Community
  • 1
  • 1
Yakiros
  • 107
  • 2
  • 2
  • 8
0

Replace this:-

 var selected = $(this).text(); 

With:-

var selected = $("#left >ul").find("li:selected").clone().children().remove().end().text();

or

var selected = $(this).clone().children().remove().end().text();

.clone() -- clone the element.
.children() -- select all the children.
.remove() -- remove all the children.
.end() -- again go back to selected element.

Sharique Ansari
  • 534
  • 5
  • 12
-2

Try This:

<div id="left">
<ul class="cmdSelected">
    <li class="cmdTitle">Test Case D</li>
        <li class="cmdTypeE" onclick="clickonthis(this)">GPP1<span hidden>143</span></li>
        <li class="cmdTypeE" onclick="clickonthis(this)">GPP2<span hidden>146</span></li>               
        <li class="cmdTypeF" onclick="clickonthis(this)">UDA<span hidden>0</span></li>
        <li class="cmdTypeB" onclick="clickonthis(this)">Complete<span hidden>1</span></li>
</ul>

on script:

function clickonthis(obj) {
    var selected = $(obj).text();
    alert(selected);  
}
  • 3
    OMG, repetitive online javascript, that's certainly not the way to go. Besides, it doesn't change anything, this doesn't work. It outputs "GPP1143" : http://jsfiddle.net/d43utya4/1/ – Jeremy Thille Apr 02 '15 at 10:08