This will be probably dummy question but I cannot find solution for that.

We have piece of code:

<script type="text/javascript">
        $(function() {
            $('.tags_select a').click(function() {
                var value = $(this).text();
                var input = $('#text_tag_input');
                input.val(input.val() + value + ', ');
                return false;
            });
        });
</script>

and HTML:

<input id="text_tag_input" type="text" name="tags" />

<div class="tags_select">
<a href="#">text1</a>
<a href="#">text2</a>
<a href="#">text3</a>
</div>

the issue is following - when I click on link text1, and then text2 etc. everything appears in input. What I want to achieve is to display only one variable (in this case, newest, last cliked).

thanks!

有帮助吗?

解决方案

This should work for you

<script type="text/javascript">
    $(function() {
        $('.tags_select a').click(function() {
            $('#text_tag_input').val("");
            var value = $(this).text();
            var input = $('#text_tag_input').val(value);
            return false;
        });
    });
</script>

<input id="text_tag_input" type="text" name="tags" />
<div class="tags_select">
  <a href="#">text1</a>
  <a href="#">text2</a>
  <a href="#">text3</a>
</div>

其他提示

Use:

input.val(value);

instead of:

input.val(input.val() + value + ', ');
input.val(input.val() + value + ', ')

What that does is set the value of your input = (input's current value + clicked value + ',')

input.val(value)

The code above simply sets the input value to the clicked value.


However, if you do not wish to remove anything in your code, you can just add

input.val('') before you call input.val(input.val() + value + ', ').

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top