Is there something wrong with this jQuery?
Is there something wrong with this javascript and HTML? I am trying to make it so that when one of the .tagSuggestTag
are clicked its value is inserted into the <input>
, but for some reason it does nothing at all.
Javascript:
$('.tagSuggestTag').click(
function(){
var currentTags = $('#testTags').val();
var selectedTag = $(this).html();
if (currentTags == "") {
currentTags = selectedTag;
} else {
currentTags = currentTags + ", " + selectedTag;
}
$('#testTags').val(currentTags);
});
HTML:
<input type="text" id="testTags">
<ul>
<li class="tagSuggestTag">test</li>
<li class="tagSuggestTag">test2</li>
<li class="tagSuggestTag">test3</li>
</ul>
UPDATE: See full HTML here: http://pastebin.com/NyCz669u
I figured out what was wrong, I didn't say that the content in the <ul&开发者_StackOverflow中文版gt;
was added by AJAX so I had forgot I needed to pass the click
throught .live()
Nothing wrong, the code works just great.
Make sure you wrap it in a $(document).ready
:
$(function() {
$('.tagSuggestTag').click(function() {
var currentTags = $('#testTags').val();
var selectedTag = $(this).html();
if (currentTags == "") {
currentTags = selectedTag;
} else {
currentTags = currentTags + ", " + selectedTag;
}
$('#testTags').val(currentTags);
});
});
Chromedude: Make sure you're properly importing jQuery. Your code seems to work, look here:
http://jsfiddle.net/UqkKY/
Good luck, Amit
The error must be somewhere else, your code works great : http://jsfiddle.net/C9WQ5/
There doesnt seem to be anything wrong with the JQuery code that you have presented. you just need to include $(document).ready() for initialization.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.tagSuggestTag').click(function () {
var currentTags = $('#testTags').val();
var selectedTag = $(this).html();
if (currentTags == "") {
currentTags = selectedTag;
} else {
currentTags = currentTags + ", " + selectedTag;
}
$('#testTags').val(currentTags);
});
});
</script>
Regards, Junaid Mufti PioneeringDev
精彩评论