I am using simplecart js. It's a really simple shop with one product. I would like to automatically redirect to the cart page when someone clicks the add to cart button.
The code for adding a product:
<div class="simpleCart_shelfItem">
<h2 class="item_name"> Awesome T-shirt </h2>
<p> <input type="text" value="1" class="item_Quantity"><br>
<span class="item_price">$35.99</span><br>
<a class="item_add" href="javascript:;"> Add to Cart </a></p>
</div>
The listener in simpleCart.js:
/* here is our shelfItem add to cart button listener */
, { selector: 'shelfItem .item_add'
, event: 'click'
, callback: function () {
var $button = simpleCart.$(this),
fields = {};
$button.closest("." + namespace + "_shelfItem").descendants().each(function (x,item) {
var $item = simpleCart.$(item);
// check to see if the class matches the item_[fieldname] pattern
if ($item.attr("class") &&
$item.attr("class").match(/item_.+/) &&
!$item.attr('class').match(/item_add/)) {
// find the class name
simpleCart.each($item.attr('class').split(' '), function (klass) {
var attr,
val,
type;
// get the value or text depending on the tagName
if (klass.match(/item_.+/)) {
attr = klass.split("_")[1];
val = "";
switch($item.tag().toLowerCase()) {
case "input":
case "textarea":
case "select":
type = $item.attr("type");
if (!type || ((type.toLowerCase() === "checkbox" || type.toLowerCase() === "radio") && $item.attr("checked")) || type.toLowerCase() === "text") {
val = $item.val();
}
break;
case "img":
val = $item.attr('src');
break;
default:
val = $item.text();
break;
}
if (val !== null && val !== "") {
fields[attr.toLowerCase()] = fields[attr.toLowerCase()] ? fields[attr.toLowerCase()] + ", " + val : val;
}
}
});
}
});
// add the item
simpleCart.add(fields);
}
}
]);
});
From what I have read it is bad practice to use href="javascript:;" is it a good idea to change it to a click function that will add the item to the cart then go to the cart page or just add the redirect? How do I go about this? Thanks
I’m not sure how the simplecart APi works, but you can try something like:
// add the item
simpleCart.add(fields);
window.location='/cart/'; // change to your cart route
If the cart saves to a server cookie, you might need to put this in a callback.
Related
How to get the current selected/unselected in a Jquery multiselect?
I already know how to get the selected values in a multiselect. The problem is that I need to get the one that was currently selected/unselected when the user clicked on it. It looks like a trivial question but I haven't really found a proper solution so far.
This is what I previously tried:
$('#mySelect').change(function(){
var element = $(this).val();
})
Unfortunately it returns an array with all selected options. What I need is to get the current either selected or unselected value by the user. I just tried to create a method myself using auxiliar variables and it seems that it works now.
if($(this).attr('id').includes('Type')) Key = "trackertype";
if(selectedValue.length > 0 && $(this).val() == null){
Value = selectedValue[0].toString();
selectedValue = [];
Key = '-' + Key;
}else if(selectedValue.length == 0 && $(this).val() != null){
selectedValue.push($(this).val()[0]);
Value = selectedValue[0].toString();
}else if(selectedValue.length > 0 && $(this).val() != null && selectedValue.length < $(this).val().length){
var selected = true;
$.each($(this).val(),function(i,item){
var current = item.toString();
$.each(selectedValue,function(i,itemV){
if(current != itemV.toString()){
Value = current.toString();
selectedValue.push(current.toString());
selected = false;
}
});
});
}else if(selectedValue.length > $(this).val().length){
$.each($(this).val(),function(i,item){
var current = item.toString();
$.each(selectedValue,function(i,itemV){
if(current != itemV.toString()){
Value = itemV.toString();
selectedValue = jQuery.grep(selectedValue, function(value) {
return value != itemV.toString();
});
selected = true;
}
});
});
}
if(selected){
Key = '-' + Key;
}
I needed to send Value(value of the current selected option) and Key(select Name) to a web service. Its not the best possible code(sorry about that) but it actually does its job.
Thanks
var selectedItems = document.querySelectorAll('#selectBoxid option:checked');
// here selectboxid is id of select element of your page.
It is simple when any html element can get using document.getElementsById('id').
Just same as if you want to get html element using css class or any css selector rather than id of element or name of html element.
For example :
<p class="text-center" > abcd </p>
Then, we can retrive all html using:
document.querySelectorAll('.text-center')
Same in given example we want option html element which is selected for that property I use:
document.querySelectorAll('option:checked');
I´m building a wix.com page with wix.com code which should show some products.
There are 3 dropdown menus on the page which are already working and 13 categories to click on. After being clicked a var turns true etc. With a maximum of 3 selected the product should be filtered to the selected categories, only showing the products the 3 categories apply on.
I´m getting an "Script error" when I click the filtering button having nothing selected. It only works when both "Picto5" and "Picto10" are true.(Showing all items that have one of the categories.. :/)
export function FilterButton_click(event) {
//Pictogramme
var PictoFilter5 = (Picto5 === true)
? "Pictogramm5": undefined;
console.log(PictoFilter5);
var PictoFilter10 = (Picto10 === true)
? "Pictogramm10": undefined;
console.log(PictoFilter10);
//Dropdowns
var emotionValue = ($w('#EmotionDropdown').value !== "alle")
? $w('#EmotionDropdown').value
: undefined;
var kategorieValue = ($w('#KategorieDropdown').value !== "alle")
? $w('#KategorieDropdown').value
: undefined;
var dekoValue = ($w('#DekoDropdown').value !== "alle")
? $w('#DekoDropdown').value
: undefined;
//Query
wixData.query("Steine")
//Dropdowns
.eq('grosse1', kategorieValue)
.eq('pictogramm1', emotionValue)
.eq('symbolSerieName', dekoValue)
//Pictogramme
.contains("kategorie1Sortierung", PictoFilter5)
.contains("kategorie1Sortierung", PictoFilter10)
.find()
.then (res => {
$w('#repeater1').data =res.items;
console.log("Filtered to " + kategorieValue +" "+ dekoValue +" "+PictoFilter5+" "+PictoFilter10);
})
.catch( (error) => {
let errorMsg = error.message;
let code = error.code;
} );
}
Thanks
Looking at your code you write you have the value true or false in the PictoFilter5 and PictoFilter10? If that is so you won't be able to use .contains to check that fields. You will need to have .eq to check a boolean field.
wixData.query("Steine")
.eq('grosse1', kategorieValue)
.eq('pictogramm1', emotionValue)
.eq('symbolSerieName', dekoValue)
//Pictogramme
.contains("kategorie1Sortierung", PictoFilter5)
.contains("kategorie1Sortierung", PictoFilter10)
.find()
i want to build mini webchat - When view site i set show 5 messages and if view more, you can click button. All things are fine but when i remove 1 node, firebase auto add last node into, how can i prevent it?
Ex: I have node A,B,C,D,E,F,G. I had loaded list C,D,E,F,G but when i delete 1 in all, it auto add B into list.
<div id="messgesDiv">
<center><h3>Message</h3></center>
</div>
<div style="margin-top: 20px;">
<input type="text" id="nameInput" placeholder="Name">
<input type="text" id="messageInput" placeholder="Message" data-id="">
<input type="text" id="idproject" placeholder="ID Project">
</div>
<button id="delete">Delete Test</button>
<button id="edit">Edit</button>
<button id="loadmore">Load more</button>
<button id="showlastkey">Show last key</button>
My javascript
$('#loadmore').click(function() {
i = 0; old = first;
myDataRef.orderByKey().endAt(first).limitToLast(6).on('child_added', function (snapshot){
if( i == 0)
first = snapshot.key();
var message = snapshot.val();
if(snapshot.key() != old)
displayChatMessage(message.name, message.text, message.idproject, 'old');
i++;
console.log('myDataRef.orderByKey().endAt(first).limitToLast(6)');
});
});
$("#messageInput").keypress(function (e){
if(e.keyCode == 13){ //Enter
var name = $("#nameInput").val();
var text = $("#messageInput").val();
var idproject = $("#idproject").val();
if($("#messageInput").data("id")=='')
{
myDataRef.push({name: name, text: text, idproject: idproject});
}
else
{
myDataRef.child(key).update({name: name, text: text, idproject: idproject});
$('#messageInput').attr('data-id', '');
}
$("#messageInput").val("");
}
});
myDataRef.limitToLast(5).on('child_added', function (snapshot){
if( i == 0)
first = snapshot.key();
var message = snapshot.val();
displayChatMessage(snapshot.key(), message.name, message.text, message.idproject, 'new');
i++;
console.log(snapshot.key());
console.log(' myDataRef.limitToLast(5)');
});
function displayChatMessage(key, name, text, idproject, status){
//console.log(name + " -- " + text + " -- " +idproject);
if( status == 'new')
{
$('<div/>', { 'data-id': key , 'class' : 'test'}).text(text + " - ").prepend($('<em/>').text(name+": " )).append("IdProject: "+idproject).appendTo($("#messgesDiv"));
$("#messgesDiv")[0].scrollTop = $("#messgesDiv")[0].scrollHeight;
}
else
{
$('<div/>', { 'data-id': key , 'class' : 'test'}).text(text + " - ").prepend($('<em/>').text(name+": " )).append("IdProject: "+idproject).insertAfter($("center"));
$("#messgesDiv")[0].scrollTop = $("#messgesDiv")[0].scrollHeight;
}
}
$('#delete').click(function() {
myDataRef.child(key).remove();
$('#messgesDiv').filter('[data-id="'+key+'"]').remove();
});
Firebase limit queries act like a view on top of the data. So if you create a query for the 5 most recent messages, the Firebase client will ensure that you always have the 5 most recent messages.
Say you start with these messages:
message1
message2
message3
message4
message5
Now if you add a message6, you will get:
child_removed message1
child_added message6
So that your total local view becomes:
message2
message3
message4
message5
message6
Conversely when you remove message 6 again, you get these events:
child_removed message6
child_added message1 (before message2)
So that you can update the UI and end up with the correct list again.
There is no way to change this behavior of the API. So if you want to handle the situation differently, you will have to do this in your client-side code.
Your code currently only handles child_added. If you have add a handler for child_removed you'll see that you can easily keep the user interface in sync with the data.
Alternatively you can detect that the message is already in your UI by comparing the key of the message you're adding to the ones already present in the DOM:
function displayChatMessage(key, name, text, idproject, status){
var exists = $("div[data-id='" + key + "']").length;
if (status == 'new' && !exists) {
$('<div/>', { 'data-id': key , 'class' : 'test'}).text(text + " - ").prepend($('<em/>').text(name+": " )).append("IdProject: "+idproject).appendTo($("#messgesDiv"));
$("#messgesDiv")[0].scrollTop = $("#messgesDiv")[0].scrollHeight;
}
else {
$('<div/>', { 'data-id': key , 'class' : 'test'}).text(text + " - ").prepend($('<em/>').text(name+": " )).append("IdProject: "+idproject).insertAfter($("center"));
$("#messgesDiv")[0].scrollTop = $("#messgesDiv")[0].scrollHeight;
}
}
In my entity (A) has 50 option set. If the user select 10 optionsset value and not selected remaining one, and he/she click save button. In that situation i need to alert user "To fill all the option set". I don't want to get the Schema name for the optionset individually, i need to get all the option set schema name dynamically.
Is it possible? Help me.
I have not tested this function, but you can try this and make changes if needed.
function IsFormValidForSaving(){
var valid = true;
var message = "Following fields are required fields: \n";
Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {
if (attribute.getRequiredLevel() == "required") {
if(attribute.getValue() == null){
var control = attribute.controls.get(0);
// Cheking if Control is an optionset and it is not hidden
if(control.getControlType() == "optionset" && control.getVisible() == true) {
message += control.getLabel() + "\n";
}
valid = false;
}
}
});
if(valid == false)
{
alert(message);
}
}
Ref: Microsoft Dynamics CRM 2011 Validate required form javascript
Required fields individual alert fire before the on save event. If you wish to prevent the single alert routine for all unfilled option sets you need to remove the requirement constraint and manage the constraint yourself, probably in your on save handler. I’m just writing the idea here (not tested).
// enter all optionsets ids
var OptionSets50 = ["new_optionset1","new_optionset2","new_optionset50"];
var dirtyOptions = [];
function MyOptionSet(id) {
var mos = this;
var Obj = Xrm.Page.getAttribute(id);
var Ctl = Xrm.Page.getControl(id);
Obj.addOnChange(
function () {
if (Obj.getValue() != null)
delete dirtyOptions[id];
else
dirtyOptions[id] = mos;
});
this.GetLabel = function() {
return Ctl.getLabel();
}
if (Obj.getValue() == null)
dirtyOptions[id] = mos;
}
function OnCrmPageLoad() {
for(var x in OptionSets50) {
OptionSets50 [x] = new MyOptionSet(OptionSets50 [x]);
}
Xrm.Page.data.entity.addOnSave(OnCrmPageSave);
}
//check for dirty options and alert
function OnCrmPageSave(execContext) {
var sMsg = "The following Optinsets Are Required: ";
var sLen = sMsg.length;
for(var os in dirtyOptions) {
sMsg += dirtyOptions[os].GetLabel() + "\n";
}
if (sMsg.length > sLen) {
execContext.getEventArgs().preventDefault();
alert(sMsg);
}
}
I am a newbie in angularjs.
I was stuck on a code and wanted some help.
I am having a controller called watchlist controller in which I am getting the data which is to be displayed in the watchlist.
However I want to display the data only once the watchlist tab is clicked.
This is the Html code :-
<div class='watchlist' >
<button class='btn' id="watchList" ng-click="fetchUserWatchlist()" watchlist-popover ng-controller="WatchlistController">
<i class="hidden-tablet hidden-phone"></i>
<span class = 'mywatchlist'>My Watchlist</span>
<div class = 'watchlist-spinner ' ></div>
</button>
</div>
My controller(watchlist):-
$scope.fetchUserWatchlist = function(pageno,callback){
$scope.isLoading = true;
$rootScope.isrequest = true;
userAPI.myWatchlist({userid:$rootScope.getUser().userid,pageno:pageno}, function(r) {
if (_.isNull(r.watchlistdata)) {
if(typeof callback == 'function'){
callback();
}
if(pageno == 1){
$scope.watchlist = [];
$scope.watchlistCount = 0;
}
if (!$rootScope.apiCalled && pageno == 1){
if(!_.isUndefined($rootScope.watchlistClicked) && $rootScope.watchlistClicked){
$rootScope.$broadcast("watchlist::click");
imageLoadingIndicator();
}
$rootScope.apiCalled = true;
}
return false;
}
if (!_.isUndefined(r.watchlistdata.watchlist)){
var rawData = [];
var tempWatchlist = $scope.watchlist;
if (_.isArray(r.watchlistdata.watchlist))
rawData = r.watchlistdata.watchlist;
else
rawData = [r.watchlistdata.watchlist];
if (pageno == 1) {
$scope.watchlistCount = parseInt(rawData[0].totalcount);
}
if ($scope.watchlist.length == 0 || ($scope.watchlist.length > 0 && pageno == 1))
$scope.watchlist = rawData;
else
_.each(sortByDate(rawData),function(item){
if (! _.some(tempWatchlist,function(existingItem){ return existingItem.programmeid == item.programmeid; }))
{
$scope.watchlist.push(item);
}
});
$scope.watchlistPage += 1;
$timeout(function(){
if (!$rootScope.apiCalled && pageno == 1){
if(!_.isUndefined($rootScope.watchlistClicked) && $rootScope.watchlistClicked){
$rootScope.$broadcast("watchlist::click");
imageLoadingIndicator();
}
$rootScope.apiCalled = true;
}
},1);
$rootScope.isrequest = false;
if(typeof callback == 'function'){
callback();
}
}else
$rootScope.end = true;
});
};
So basically I want to implement ng-click on the controller but here in the above scenario it does not help..The data is called before the button is clicked.
Please help me with this
ng-click will work using the scope:
ng-click="executeThis()"
will look in the $scope for a variable named 'executeThis'. F.e.:
$scope.executeThis = function(){
// Do stuff you want
};
So when you click the element that has this ng-click attribute, the executeThis function on the scope will be executed. In this function you should do whatever you want to do. To display something when you click it, you could use the function to set a variable on the scope to true and then use ng-show to display what you want to display.
HTML:
<div ng-show="varX">someDiv</div>
JS inside controller:
$scope.varX = false;
So whenever you set this variable to true, your element should be shown.
However, I do suggest following some tutorials since I suspect you don't yet grasp how angular works.. Understanding how the fundamentals of angular work is definitely necessary if you want to develop an app.
try
<button class='btn' id="watchList" ng-click="myClickFunction()" watchlist-popover ng-controller="WatchlistController">
The best way to learn (IMHO) is documentation :-)