Selectors ignoring Ajax / Jquery loaded content - javascript

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();
}
});
});

Related

shopping card values in localstorage (js)

I made a simple shopping card store in jQuery. I am trying to make sure that after refresh my webapp, the data in the basket remains (if the data was added to the basket). I am trying to use localstorage, but I can not understand why it does not work.
$(document).ready(function()
{
$("body").on("click", ".addtobasket", function (evt) {
$("#kontener_koszyka").fadeIn();
var nazwa = $(this).closest('.produkt').find('.nazwa').text();
var cena = $(this).closest('.produkt').find('.cenaprzedmiotu').text();
var suma = 0;
var li = "<li class='produkt_w_koszyku'><b>"+nazwa+"</b> <span class='cena_w_koszyku'>"+cena+" zł</span><span style='float: right; margin-right: 30px;' class='deleteitembasket'><i class=\"fas fa-times\"></i></span></li>";
localStorage.setItem('itemlist', li);
$("#koszyk").append(li);
$("#koszyk .cena_w_koszyku").each(function()
{
suma += parseFloat($(this).text());
});
$("#cena span").text(suma.toFixed(2));
localStorage.setItem('sumalist', suma);
});
if (localStorage.getItem('itemlist') != null)
{
$("#koszyk").append(itemlist);
$("#cena span").text(sumalist.toFixed(2));
}
$(document).on('click','.deleteitembasket', function () {
$(this).closest("li").remove();
});
});

jquery- On onchange event tab content is not getting displayed properly

Below is my HTML code:
<select id="sourceNameDropdownId" label="condition " style="width:300px;">
</select>
<div id="tabs" class="selector">
</div>
Here, is my javascript code:
$("#DropdownId").change(function () {
var sid= $("#DropdownId option:selected").text();
afterclick(sid);
});
I am calling an onchange event on dropdown list, and the selected value i am passing to function afterclick
function afterclick(sid){
var tabsContainer = document.getElementById("tabs");
var crawlTab=document.createElement("ul");
//here in my actual code i am making a ajax call to fetch values for crawlList, providing static values here
var crawlList=["name1","name2","name3","name4"];
$.each(crawlList, function( index, crawlType ) {
var crawlTabElement=document.createElement("li");
crawlTabElement.innerHTML= '' +crawlType+'';
crawlTab.appendChild(crawlTabElement);
});
tabsContainer.appendChild(crawlTab);
var count=1;var tabCount=1;
$.each(crawlList, function( index, crawlType ) {
var contentCrawlTab=document.createElement("div");
contentCrawlTab.setAttribute("id",crawlType);
var p='<p>'+crawlType+'</p>';
contentCrawlTab.innerHTML=p;
tabsContainer.appendChild(contentCrawlTab);
});
$( ".selector" ).tabs();
}
This code is working fine when for the first time page gets loaded and a value is selected from the dropdown, but when i re-select value from the dropdown tabs are not getting displayed properly.
This is when i select value for the first time after page is loaded.
And when i reselect the value from dropdown its showing like this-
Is there something like reload to reload the tabs div entirely, as it seems that its appending the previous values and next time when afterclick function is called tab elements are not getting displayed properly.
I tried clearing the "tabs" div too, using **$( "#tabs " ).empty()**But it didn't worked for me.
Please help me out.
Check this working code.
$().ready(function () {
$(".selector").tabs();
$("#DropdownId").change(function () {
var sid = $("#DropdownId option:selected").text();
afterclick(sid);
});
});
function afterclick(sid) {
var tabsContainer = document.getElementById("tabs");
tabsContainer.innerHTML = '';
var crawlTab = document.createElement("ul");
//here in my actual code i am making a ajax call to fetch values for crawlList, providing static values here
var crawlList = [sid + "1", sid + "2", sid + "3", sid + "4"];
$.each(crawlList, function (index, crawlType) {
if (crawlType != null) {
var crawlTabElement = document.createElement("li");
crawlTabElement.innerHTML = '' + crawlType + '';
crawlTab.appendChild(crawlTabElement);
}
});
tabsContainer.appendChild(crawlTab);
var count = 1; var tabCount = 1;
$.each(crawlList, function (index, crawlType) {
if (crawlType != null) {
var contentCrawlTab = document.createElement("div");
contentCrawlTab.setAttribute("id", crawlType);
var p = '<p>' + crawlType + '</p>';
contentCrawlTab.innerHTML = p;
tabsContainer.appendChild(contentCrawlTab);
}
});
$(".selector").tabs('destroy');
$(".selector").tabs();
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<select id="DropdownId" label="condition " style="width:300px;">
<option selected="selected" disabled="disabled">--Select--</option>
<option>Bilna-ID</option>
<option>IndiatimesShopping</option>
</select>
<div id="tabs" class="selector">
</div>

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.

Display selected radio button value on the panel title

I want to display the selected radio button value on a panel title.
This is my js file
$(document).ready(function(){
$(".child_option_radio").on("change", function(){
elem = $(this);
if ($(this).is(':checked'))
{
alert($(this).val());
}
$("#part_child_" + elem.attr("data-option-subid")).html(e);
alert("#part_child_" + elem.attr("data-option-subid"));
});
My part_child.erb file
<div class="row">
<%= options_radio_tag part_child, class: "child_option_radio", "data-option-subid" => part_child.id, "data-option-name" => part_child.name %>
</div>
This is my helper file for option_radio_tag for part child
def options_radio_tag(part_child)
html = ""
attr_name = "order[part][#{part_child.parent.id}][children][][part] [#{part_child.id}][option][][id]"
part_child.options.each do |o|
html += "<div class='col-sm-2'>"
html += label_tag "#{attr_name}", raw("<input id='order_part_#{part_child.id}_option_#{o.id}', data-option-subid='option_subid_#{o.id}', data-option-name='#{o.name}', name='#{attr_name}' type='radio' value='#{o.id}' #{o.is_default? ? 'checked' : ''} data-option-subid='option_subid_#{o.id}'> #{o.name}")
html += "</div>"
end
html.html_safe
end
Please let me know If you need any more details.
PS: With the above code I am getting this
wrong number of arguments (2 for 1)
You are trying to use a variable e which is not present in the handler method
$(document).ready(function () {
$(".child_option_radio").on("change", function () {
var elem = $(this);
if (this.checked) {
$("#part_child_" + elem.attr("data-option-subid")).html(this.value);
}
});
});
$(document).ready(function(){
$(".child_option_radio").on("change", function(){
elem = $("input[type=radio]:checked.child_option_radio");
alert(elem.val()); // Will give you the value of selected radio button
$("#part_child_" + elem.attr("data-option-subid")).html(elem.val());
});

jQuery error, only with Explorer

I have a custom jQuery script that works fine in all bowsers but one (Explorer 6, 7, 8?).
The purpose of the code is to allow a user to add multiple form fields to their form (if the user want more than one phone number or more than one web address).
It is written so that any "A" tag with a class containing "add" is bound to the jQuery function.
The error I am getting is as follows:
///////////////////////////////
Line: 240
Char: 5
Error: 'this.id.3' is null or not an object
Code: 0
///////////////////////////////
HTML of form:
(please note that I am aware that the form tags are not here, this is a small portion of a larger form.
<ul>
<li>
<ul>
<li class="website">
<input id="website1_input" name="website[1][input]" type="text" value="www.test.org"/>
<input type="checkbox" id="website1_delete" name="website[1][delete]" class="element radio" value="1" />
<label for="website1_delete">Delete</label>
</li>
</ul>
add another website
</li>
</ul>
And now the jQuery:
There should be on a page a ul containing at least one li.
All the lis should have a certain class like "phone" or "address"
After the /ul There should be a link with a matching id, like
"addPhone" or "addAddress". The href attribute should be "#".
function makeAddable(theClass) {
$('#add' + theClass[0].toUpperCase() + theClass.substr(1)).click(function() {
var numItems = $('.' + theClass).length;
var newItem = $('.' + theClass).eq(numItems - 1).clone();
newItem.find('input[type=text]').val('');
numItems++; // number in the new IDs
// keep ids unique, linked to label[for], and update names
// id & for look like: phone1_type, phone1_ext, phone13_p1, etc.
// names look like: phone[1][type], phone[1][ext], phone[13][p1], etc.
newItem.find('[id^=' + theClass + ']').each(function(i) {
var underscoreIndex = this.id.indexOf('_');
var idNum = this.id.substring(theClass.length, underscoreIndex);
this.id = this.id.replace(idNum, numItems);
});
newItem.find('[for^=' + theClass + ']').each(function(i) {
var jqthis = $(this);
var forAttr = jqthis.attr('for');
var underscoreIndex = forAttr.indexOf('_');
var idNum = forAttr.substring(theClass.length, underscoreIndex);
forAttr = forAttr.replace(idNum, numItems);
jqthis.attr('for', forAttr);
});
newItem.find('[name^=' + theClass + ']').each(function(i) {
var jqthis = $(this);
var nameAttr = jqthis.attr('name');
var bracketIndex = nameAttr.indexOf(']');
var idNum = nameAttr.substring(theClass.length + 1, bracketIndex);
nameAttr = nameAttr.replace(idNum, numItems);
jqthis.attr('name', nameAttr);
});
$(this).prev('ul').append(newItem);
return false;
});
}
// Automatically enable all <a href="#" id="addSomething"> links
$(function() {
$('a[href=#][id^=add]').each(function(i) {
makeAddable( this.id[3].toLowerCase() + this.id.substr(4) );
});
});
this.id.charAt(3).toLowerCase()
Change this...
this.id[3]
To this...
this.id.substr(3, 1);
Something like this will achieve the same affect but makes greater use of jquery, thereby avoiding the crossbrowser compatibility problems so common with javascript:
function addInput(inputType) {
var items, itemNumber, lastItem, newListItem, parentList, inputName, inputId, deleteId, thisId;
items = $('li.' + inputType);
itemNumber = items.length + 1;
lastItem = $(items[itemNumber-2]);
newListItem = lastItem.clone();
parentList = lastItem.parents('ul:first');
inputId = inputType + itemNumber + '_input';
deleteId = inputType + itemNumber + '_delete';
$(':input', newListItem).each(function() {
inputName = $(this).attr('name').replace(/\[\d*\]/, '['+itemNumber+']');
thisId = $(this).attr('id').match(/_delete/) ? deleteId : inputId
$(this)
.val('')
.removeAttr('checked')
.attr('id', thisId)
.attr('name', inputName)
}).end()
.find('label').attr('for', deleteId).end()
.appendTo(parentList)
;
}
$(function() {
$('a[href=#][id^=add]').live('click', function() {
addInput(this.id.substr(3).toLowerCase());
});
});

Categories