문제

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