Is there something wrong with this jQuery? - javascript

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> 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

Related

javascript variables in jquery selectors not working

I am trying to bring the variable name inside the selectors, but its not working,
here is the code, from where I have taken the example
How to use javascript variables in jquery selectors
and here is my code
$(document).ready(function() {
//var detail = sample.one;
var detail = sample;
$('#' + detail).click(function() {
});
});
you need to put the value between " because you want to store a string in your variable.
var detail = "sample"
Try this:
$(document).ready(function() {
var detail = 'sample';
$('#' + detail).click(function() {
});
});
$(document).ready(function() {
//var detail = sample.one;
var detail = 'sample';
$('#' + detail).click(function() {
});
});
<input type="button" id="sample" />
This is working.
sample is a string so use "
create a variable with string value for example
var detail = 'sample';

Jquery Click send doesn't work

Hi everyone i have one question about jquery click send function. I have created this demo from jsfiddle. So if you visit the demo then you can see there is one smiley and textarea. When you write some text and press enter then the message sending successfully. But i want to add also when you click the smiley then it need to send (w1) from the image sticker="(w1)" like click to send. But click send function doesn't work. What is the problem on there and what is the solution ? Anyone can help me in this regard ?
JS
$('.sendcomment').bind('keydown', function (e) {
if (e.keyCode == 13) {
var ID = $(this).attr("data-msgid");
var comment = $(this).val();
if ($.trim(comment).length == 0) {
$("#commentload" + ID).text("Plese write your comment!");
} else {
$("#commentload" + ID).text(comment);
$("#commentid" + ID).val('').css("height", "35px").focus();
}
}
});
/**/
$(document).ready(function() {
$('body').on("click",'.emo', function() {
var ID = $(this).attr("data-msgid");
var comment = $(this).val();
if ($.trim(comment).length == 0) {
$("#commentload" + ID).text("nothing!");
} else {
$("#commentload" + ID).text(comment);
$("#commentid" + ID).val('').css("height", "35px").focus();
}
});
});
$('body').on('click', '.sm-sticker', function(event) {
event.preventDefault();
var theComment = $(this).parents('.container').find('.sendcomment');
var id = $(this).attr('id');
var sticker = $(this).attr('sticker');
var msg = jQuery.trim(theComment.val());
if(msg == ''){
var sp = '';
} else {
var sp = ' ';
}
theComment.val(jQuery.trim(msg + sp + sticker + sp));
});
HTML
<div class="container one">
<div class="comments-area" id="commentload47">comments will be come here</div>
<div class="user-post" id="postbody47">
<textarea class="sendcomment" name="comment" id="commentid47" data-msgid="47"></textarea>
<div class="stiemo">
<img src="http://d.lanrentuku.com/down/png/1009/networking/emoticon_inlove.png" class="sm-sticker emo" sticker="(w1)"> click smiley to send (w1)</div>
</div>
</div>
</div>
try this :
just append below JS after the line theComment.val(jQuery.trim(msg + sp + sticker + sp));
var e = $.Event("keydown");
e.keyCode = 13; // # Some key code value
$('.sendcomment').trigger(e);
Demo
you should use this:
$('body').on("click",'.emo', function() {
var ID = $('.sendcomment').attr("data-msgid");
var comment = $('.sendcomment').val();
if ($.trim(comment).length == 0) {
$("#commentload" + ID).text("nothing!");
} else {
$("#commentload" + ID).text(comment);
$("#commentid" + ID).val('').css("height", "35px").focus();
}
});
so basically instead of this you have to use input and get msgid and val from there, use same approach for rest.
So when you are attaching event on some button and you want to use data from some other dom element you have to get that element by using $(selector) under your delegated function, really simple approach.

Selectors ignoring Ajax / Jquery loaded content

I'm working with a static json file. I'm using jquery to load my file into my store.
Everything loads fine.
At the side of my store, I have a categories menu, where I can filter my store items.
Because my store is items are dynamically generated, I dont seem to be able to select them with jquery.
Here is the ajax request:
<script>
$(function () {
var actionUrl = '#Url.Action("Items", "Home")';
$.getJSON(actionUrl, displayData);
function displayData(response) {
if (response != null) {
for (var i = 0; i < response.length; i++) {
$("#store").append("<div class='storeItem' data-price=" + response[i].PriceScale + " data-category=" + response[i].Cat + "> <img src='#" + response[i].Cat + "' class='itemImage' alt='" + response[i].Title + "'/><span class='itemTitle'>" + response[i].Title + "</span><span class='itemDesc'><p>" + response[i].Desc + "</p></span><span class='itemPrice'>"+ response[i].Price +"</span><a href='#' class='add2cart'>ADD TO CART</a>")
}
}
else {
$("#store").append("<h5>There was a problem loading the store content.</h5>");
}
}
});
</script>
Here is the code I have tride:
<script>
$(function () {
$( "nav#catagories ul li input").on("click", function () {
var a = $(this).prop("checked");
var b = $(this).attr("id");
if (a == true) {
$("div.storeItem").hide();
$(".storeItem").data("category", b).show();
}
});
});
</script>
I've also tried:
<script>
$(function () {
$(document).on("click","nav#catagories ul li input", function () {
var a = $(this).prop("checked");
var b = $(this).attr("id");
if (a == true) {
$("div.storeItem").hide();
$(".storeItem").data("category", b).show();
}
});
});
</script>
In both cases the script works up untill the div.storeItem hide.
Here is the HTML that is outputed:
<div class="storeItem" data-price="med" data-category="apparel">
<img src="#apparel" class="itemImage" alt="Shirt">
<span class="itemTitle">Shirt</span>
<span class="itemDesc">
<p>A Beatiful Shirt</p>
</span>
<span class="itemPrice">23.45</span>
ADD TO CART
</div>
Maybe your problem doesn't have to do anything with items being dynamically generated. Here $(".storeItem").data("category", b).show(); you are replacing category value with value stored in b, while it seems you want to select those which has category equal to b.
Maybe this will work or at least give you the direction:
$(function () {
$(document).on("click", "nav#catagories ul li input", function () {
var checked = $(this).prop("checked");
var category = $(this).attr("id");
if (checked) {
$(".storeItem").hide()
.filter(function () {
return $(this).data("category") === category;
}).show();
}
});
});

Attribute "src" contains zero on the left Image

I am having a little bit of trouble with the src on this code:
A event updates the src that depends on a variable collected from the form, then the those .jpg´s can't be name changed so I need to stick with that. The problem is all of their names are in numbers and also some of them start with a zero, so using attr from string is not working properly:
var newSrc = "http://charal.unacar.mx/fotos/" +credencial+ ".jpg";
$('#foto').removeAttr("src")
$('#foto').attr('src', newSrc);
This credential would work: ######
This credential would not: 0#####
Where lays my problem?
i have one example for you might it will help you. This is not the exact code but by checking this you can do what you want.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('li[id^="step"]').click(function(){
var imagepath = jQuery(this).attr('dir');
jQuery('#ImageDiv').find('img').attr('src',imagepath);
});
});</script>
<style>
li{ cusrsor:pointer; padding:10px; }
</style>
<li id="step1" dir="images1.jpg">Step1</li>
<li id="step2" dir="images2.jpg">Step2</li>
<li id="step3" dir="images3.jpg">Step3</li>
<li id="step4" dir="images4.jpg">Step4</li>
<li id="step5" dir="images5.jpg">Step5</li>
<div id="ImageDiv"><img src="images1.jpg"></div>
weird thing it started working by it self this morning i don't know what i did, thank you for your help , the working code is this:
$("#credencial").keyup(function(e) {
if ($("#credencial:focus") && (e.keyCode === 13)) {
var credencial = $("#credencial").val();
console.log("\n credencial " + credencial);
$(':input', '#frm')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
$.post("http://localhost/Aplicaciones%20con%20bases%20de%20datos/consulta.php", {
credencial: credencial
}, function(json) {
$('#matricula').val(json.matricula);
$('#des').val(json.des);
$('#carrera').val(json.carrera);
$('#nombre').text(json.nombre + " " + json.apellido);
//var newSrc = "background:url('http://charal.unacar.mx/fotos/"+json.matricula+".jpg'); background-size:300px;";
var newSrc = "http://charal.unacar.mx/fotos/" +credencial+ ".jpg";
$('#foto').removeAttr("src")
$('#foto').attr('src', newSrc);
},
"json");
}
});

How to bind JavaScript result to a div on my page?

i have a java script file that it's output is a table with some information.
i want to show this result in one of my DIVs in my page but the result of function,placed at top of my page's Header!
What can i do to fix this?
this is end of my java script file ,in fact this is its output
' document.write("")
document.write(" اوقات شرعی کلیه شهر ها ")
document.write("")
document.write(" ")
document.write(" اذان صبح طلوع خورشید اذان ظهر غروب خورشید اذان مغرب")
document.write(" اوقات به افق : انتخاب شهراراکاردبیلارومیهاصفهاناهوازایلامبجنورد بندرعباسبوشهربیرجندتبریزتهرانخرم آبادرشتزاهدانزنجانساریسمنانسنندجشهرکردشیرازقزوینقمکرمان کرمانشاهگرگانمشهدهمدانیاسوجیزد ")
document.write("") '' and this is its call at the and of my master page '
$(document).ready(function ogh() {
var CurrentDate = new Date();
var JAT = 1;
function pz() { };
init(); document.getElementById("cities").selectedIndex = 12;
coord(); main();
});
$(document).ready(function () {
$("#oghatSharii").append(ogh());
});
</script>
</form>
'
if you could't understand top of my code,,its output is a table
You can set the HTML of the div using jquery in the ready event like follows:
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
....
<script type="text/javascript">
$(document).ready(function () {
$("#myDiv").append(pz());
});
function pz() {
// do here something useful and return the text you want to add to the div
return "Hello there =) !!!";
};
</script>
<div id="myDiv"></div>
Don't forget to install jquery:
https://nuget.org/packages/jQuery
i use this
function ogh()
{
var CurrentDate = new Date();
var JAT = 1;
function pz() { };
init(); document.getElementById("cities").selectedIndex = 12;
coord(); main();
}
$(document).ready(function () {
$("#oghatSharii").append(ogh());
});
but i got an error : one of my functions could't access to oits data
Some steps
Move your JavaScript code at the bottom of the page.
Make use of innerHTML (basic JavaScript) or html() (jQuery) to add so.

Categories