2016-08-21 16 views
0

<ul>タグ内に単語のリストがあります。ユーザーが<li>要素をクリックすると、そのliの単語をテキストエリアに追加しようとしています。単語が正しく追加されますが、ユーザーが同じ<li>要素をクリックした場合、その単語をテキストエリアから削除しようとしています。文字列のjQueryをクリックして、テキストエリア内で一致するテキストを追加または削除します

<ul> 
     <li>Word One</li> 
     <li>Word deux</li> 
     <li>Other Word three</li> 
     <li>yet another Word 4</li> 
    </ul> 

    <textarea id="list" rows="4" cols="20"></textarea> 

jQueryの

jQuery(document).ready(function() { 

// removing the textarea value when window is loaded again 
// otherwise for some reason all the values entered before are still there ? 

jQuery(window).load(function() { 
    jQuery('#list').val(''); 
}) 

jQuery('ul li').click(function(addWord) { 

    var choice = jQuery.trim($(this).text()); 
    var textArea = jQuery("#list"); 

    // if the <li> with the word was allready clicked, then remove its "selected" class 
    if (jQuery(this).hasClass('selected')) { 
     jQuery(this).removeClass('selected'); 

     //textArea.replace(choice,''); 

    } else { 
     // add class selected to the clicked <li> word, add the word to the textarea 
     jQuery(this).addClass('selected'); 
     textArea.val(textArea.val() + choice + ' , ').text(textArea.val()); 
    } 
}); 
} 

答えて

1

あなたはselectedクラスを削除するときにテキストを交換する必要があります。ここでは.val(function)が使用されます。

jQuery(document).ready(function() { 
 

 
    jQuery('ul li').click(function(addWord) { 
 

 
    var choice = jQuery.trim($(this).text()); 
 
    var textArea = jQuery("#list"); 
 

 
    // if the <li> with the word was allready clicked, then remove its "selected" class 
 
    if (jQuery(this).hasClass('selected')) { 
 
     jQuery(this).removeClass('selected'); 
 

 
     textArea.val(function(_, val) { 
 
     return val.replace(choice + ' , ', ''); 
 
     }); 
 
    } else { 
 
     // add class selected to the clicked <li> word, add the word to the textarea 
 
     jQuery(this).addClass('selected'); 
 
     textArea.val(function(_, val) { 
 
     return val + choice + ' , '; 
 
     }); 
 
    } 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<ul> 
 
    <li>Word One</li> 
 
    <li>Word deux</li> 
 
    <li>Other Word three</li> 
 
    <li>yet another Word 4</li> 
 
</ul> 
 

 
<textarea id="list" rows="4" cols="20"></textarea>

+0

今期待通りに働いて、ありがとうございました。私はあなたのコードをもっと詳しく調べます、特に 'val(function()'の部分です。もう一度Satpalに感謝します。 – mlclm

関連する問題