In this script I select checked id and store string in hidden field.
For removing exist id I have stored string in array.
I want to remove exist id from array and store array values into
hidden field.
Script:
AddRemoveCustomer = function(){
$(".checkBoxClass").click(function (e) {
//var CustomerIDArray = '';
var hidCID = document.getElementById("hfCustomerID");
var CustArray = [];
if(hidCID!=null || hidCID!=undefined)
{
var CustID = hidCID.value;
CustArray = CustID.split("");
alert('CustID is :' + CustID );
alert('CustArray is :' + CustArray );
if (CustID == null || CustID=="") {
$(".checkBoxClass:checked").each(function () {
alert("Null");
//CustomerIDArray = $(this).val();
//alert(CustomerIDArray);
alert('value : '+$(this).val());
hidCID.value = $(this).val();
});
} else {
alert("Not Null");
//CustomerIDArray = CustID;
$(".checkBoxClass:checked").each(function () {
alert($(this).val());
//CustomerIDArray = CustomerIDArray + "," + $(this).val();
//alert(CustomerIDArray);
CustID = CustID +","+ $(this).val();
alert(CustID);
alert('value : '+$(this).val());
hidCID.value = CustID;
});
}
//CustID = CustomerIDArray.values;
}
//$('#hfCustomerID').val(allSelectedValues);
//alert($('#hfCustomerID').val());
});
};
To remove array item use Array.splice(startIndex, deleteCount).
let elIndex = custArray.indexOf(deleteId);
custArray.splice(elIndex, 1);
Related
I'm trying to sum the values from the key "value" in the object data.
Googled alot but cant figure this out.
My guess is that i'm not retrieving the values from localStorage.
EDIT: And i want to save the summed values to localStorage...
var storage = localStorage.getItem("Bills");
if (storage !== null) {
var data = JSON.parse(storage);
loadData(data);
var id = data.length;
} else {
id = 0;
data = [];
};
function loadData(array) {
array.forEach(function(bill) {
newItem(bill.name, bill.value, bill.id, bill.payed);
});
};
function addBill() {
modal.style.display = "none";
var bill = document.getElementById("billName").value;
var billVal = document.getElementById("billValue").value;
newItem(bill, billVal, id, false);
data.push({
name: bill,
value: billVal,
id: id,
payed: false
});
billsTotals.innerHTML = Object.values(data).reduce((t, { value }) => t + value, 0); // ?????
localStorage.setItem("Bills", JSON.stringify(data));
};
function newItem(name, value, id, payed) {
if (payed == true) {
return;
}
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode(name + " " + value + "kr"));
li.setAttribute("id", id);
ul.appendChild(li);
bill = document.getElementById("billName").value = "";
billVal = document.getElementById("billValue").value = "";
};
i'v tried to add .values before reduce but nothing works:
billsTotals.innerHTML = Object.values(data.value).reduce((t, {value}) => t + value, 0); // ?????
Not sure about your data variable. But the data variable is an array then you could do something like this.
data.reduce((total,{value})=>{
return total +value
},0)
I'm doing a cart and I want to increment the qty if the item_id exising in localStorage.
<button data-item_id="1" data-item_name="cake" data-item_price="2 dollar">Add to cart</button>
Not sure why my below code doesn't work, it added a new object instead of increment the qty value.
$(function(){
$('button').click(function(){
var item_id = $(this).attr('data-item_id');
var item_name = $(this).attr('data-item_name');
var item_price = $(this).attr('data-item_price');
var arr = JSON.parse(localStorage.getItem('cart')) || [];
var obj = {};
if(arr.length === 0){ // first time insert
obj.item_id = item_id;
obj.item_name = item_name;
obj.item_price = item_price;
obj.item_qty = 1;
}else{
$(arr,function(i){
//doesn't work here
obj.item_qty[i] = parseInt(this.qty) + 1;
});
}
arr.push(obj);
localStorage.setItem('cart',JSON.stringify(arr));
});
});
debug for few hours couldn't solved.
Use {} instead of [] making the arr contain one object per item_id and each object will get 1 added to the qty each time it is called. There is no remove in this code
$(function(){
$('button').on("click",function(e){
var item_id = $(this).data("item_id");
var item_name = $(this).data("item_name");
var item_price = $(this).data("item_price");
var cart = JSON.parse(localStorage.getItem('cart')) || {};
var currentObj = cart[item_id];
if(currentObj){
currentObj.qty++; // increase the qty by one
}
else { // item_id had not been stored before, create it
cart[item_id]= {
"item_name" :item_name,
"item_price":item_price,
"item_qty" :1
}
}
localStorage.setItem('cart',JSON.stringify(cart));
});
});
Then you have to do like this:
$(function(){
$('button').click(function(){
var item_id = $(this).attr('data-item_id');
var item_name = $(this).attr('data-item_name');
var item_price = $(this).attr('data-item_price');
var arr = JSON.parse(localStorage.getItem('cart')) || [];
var obj = {};
obj.item_id = item_id;
obj.item_name = item_name;
obj.item_price = item_price;
obj.item_qty = 1;
detectchange = 'no';
$.each(arr,function(i){
if(this.item_id == obj.item_id){
this.item_qty = parseInt(this.item_qty) + 1; detectchange = 'yes'; }
});
if(detectchange =='no'){
arr.push(obj); }
localStorage.setItem('cart',JSON.stringify(arr));
});
});
so I'd like to assign a url parameter value to jquery but it won't take it ..
var product_id = '<?php echo $_GET["pID"]; ?>';
my function is below , document ready is included... just posted the relevant stuff
function sendOrderToServer() {
var order = $(".sortable_table").sortable("serialize");
var array_order = order.split("&");
var product_id = '<?php echo $_GET["pID"]; ?>';
alert(product_id);
for (var i=0;i<array_order.length;i++){
var id = array_order[i].split("=");
id = id[1];
var text_field_video = $("#products_video_sm_dynamic_"+ id).val();
var text_field_video_caption = $("#products_video_sm_dynamic_"+ id +"_caption").val();
var text_field_image = $("#products_image_sm_dynamic_"+ id).val();
var text_field_image_caption = $("#products_image_sm_dynamic_"+ id +"_caption").val();
var text_field_video_xl = $("#products_video_xl_dynamic_"+ id).val();
var text_field_video_xl_caption = $("#products_video_xl_dynamic_"+ id +"_caption").val();
var text_field_image_xl = $("#products_image_xl_dynamic_"+ id).val();
if(text_field_video != undefined){
var element = "products_video_sm_dynamic_" + id;
var position = i + 1;
}
if(text_field_image != undefined){
var element = "products_image_sm_dynamic_" + id ;
var position = i + 1;
}
if(text_field_video_xl != undefined){
var element2 = "products_video_xl_dynamic_" + id ;
var position = i + 1;
}
if(text_field_image_xl != undefined){
var element2 = "products_image_xl_dynamic_" + id ;
var position = i + 1;
}
//alert(element);
//alert("position is" + position);
$.ajax({
type:'POST',
url :'includes/insert_database.php',
data:{ position : position, element1:element , element2:element2},
success: function(result){
alert(result);
}
});
}
}
http://example.com/yourpage.php?pID=%27%3B+alert%28%27OMG+I+just+totally+hacked+your+site%21%27%29%3B+%27
Try this instead:
var product_id = <?php echo json_encode($_GET['pID']); ?>
I don't have all that much experience with Prototype and I've been working with jQuery to get things working properly on our site found here. Today I've added a jQuery based script for session handling. The problem I'm having is that even though I've gotten so far today in terms of functionality, I can't seem to get the change event fired via jQuery.
I'm using the following code currently, but it isn't working properly (you can test it on the site.. as soon as you change the year using your mouse, the AJAX is triggered and a Make can be selected)...
var yearSelected = jQuery.jStorage.get("yearSelected");
console.log(yearSelected);
// Set the vars...
if ((jQuery("div.amfinder-horizontal td:nth-child(1) select").val() == "0")) {
jQuery("div.amfinder-horizontal td:nth-child(1) select option").each(function() { this.selected = (this.text == "2003"); });
jQuery("div.amfinder-horizontal td:nth-child(1) select").trigger('change');
console.log('Set the year!');
}
The following code is the Prototype script controlling this and I need to fire off the change event, and would love to do it via jQuery if at all possible.
var amFinder = new Class.create();
amFinder.prototype = {
initialize: function(containerId, ajaxUrl, loadingText, isNeedLast, autoSubmit)
{
this.containerId = containerId;
this.ajaxUrl = ajaxUrl;
this.autoSubmit = Number(autoSubmit);
this.loadingText = loadingText;
this.isNeedLast = Number(isNeedLast);
this.selects = new Array();
//possible bug if select order in the HTML will be different
$$('#' + this.containerId + ' select').each(function(select){
select.observe('change', this.onChange.bindAsEventListener(this));
this.selects[this.selects.length] = select;
}.bind(this));
},
onChange: function(event)
{
var select = Event.element(event);
var parentId = select.value;
var dropdownId = 0;
/* should load next element's options only if current is not the last one */
for (var i = 0; i < this.selects.length; i++){
if (this.selects[i].id == select.id && i != this.selects.length-1){
var selectToReload = this.selects[i + 1];
if (selectToReload){
dropdownId = selectToReload.id.substr(selectToReload.id.search('--') + 2);
}
break;
}
}
this.clearAllBelow(select);
if (0 != parentId && dropdownId){
var postData = 'dropdown_id=' + dropdownId + '&parent_id=' + parentId;
new Ajax.Request(this.ajaxUrl, {
method: 'post',
postBody : postData,
evalJSON : 'force',
onLoading: function(){
this.showLoading(selectToReload);
}.bind(this),
onSuccess: function(transport) {
if (transport.responseJSON){
this.clearSelectOptions(selectToReload);
var itemsFound = false;
transport.responseJSON.each(function(item){
itemsFound = true;
var option = document.createElement('option');
option.value = item.value;
option.text = item.label;
option.label = item.label;
$(selectToReload).appendChild(option);
});
if (itemsFound){
$(selectToReload).disabled = false;
}
}
}.bind(this)
});
}
},
isLast: function(select)
{
return (this.selects[this.selects.length-1].id == select.id);
},
isFirst: function(select)
{
return (this.selects[0].id == select.id);
},
clearSelectOptions: function(select)
{
$(select).descendants().each(function(option){
option.remove();
});
},
clearAllBelow: function(select)
{
var startClearing = false;
for (var i = 0; i < this.selects.length; i++){
if (startClearing){
this.clearSelectOptions(this.selects[i]);
$(this.selects[i]).disabled = true;
}
if (this.selects[i].id == select.id){
startClearing = true;
}
}
var type = (((this.isLast(select) && !this.isNeedLast) && select.value > 0) || ((this.isNeedLast) && ((select.value > 0) || (!this.isFirst(select))))) ? 'block' : 'none';
if ('block' == type && this.autoSubmit && this.isLast(select))
{
$$('#' + this.containerId + ' .amfinder-buttons button')[0].form.submit();
} else {
$$('#' + this.containerId + ' .amfinder-buttons')[0].style.display = type;
}
},
showLoading: function(selectToReload)
{
var option = document.createElement('option');
option.value = 0;
option.text = this.loadingText;
option.label = this.loadingText;
$(selectToReload).appendChild(option);
},
};
I had the same problem. Here is solution. When you create : amfinder-horizontal the html goes something like this
<div class="amfinder-horizontal" id="amfinder_5333ffb212b09Container">
...
</div>
Look at id element : amfinder_5333ffb212b09 Container, bold part is also the name of variable that is amfinder object (created from prototype). It's a random name. This is from the extension source :
<?php $finderId = 'amfinder_' . uniqid(); ?>
...
<script type="text/javascript">
var <?php echo $finderId ?> = new amFinder(
'<?php echo $finderId ?>Container',
'<?php echo $this->getAjaxUrl() ?>',
'<?php echo $this->__('Loading...')?>',
'<?php echo Mage::getStoreConfig('amfinder/general/partial_search')?>',
<?php echo intval(Mage::getStoreConfig('amfinder/general/auto_submit')) ?>
);
</script>
So on every page refresh there is different name. var <?php echo $finderId ?>
Steps :
// Find the name for amfinder object.
var objName = jQuery("div.amfinder-horizontal").attr('id').replace('Container','');
// set Value to that select - copied from your code
jQuery("div.amfinder-horizontal td:nth-child(1) select option").each(function() { this.selected = (this.text == "2003"); });
// call the change event of that object
var targetObj = {
target : jQuery("div.amfinder-horizontal td:nth-child(1) select")[0]
};
window[objName].onChange(targetObj);
What happens in the code is we are displaying an RSS feed based on a radio button click. The RSS feeds for each radio button do not always have content and I would like to have a message display upon a blank screen. Thank you!
<script type="text/javascript">
$(document).ready(function() {
$('input[type=radio]').click(function() {
var id = this.id;
if(id == 'radio-bio') { var categoryURL = '/BayAreaTech/wp-rss2.php?cat=15';}
else if (id == 'radio-com'){ var categoryURL = '/BayAreaTech/wp-rss2.php?cat=13';}
else if (id == 'radio-eleP'){ var categoryURL = '/BayAreaTech/wp-rss2.php?cat=9';}
else if (id == 'radio-eleD'){ var categoryURL = '/BayAreaTech/wp-rss2.php?cat=10';}
else if (id == 'radio-nano'){ var categoryURL = '/BayAreaTech/wp-rss2.php?cat=16';}
else if (id == 'radio-opt'){ var categoryURL = '/BayAreaTech/wp-rss2.php?cat=12';}
else if (id == 'radio-semi'){ var categoryURL = '/BayAreaTech/wp-rss2.php?cat=11';}
else if (id == 'radio-comSoft'){ var categoryURL = '/BayAreaTech/wp-rss2.php?cat=14';}
else if (id == 'radio-techMan'){ var categoryURL = '/BayAreaTech/wp-rss2.php?cat=17';}
else { var categoryURL = '/BayAreaTech/wp-rss2.php?cat=1';}
$('#feedContainer').empty();
$.ajax({
type: 'GET',
url: categoryURL,
dataType: 'xml',
success: function (xml) {
var data = [];
$(xml).find("item:lt(40)").each(function () {
var dateText = $(this).find("Date").text().toString();
var eventDate = moment(dateText,"YYYY-MM-DD");
var title = $(this).find("title").text();
var region = dateText.substr(8).toUpperCase();
if (region.length < 3) { region = "SF"; }
var description = $(this).find("description").text();
var infoDisplay = description.substr(0, description.indexOf(",")+120) + "..."; //Parsed DATE from description
//var locationdisplay = description.substr(description.indexOf(",")+6,4); //Parsed the location from description
var category = $(this).find("category").text();
var linkUrl = $(this).find("link").text();
var displayTitle = "<a href='" + linkUrl + "' target='_blank'>" + title + "</a>"
var item = {title: displayTitle, infoDecription: infoDisplay, Date: new Date(eventDate), Region: region,}
var now = moment();
if (item.Date >= now){ data.push(item); }
// $('#feedContainer').append('<h3>'+displaytitle+'</h3><p>'+"Event Date: "+descriptdisplay+'</p><p>'+"Location: "+region+'</p');
});
data.sort(function (a, b) {
a = new Date(a.Date);
b = new Date(b.Date);
return a<b ? -1 : a>b ? 1 : 0;
});
$.each(data, function (index, item) {
$('#feedContainer').append('<h3>' + item.title + '</h3><p>' + item.infoDecription + '</p>');
});
}
});
$("#fieldpanel").panel("close");
});
});
</script>
You could just check the array's length
if (data.length > 0) {
data.sort(function (a, b) {
a = new Date(a.Date);
b = new Date(b.Date);
return a<b ? -1 : a>b ? 1 : 0;
});
$.each(data, function (index, item) {
$('#feedContainer').append('<h3>' + item.title + '</h3><p>' + item.infoDecription + '</p>');
});
}
else {
$("#feedContainer").append('<h3>There is no content to display</h3>');
}