问题
I am trying to create a web page where
- if a user clicks on a word it is presented in a text box
- if a word is clicked twice it does not appear again in the box
- the user can clear the box with a button
- the user can send the contents to another page
my code is the following:
<div id="parent">
<!-- get the clicked word and add it to textarea-->
<script type="text/javascript">
$("#parent").delegate("span", "mousedown", function() {
if ( $("#thediv").text().indexOf($(this).text()) <0 )
{
$("#thediv").append($(this).text());// get old div contents and add clicked word
$("#thediv").append(' ');// also add a space
$("#thediv").html(); //print to div
};
})
</script>
<!-- clickable words -->
<span>One </span><span>Two</span><span>Three</span>
<!-- the form -->
<form action="/test/index6.html" method="get">
<textarea id="thediv" name="thediv"></textarea><br>
<input type="submit" >
</form>
<!-- Clear button -->
<input type="button" id="clear" value="Clear" />
<script type="text/javascript">
$('#clear').click(function (){
$("#thediv").val('');
});
</script>
</div>
it works fine, on mouseclick the word that is clicked is stored (if it is positioned between a tag. for each word that is clicked, I check if the text area already contains it and if not i add it.
My problem is with the clear button. it clears the text area but then I cannot add any more words, as if this part of the code stops working.
Any advice?
回答1:
Try changing $("#thediv").val('');
to $("#thediv").html('');
, as in this jsfiddle.
来源:https://stackoverflow.com/questions/19577602/clear-button-empties-textarea-but-i-cannot-repopulate-it