Empty Woocommerce Cart before adding new item

If you happen to only wants to allow 1 item in your cart and remove all other cart item before adding one, this article might be your saver. Apparently there are a few article that uses a hook call 'woocommerce_add_to_cart' where it 'should' remove the item before adding it. But it doesn't work for newer version of woocommerce. However, there is another hook call 'woocommerce_add_to_cart_validation'. Therefore, if you would like to remove an item before adding a new item into your cart in Woocommerce, you should do something like this.

// before addto cart, only allow 1 item in a cart
add_filter( 'woocommerce_add_to_cart_validation', 'woo_custom_add_to_cart_before' );

function woo_custom_add_to_cart_before( $cart_item_data ) {

    global $woocommerce;
    $woocommerce->cart->empty_cart();

    // Do nothing with the data and return
    return true;
}

This will remove everything during validation before adding the item into wWocommerce cart. Try it!

Multiple Upload Using Single Upload File With jQuery

This is a trick to perform multiple upload using a single upload bar instead of multiple upload bars created by stickman. If you are looking for multiple upload using iframe or asynchronous method, you can visit this simplest way tutorial that explains how iframe method can be done and whether ajax method is available. I first came across stickman article was when i was doing research for multiple upload without having the file uploaded into the server. His idea was brilliant. However, i hardly have the need for such function until recently when my project submit form required multiple upload using a single upload bar again. Stickman method was pure JavaScript which is great and efficient but i needed something from jQuery. Here, i will try to simplify his method into jQuery form.

Concept of Single Multiple Upload File

In order to achieve single multiple upload file, we will have to understand that multiple upload is still possible even without asynchronous upload, that is, we will need multiple upload bar displaying on the screen and having user to click on each upload bar to upload multiple item at once. In stickman concept, its almost the same. The only differences is that he uses one upload bar and insert a new one on top of the existing upload bar AFTER a user has finished selected the item to be uploaded. Therefore it seems like there is only one upload bar. (the process is too fast for our eyes to follow. Thus, we all get trick when this happen) But in reality, all these upload bars were only hidden from user but not from codes. Once, the submit button is pressed, all the visible and non-visible upload bars are being uploaded to the server! This way we get our cheap multiple upload using a single upload bar method.

jQuery Single Multiple Upload File

I won't be displaying stickman code in this article as you can download directly from his website. We can now proceed with the coding after we have understand how stickman method works.

HTML code

All we need on the HTML section are these:

<div>
	<input type="file" name="files[]">
	<div id="upload_list"></div>
</div>

jQuery code

jQuery code is fairly simple. Let's don't complicate stuff. All we need to do is this.

jQuery(document).ready(function($){
var replaceMe = function(){
	var obj = $(this);
	$(obj).css({'position':'absolute','left':'-9999px','display':'none'}).parent().prepend('<input type="file" name="'+obj.attr('name')+'"/>')
	$('#upload_list').append('<div>'+obj.val()+'<input type="button" value="cancel"/><div>');
	$("input[type='file']").change(replaceMe);
	$("input[type='button']").click(function(){
		$(this).parent().remove();
		$(obj).remove();
	});
}
$("input[type='file']").change(replaceMe);
});

The above takes care of the basic. If you wish to restrict the number of upload, you can place a restriction variable.

jQuery(document).ready(function($){
var max = 2;
var replaceMe = function(){
	var obj = $(this);
	if($("input[type='file']").length > max)
	{
		alert('fail');
		obj.val("");
		return false;
	}
	$(obj).css({'position':'absolute','left':'-9999px','display':'none'}).parent().prepend('<input type="file" name="'+obj.attr('name')+'"/>')
	$('#upload_list').append('<div>'+obj.val()+'<input type="button" value="cancel"/><div>');
	$("input[type='file']").change(replaceMe);
	$("input[type='button']").click(function(){
		$(this).parent().remove();
		$(obj).remove();
		return false; //safari fixes
	});
}
$("input[type='file']").change(replaceMe);
});

Where max is the counter that restricts the number of uploads. Since jQuery takes care of most of the complicated things. The code eventually became smaller. For some reason bind doesn't works for the event change. Thus, i will have to attach the event again. From pure JavaScript of 156 line into a few line of codes, jQuery definitely makes developers life much more easier (doesn't means the code produce by jQuery is much more efficient though.).

The Demo

The demo can be found here.

Conclusion

The above jQuery code has simplify the version found on stickman site. Although the display doesn't looks as attractive but my objective has been achieved. Sometimes, JavaScript can be harder to read compared to a jQuery one. However, JavaScript version still has a better efficiency as compared to a jQuery one.

Tutorial: disable _blank attribute from opening new window

Today is an interesting day. I was working on my project and found that i have a hard time looking for a way to disable my target attribute, _blank, which will open a new window and display the item there.  Surprisingly, i found tons of how to create pop out box and many discussion regarding setting up a window.open instruction. But no one care to explain how to stop or disable it! Hence, i decide to write it out myself.

Pop out box

We all know how to enable a pop out box. We can do that either by window.open or using target attribute _blank to pass the work to another window. We can also do that for form submission but bringing out another box is not very professional unless you are showing certain information. Hence, most of us will go with ajax or iframe way of synchronize submission. Nonetheless, pop out box is a necessity in our web environment. While opening a new window box is easy but how about disabling it?

Disable _blank attribute

Disabling a pop out box or anything that will pop out is pretty simple. If you try to recall how you disable those anchor link, you might have an idea how you are going to disable all other types of link. Most pop out box is being initialize by a click. Hence, the event that we are interested with is onclick event handler. However, different people will have different ways of disabling an anchor link such as

<a href="JavaScript: void();">link</a>

or

<a href="#">link</a>

But we are interested in

<a href="JavaScript: return false;">link</a>

In order to disable pop out, it is the same as how we used to disable link. Hence, if you have a link such as this,

<a href="http://somewhere.com" target="_blank">link</a>

it will bring you to somewhere.com on a new pop out box. And if you want to prevent that, you will do this.

<a href="http://somewhere.com" target="_blank" onclick='return false;'>link</a>

That's it! To prevent window.open, we just remove that sentence! haha..

jQuery and JavaScript CSS !important

Everyone who is familiar with CSS !important statement understood that it means that the style have the highest priority regardless of other priority. However, !important should be avoided as much as possible and order priority should be practice in CSS instead. In jQuery, there are times when we need to change the styling of our web program but programmers usually lack of such knowledge and inquire whether !important is available for jQuery css() method. In this article, we will discuss jQuery css() and JavaScript methods in term of using !important definition.

jQuery CSS !important

One thing that everyone must have wonder (those that haven't tried yet) is whether jQuery support declaration of !important for their css() method such as this.

jQuery('#id').css('height', '200px !important');

You will find that nothing will happen with a declaration of such manipulation. If we were to try out on pure JavaScript with the above declaration, it will be something like this.

document.getElementById('id').style.height = "200px !important";

Having a pure JavaScript instruction such as this will not work in most browser other than safari 3++. Hence, jQuery will definitely won't work too. This is not a bug but something that most browser doesn't acknowledge a need since inline style already have the highest priority other than user defined ones. (unless you do not want your user to change how they view your website).

Solution to jQuery CSS !important

Well, the typical way of getting !important will not work. Rather, you might want to try CSS DOM cssText. Hence, you will force !important to your jQuery statement by doing this.

jQuery('#id').css('cssText', 'height: 200px !important');

However, most people will be unfamiliar with cssText. cssText will overwrites the css of that particular element. Hence, you will have to redeclare the rule for that particular element all over again. On the other hand, if you are using JavaScript cssText, different browser treat cssText different such as ie you will define this way,

document.getElementById('id').style.cssText = 'height: 200px !important'

While normally you will use it this way.

document.getElementById('id').cssText = 'height: 200px !important'

Definitely, there is a better alternative such as using the cssRules/rules array which can specify the rule in that element to be modify.

The other more practical way of doing it is by introducing new class for your element. Instead of styling through jQuery or DOM object which is applying inline styling (means highest priority already), you should leave every majority styling or best all of the styling to an external style sheet that help you reduce some bytes on the script and also improve maintainability for both your code and style. You can do this using the toggleClass which adds a new class to that element automatically.

jQuery('#id').toggleClass('classname');

or you can do this in JavaScript by replacing the class (this is more efficient than the jQuery one since there isn't any additional checking and stuff)

document.getElementById('id').className = 'classname';

Summary

Using !important in CSS is not advisable since it might kill your web usability. Furthermore, there is no reason why !important should be use as inline styling already has the highest priority. Hence, you might want to reconsider applying !important on your script after thinking about the consequences that might bought to your users.

Tutorial: jQuery Select Box Manipulation Without Plugin

In jQuery, working with select box required some additional knowledge and interaction with jQuery. You may have some problem manipulating select box during your web development on jQuery. In this article we will discuss how you can solve this without any additional plugin to kill efficiency.

Create Selext Box In jQuery

Create a select box is very simple and straight forward. Just write a string with the normal select tag and a select box is created in jQuery

jQuery('#some_element').append('<select></select>');

I bet everyone would have tried this and it work. However, manipulating might be a more challenging task.

Add Option In Select Box With jQuery

One easy way is to create a string with the whole element and create it straight away

//obj is the list of option values
function(obj)
{
	var create = '<select id="test">';
	for(var i = 0; i < obj.length;i++)
	{
		create += '<option value="'+obj[i]+'">'+obj[i]+'</option>';
	}
	create += '</select>';
	jQuery('#some_element').append(create);
}

Another way to create a list of elements is to create its option and append it in using pure jQuery.

function(id, obj)
{
	jQuery('#some_element').append('<select id="'+id+'"></select>');
	jQuery.each(obj, function(val, text) {
		jQuery('#'+id).append(
		jQuery('<option></option').val(val).html(text)
	);})
}

You may not be familiar what i wrote above. Hence, a more javascript approach is shown below.

function(id, obj)
{
	jQuery('#some_element').append('<select id="'+id+'"></select>');
	for(var i = 0; i < obj.length;i++)
	{
		jQuery('#'+id).append('<option value="'+obj[i]+'">'+obj[i]+'</option')
	}
}

Get Select Box Value/Text In jQuery

Sometimes we want to know what is the value of the selected option. This is how we do it. Please bear in mind that there shouldn't be any spaces between the : and selected.

//#selectbox is the id of the select box
jQuery('#selectbox option:selected').val();

On the other hand, we can get the text of the option by doing this.

//#selectbox is the id of the select box
jQuery('#selectbox option:selected').text();

What if you know the value of the options you want to get instead of the one selected?

//#selectbox is the id of the select box
$("#selectList option[value='thisistheone']").text();

How about the first element on the select box?

//#selectbox is the id of the select box
$("#selectList option:first").text()

How about the n element on the select box?

//#selectbox is the id of the select box
$("#selectList option:eq(3)").text()

How about getting all elements but the first and last one in a select box?

//#selectbox is the id of the select box
$("#selectList option:not(option:first, option:last)").each(function(){
$(this).text();
});

Get Multiple Selected Value/Text In jQuery Select Box

Now we want to try to retrieve multiple selected values, we can do it easily with the following code.

	jQuery('#some_element:selected').each(function(){
		alert(jQuery(this).text());
		alert(jQuery(this).val());
	});

How about storing these values?

	var current = [];
	jQuery('#some_element:selected').each(function(index, selectedObj){
		current[index] = $(selectedObj).text();
	});

This way we eliminate the additional index needed to follow through the loop! How about shorten the cold a bit?

var foo = jQuery('#multiple :selected').map(function(){return jQuery(this).val();}).get();

This way we eliminate the need to create an array.

Remove Element In Select Box With jQuery

So we can get and add element into the select box. How about remove them? Basically, you will need to use one of the get element method describe above before applying the remove instruction.

jQuery('#selectbox: selected').remove();

Here we will remove all elements except the first and last one.

//#selectbox is the id of the select box
$("#selectbox option:not(option:first, option:last)").remove();

Select an option in the select box with jQuery

If you want to select an option in the select box, you can do this.

jQuery('#selectbox option[value="something"]').attr('selected', 'selected');

all option will be selected in this case.

UnSelect an option in the select box with jQuery

If you want to unselect an option in the select box, you can do this.

jQuery('#selectbox option[value="something"]').attr('selected', false);

all option will be unselected n this case.

OnChange find selected option from the select box

onchange find select box selected item.

$('#selectbox').change(function(){
	var val = $(this).find('option:selected').text();
	alert('i selected: ' + val);
});

onchange find select box selected items.

$('#selectbox').change(function(){
	$(this).find('option:selected').each(function () {
		alert('i selected: ' + $(this).text());
	}
});

Summary

There are definitely other tricks to manipulate select box. The above are just some of it.