With present code, data-endpoint path changing as
data.15435.json?parameter=test
data.13588.json?parameter=test?parameter=test
data.15435.json?parameter=test?parameter=test?parameter=test
On each change, parameter is appending. But, need to include this parameter only once.
$('a.dropdown-item').on('click', function(){
let getDataKey = $(this).attr('data-key');
let getEndPoint = $('.detail.component').attr('data-endpoint');
var getEndPointVal = getEndPoint.replace(/[.0-9]*\.json/, '.' + getDataKey + '.json');
var getEndPointValParam = getEndPointVal + '?parameter=test';
var getJsonUrl = $('.detail.component').attr('data-endpoint', getEndPointValParam);
let getNewDataKey = getJsonUrl;
console.log(getJsonUrl)
}
<div class="detail component" data-endpoint="detail.json">
..
</div>
<div class="dropdown start-date">
<button id="startdate" type="button" class="btn btn-outline-dark">List 1</button>
<div class="dropdown-menu">
<a type="button" data-key="15435" class="dropdown-item">List 1</a>
<a type="button" data-key="13588" class="dropdown-item">List 2</a>
</div>
</div>
The only way how i can see, is to set the data-endpoint to be a permanent or constant. Try this:
let getEndPoint = $('.detail.component').attr('data-endpoint');
$('a.dropdown-item').on('click', function(e){
e.preventDefault();
let getDataKey = $(this).data('key');
var array = getEndPoint.split('.'); //now it is an array
var getEndPointVal = array[0] + '.' + getDataKey + '.' + array[1];
var getEndPointValParam = getEndPointVal + '?parameter=test';
$('.detail.component').data('endpoint', getEndPointValParam);
var getJsonUrl = $('.detail.component').data('endpoint');
console.log(getJsonUrl);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="detail component" data-endpoint="detail.json">
</div>
List 1
List 2
Related
This is probably going to be marked as a duplicate because there are so many SO questions about this already, but I'm just unable to apply those questions answers onto my code.
I am using Razor, html, css, and javascript in my Blob storage page code.
On the left side in the image below there are three containers. When clicking on one of them they are to open up and show all their children (blobs). The first time I click one of the containers only one of the function calls run (listContainerBlobs()) and it is not the one opening the container up (showHide()).
Below is the html p-tag calling the functions onclick.
<p class="blob-container" onclick="showHide('#containerId', '#arrowId');listContainerBlobs('#jsonBlob', '#container.Name');"><i class="fa fa-caret-right" id="#arrowId"></i> #container.Name</p>
The full div with C# and razor:
<aside class="aside">
<div class="aside-header">
<i class="fa fa-plus add-container-button aside-header-icons" onclick="addContainer()"></i><i class="fa fa-search search-button aside-header-icons"></i>
<input id="searchBox" type="text" onkeyup="search()" name="search" placeholder="Search blobs..." />
</div>
<div class="aside-containers">
#foreach (var container in containers)
{
caretArrowNumber++;
string arrowId = "arrowId-" + caretArrowNumber;
containerNumber++;
string containerId = "containerId-" + containerNumber;
var blobs = await Model.ListContainerBlobs(container.Name);
//var jsonBlob = Json.Serialize(blobs);
List<object> blobObject = new List<object>();
blobObject.Add(new
{
blobCount = blobs.Count,
blobs = blobs.Select(x => new
{
Name = x.Name,
Container = container.Name,
Blobtype = x.BlobType,
Uri = x.Uri
})
});
var jsonBlob = JsonConvert.SerializeObject(blobObject);
<div class="arrow-blob-container">
<p class="blob-container" onclick="showHide('#containerId', '#arrowId');listContainerBlobs('#jsonBlob', '#container.Name');"><i class="fa fa-caret-right" id="#arrowId"></i> #container.Name</p>
</div>
<div class="showBlob" id="#containerId">
<div class="ml-4">
#foreach (var blob in blobs)
{
blobNumber++;
string blobId = "blobId-" + blobNumber;
<div>
<input class="blobs" id="#blobId" type="button" value="#blob.Name" onclick="downloadBlob('#blobId', '#blob.Name', '#blob.Container.Name')" />
</div>
}
</div>
</div>
}
</div>
</aside>
The following code is the two functions being called on onclick:
<script>
function listContainerBlobs(json, container) {
console.log("beginning");
console.log(json);
var arr = JSON.parse(json);
console.log(arr);
var blobs = document.getElementById('container-blob-display').innerHTML = "<h4>" + container + "</h4>";
var otherDiv = document.getElementById('section-1');
var thisDiv = document.getElementById('section-2');
otherDiv.style.display = 'none';
thisDiv.style.display = 'inline';
var blobNumber = 0;
for (i = 0; i < arr.length; i++){
blobNumber++;
var blobId = "blobId" + blobNumber;
blobs += "<p class='search-result' id='" + blobId + "' onclick='downloadBlob('" + blobId + "', '" + arr[i].Name + "', '" + container + "')'>" + arr[i].Name + "</p>";
}
console.log(blobs);
}
function showHide(containerId, arrowId) {
var c = document.getElementById(containerId);
var a = document.getElementById(arrowId);
if (c.style.display === "none") {
c.style.display = "inline";
a.className = "fa fa-caret-down";
} else {
c.style.display = "none";
a.className = "fa fa-caret-right";
}
}
</script>
I have tried
commenting out the ListContainerBlobs()-function
commenting out all the css
changed from style.display = "block" to "inline" (seen in the example code)
moved the whole script section to the top of the html
commented out almost all code in the html except the most necessary
But showHide() still wouldn't run on the first click.
So currently, on the first click the listContainerBlobs() run and on the second click the showHide() runs, but I would prefer if both of them ran on the first onclick.
I appreciate all the help I can get! Thanks in advance!
P.S I'd love to do a jsfiddle but it doesn't seem to understand C# and List<> (thinking <> is a tag)
Edit from Mr. Smiths solution
It still takes two clicks for me to run both functions with this solution from Mr. Smith:
HTML:
<div class="arrow-blob-container">
<p class="blob-container aside-content" id="#newContId" data-containerId="#containerId" data-arrowId="#arrowId" data-jsonBlob="#jsonBlob" data-containerName="#container.Name"><i class="fa fa-caret-right" id="#arrowId"></i> #container.Name</p>
</div>
Js:
document.querySelectorAll('.aside-content').forEach(element => {
element.addEventListener('click', function (e) {
let ds = this.dataset;
showHide(ds.containerid, ds.arrowid);
listContainerBlobs(ds.jsonblob, ds.containername);
})
});
This works all the way with the right ids and other values, but like I said, I still need to click two timesto get both functions to be called. First click runs listContainerBlobs(), second click showHide().
Any ideas of why that might be?
You can create an event listener which calls your functions:
<div class="arrow-blob-container">
<p class="blob-container" data-container-id="#containerId" data-arrow-id="#arrowId" data-json-blob="#jsonBlob" data-container-name="#container.Name" ><i class="fa fa-caret-right" id="#arrowId"></i> #container.Name</p>
</div>
Script:
<script>
document.querySelectorAll('.blob-container').forEach(element => {
element.addEventListener('click', function(e) {
let dataset = e.currentTarget.dataset;
showHide(dataset.containerId, dataset.arrowId);
listContainerBlobs(dataset.jsonBlob, dataset.containerName);
});
});
</script>
Check this snippet:
document.querySelectorAll('.blob-container').forEach(element => {
element.addEventListener('click', function(e) {
let dataset = e.currentTarget.dataset;
console.log("containerId: " + dataset.containerId);
console.log("arrowId: " + dataset.arrowId);
console.log("jsonBlob: " + dataset.jsonBlob);
console.log("containerName: " + dataset.containerName);
});
});
<div class="arrow-blob-container">
<button class="blob-container" data-container-id="container1" data-arrow-id="arrow1" data-json-blob="{...}" data-container-name="Button1">Display dataset</button>
<button class="blob-container" data-container-id="container2" data-arrow-id="arrow2" data-json-blob="{...}" data-container-name="Button2">Display dataset</button>
<button class="blob-container" data-container-id="container3" data-arrow-id="arrow3" data-json-blob="{...}" data-container-name="Button3">Display dataset</button>
<button class="blob-container" data-container-id="container4" data-arrow-id="arrow4" data-json-blob="{...}" data-container-name="Button4">Display dataset</button>
</div>
This also works without querySelector which might be clearer:
function onButtonClick(e) {
let dataset = e.dataset;
console.log("containerId: " + dataset.containerId);
console.log("arrowId: " + dataset.arrowId);
console.log("jsonBlob: " + dataset.jsonBlob);
console.log("containerName: " + dataset.containerName);
}
<div class="arrow-blob-container">
<button class="blob-container" onClick="onButtonClick(this)" data-container-id="container1" data-arrow-id="arrow1" data-json-blob="{...}" data-container-name="Button1">Display dataset</button>
<button class="blob-container" onClick="onButtonClick(this)" data-container-id="container2" data-arrow-id="arrow2" data-json-blob="{...}" data-container-name="Button2">Display dataset</button>
<button class="blob-container" onClick="onButtonClick(this)" data-container-id="container3" data-arrow-id="arrow3" data-json-blob="{...}" data-container-name="Button3">Display dataset</button>
<button class="blob-container" onClick="onButtonClick(this)" data-container-id="container4" data-arrow-id="arrow4" data-json-blob="{...}" data-container-name="Button4">Display dataset</button>
</div>
I'm trying to join the data result from ajax to the const res.
So Ideally the list order would be
Attack 402983
Defense 1500
Strength 70
HitPoints 68
As you can see below, i'm having trouble appending the two together in a list fashion. An example of whats coming from ajax data is 402983,1500,70,68
HTML
<form class="form-inline mt-2 mt-md-0">
<input class="form-control mr-sm-2" type="text" name="search" placeholder="Search"/>
<button id="search-btn" class="btn btn-outline-success my-2 my-sm-0" type="submit">Search </button>
</form>
<ul id="response">
</ul>
JAVASCRIPT
// this is the id of the form
$('#search-btn').on('click', function(e) {
e.preventDefault();
var url = "?player=";
var player = $('input[name="search"]').val();
var urlAddition = url + player
$.ajax({
url: urlAddition,
dataType: "html",
success: function(data) {
const res = 'Attack, Defense, Strength, HitPoints';
const list = res.split(",");
const listdata = data.split(",");
const secondlists = listdata.map(item => + item);
$('ul#response').html(list.map(item => '<li>' + item + secondlists + '</li>').join(''));
}
});
});
You can use the second param from the handler which is the index.
$('ul#response').html(list.map((item, i) => '<li>' + `${item} ${listdata[i]}` + '</li>').join(''));
^ ^
As you can see, this approach uses the array listdata directly.
I have form which gets clone when user click on add more button .
This is how my html looks:
<div class="col-xs-12 duplicateable-content">
<div class="item-block">
<button class="btn btn-danger btn-float btn-remove">
<i class="ti-close"></i>
</button>
<input type="file" id="drop" class="dropify" data-default-file="https://cdn.example.com/front2/assets/img/logo-default.png" name="sch_logo">
</div>
<button class="btn btn-primary btn-duplicator">Add experience</button>
...
</div>
This my jquery part :
$(function(){
$(".btn-duplicator").on("click", function(a) {
a.preventDefault();
var b = $(this).parent().siblings(".duplicateable-content"),
c = $("<div>").append(b.clone(true, true)).html();
$(c).insertBefore(b);
var d = b.prev(".duplicateable-content");
d.fadeIn(600).removeClass("duplicateable-content")
})
});
Now I want every time user clicks on add more button the id and class of the input type file should be changed into an unique, some may be thinking why I'm doing this, it I because dropify plugin doesn't work after being cloned, but when I gave it unique id and class it started working, here is what I've tried :
function randomString(len, an){
an = an&&an.toLowerCase();
var str="", i=0, min=an=="a"?10:0, max=an=="n"?10:62;
for(;i++<len;){
var r = Math.random()*(max-min)+min <<0;
str += String.fromCharCode(r+=r>9?r<36?55:61:48);
}
return str;
} var ptr = randomString(10, "a");
var className = $('#drop').attr('class');
var cd = $("#drop").removeClass(className).addClass(ptr);
Now after this here is how I initiate the plugin $('.' + ptr).dropify().
But because id is still same I'm not able to produce clone more than one.
How can I change the id and class everytime user click on it? is there a better way?
Working Fiddle.
Problem :
You're cloning a div that contain already initialized dropify input and that what create the conflict when you're trying to clone it and reinitilize it after clone for the second time.
Solution: Create a model div for the dropify div you want to clone without adding dropify class to prevent $('.dropify').dropify() from initialize the input then add class dropify during the clone.
Model div code :
<div class='hidden'>
<div class="col-xs-12 duplicateable-content model">
<div class="item-block">
<button class="btn btn-danger btn-float btn-remove">
X
</button>
<input type="file" data-default-file="http://www.misterbilingue.com/assets/uploads/fileserver/Company%20Register/game_logo_default_fix.png" name="sch_logo">
</div>
<button class="btn btn-primary btn-duplicator">Add experience</button>
</div>
</div>
JS code :
$('.dropify').dropify();
$("body").on("click",".btn-duplicator", clone_model);
$("body").on("click",".btn-remove", remove);
//Functions
function clone_model() {
var b = $(this).parent(".duplicateable-content"),
c = $(".model").clone(true, true);
c.removeClass('model');
c.find('input').addClass('dropify');
$(b).before(c);
$('.dropify').dropify();
}
function remove() {
$(this).closest('.duplicateable-content').remove();
}
Hope this helps.
Try this:
$(function() {
$(document).on("click", ".btn-duplicator", function(a) {
a.preventDefault();
var b = $(this).parent(".duplicateable-content"),
c = b.clone(true, true);
c.find(".dropify").removeClass('dropify').addClass('cropify')
.attr('id', b.find('[type="file"]')[0].id + $(".btn-duplicator").index(this)) //<here
$(c).insertBefore(b);
var d = b.prev(".duplicateable-content");
d.fadeIn(600).removeClass("duplicateable-content")
})
});
Fiddle
This does what you specified with an example different from yours:
<div id="template"><span>...</span></div>
<script>
function appendrow () {
html = $('#template').html();
var $last = $('.copy').last();
var lastId;
if($last.length > 0) {
lastId = parseInt($('.copy').last().prop('id').substr(3));
} else {
lastId = -1;
}
$copy = $(html);
$copy.prop('id', 'row' + (lastId + 1));
$copy.addClass('copy');
if(lastId < 0)
$copy.insertAfter('#template');
else
$copy.insertAfter("#row" + lastId);
}
appendrow();
appendrow();
appendrow();
</script>
Try adding one class to all dropify inputs (e.g. 'dropify'). Then you can set each elements ID to a genereted value using this:
inputToAdd.attr('id', 'dropify-input-' + $('.dropify').length );
Each time you add another button, $('.dropify').length will increase by 1 so you and up having a unique ID for every button.
I am building an eCommerce Application where the user can select the option and the shopping cart is automatically updated through jquery.
The user will have few radio button to choose from and as he selects the radio button, the shopping cart is updated.
Now, the issue I am facing is, when he taps on the radio button ( Mobile website), some times, the callback function is not called at all so the shopping card is not updated.
I am not an expert, but can you please tell me if I am missing anything. Here is the code I am using.
HTML Code
<div class="col-33">
<div class="panel1 panel-primary text-center no-border">
<div class="panel-body blue">
<label>
<input type="radio" name="recharge_amount" value="{var name='price_id'}"/><br/>{var name='grand_total1'}
<input type="hidden" id="carttotal_{var name='price_id'}" value="{var name='carttotal'}"/>
<input type="hidden" id="taxper_{var name='price_id'}" value="{var name='taxper'}"/>
<input type="hidden" id="taxamount_{var name='price_id'}" value="{var name='taxamount'}"/>
<input type="hidden" id="grand_total_{var name='price_id'}" value="{var name='grand_total'}"/>
</label>
</div>
</div>
</div>
Jquery
$('#transfer_target input[type="radio"]').click(function()
{
$('#cart_total').hide();
var $amt = $(this).val();
var carttotal_el = "#carttotal_" + $amt;
var taxper_el = "#taxper_" + $amt;
var taxamount_el = "#taxamount_" + $amt;
var grand_total_el = "#grand_total_" + $amt;
//update_price_list($amt);
var $carttotal = $('#carttotal');
$carttotal.html($(carttotal_el).val());
var $salestax_per = $('#salestax_per');
var $str = '<h4>Sales Tax(' + $(taxper_el).val() + ')</h4>';
$salestax_per.html($str);
var $salestax_amount = $('#salestax_amount');
$salestax_amount.html($(taxamount_el).val());
var $grand_total = $('#grand_total');
$grand_total.html($(grand_total_el).val());
$('#cart_total').show();
});
Are you using a DOM Ready function? You should have something that looks like this. It may simply be that the data is ready.
$(document).ready(function() {
someName();
});
function someName() {
$('#transfer_target input[type="radio"]').click(function() {
$('#cart_total').hide();
var $amt = $(this).val();
var carttotal_el = "#carttotal_" + $amt;
var taxper_el = "#taxper_" + $amt;
var taxamount_el = "#taxamount_" + $amt;
var grand_total_el = "#grand_total_" + $amt;
var $carttotal = $('#carttotal');
$carttotal.html($(carttotal_el).val());
var $salestax_per = $('#salestax_per');
var $str = '<h4>Sales Tax(' + $(taxper_el).val() + ')</h4>';
$salestax_per.html($str);
var $salestax_amount = $('#salestax_amount');
$salestax_amount.html($(taxamount_el).val());
var $grand_total = $('#grand_total');
$grand_total.html($(grand_total_el).val());
$('#cart_total').show();
});
}
Small part of my html code :
<div class="text-center">
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
Platforms <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" id = "buttonsPlace">
</ul>
</div>
In my js file :
for (i = 0; i < platformList.length; i++) {
var li = $("<li/>" , { id : "plat"+i,class : "dropdown" text : platformList[i] } )
//var text = document.createTextNode(platformList[i]);
//li.appendChild(text);
//btn.data("platform", platformList[i] );
$("#buttonsPlace").append(li);
console.log("hiding");
$("#plat" + i).hide();
}
However the menu is appearing but the menu items are not. where am i going wrong
Try This
$(function() {
var change = function( txt ) {
$("#ID").append( '<li>' + txt + '</li>' );
};
change("this is the first change");
change("this is the second change");
});
Demo
For Li Click
$("ul").on('click', 'li', function () {
var id = this.id;
//play with the id
});
$(function(){
$('.dropdown-toggle').click(function(){
var countRows = $('ul.dropdown-menu li').size();
$('.dropdown-menu').append('<li>Row '+countRows+'</li>');
countRows++;
});
});
Here is the jsfiddle for you http://jsfiddle.net/alexchizhov/ncgXK/
$('#drowdown-link1').click(function(e){
e.preventDefault();
window.location.href = 'http://example.com';
});
Here is another jsfiddle for you http://jsfiddle.net/alexchizhov/ncgXK/4/