jqtransform form events problem - javascript

I'm a web designer with css experience, but I'm not a JS developer.
I used jqtransform to style a search form ,
the problem is it removes all events from selectors and the search button .
here is the code before jqtransform
<input id="go-search" type="button" name="btn_search" value="search" onclick="searchLocations()" />
and after applying the script, the button doesn't do any thing
I opened the page source and here how it looks like:
<button class=" jqTransformButton" type="button" name="btn_search" id="go-search"><span><span>search</span></span></button>
Please help me !

I think it’s best to put new questions in new posts …
$(function() { $("form.jqtransform").jqTransform(); $("#city").click(populateDestrict); });
when assigning functions to an event by JavaScript, you only assign the function reference. putting parentheses behind a function identifyer will execute the function.
function myFunction(x)
{
alert(x);
return 1;
}
// correct, the onload event will trigger the function
window.onload = myFunction;
// alerts "[object Event]"
// wrong
window.onload = myFunction("hello");
// this assigns "1" to the onload property*
// * - IE may execute this, but no standard compliant browser

As far as can see only buttons are affected. The script replaces your original buttons with new ones, so everything besides the id, name, type & class attributes is removed. You would have to assign the function anew when jqtransform finished its job.
// after jqtransform
// probably $("#go-search").click(searchLocations); in jQuery, but I’m not a jQuery user … thus in plain JavaScript:
var bt = document.getElementById("go-search");
if (window.addEventListener) {
bt.addEventListener("click", searchLocations, false);
}
else {
bt.attachEvent("onclick", searchLocations);
}
I would hazard a guess at using it like
$(function() {
//find all form with class jqtransform and apply the plugin
$("form.jqtransform").jqTransform();
// fix your button
$("#go-search").click(searchLocations);
});

May be late but... Faced the same issue recently. and the solution was to use this version of the jqTransform script:
NOTE: 1) Open your jqTransform file, 2)DELETE everything, 3)COPY the code bellow 4) PASTE and 5) SAVE.
VOILA!!
/*
*
* jqTransform
* by mathieu vilaplana mvilaplana#dfc-e.com
* Designer ghyslain armand garmand#dfc-e.com
*
*
* Version 1.0 25.09.08
* Version 1.1 06.08.09
* Add event click on Checkbox and Radio
* Auto calculate the size of a select element
* Can now, disabled the elements
* Correct bug in ff if click on select (overflow=hidden)
* No need any more preloading !!
*
******************************************** */
(function($){
var defaultOptions = {preloadImg:true};
var jqTransformImgPreloaded = false;
var jqTransformPreloadHoverFocusImg = function(strImgUrl) {
//guillemets to remove for ie
strImgUrl = strImgUrl.replace(/^url\((.*)\)/,'$1').replace(/^\"(.*)\"$/,'$1');
var imgHover = new Image();
imgHover.src = strImgUrl.replace(/\.([a-zA-Z]*)$/,'-hover.$1');
var imgFocus = new Image();
imgFocus.src = strImgUrl.replace(/\.([a-zA-Z]*)$/,'-focus.$1');
};
/***************************
Labels
***************************/
var jqTransformGetLabel = function(objfield){
var selfForm = $(objfield.get(0).form);
var oLabel = objfield.next();
if(!oLabel.is('label')) {
oLabel = objfield.prev();
if(oLabel.is('label')){
var inputname = objfield.attr('id');
if(inputname){
oLabel = selfForm.find('label[for="'+inputname+'"]');
}
}
}
if(oLabel.is('label')){return oLabel.css('cursor','pointer');}
return false;
};
/* Hide all open selects */
var jqTransformHideSelect = function(oTarget){
var ulVisible = $('.jqTransformSelectWrapper ul:visible');
ulVisible.each(function(){
var oSelect = $(this).parents(".jqTransformSelectWrapper:first").find("select").get(0);
//do not hide if click on the label object associated to the select
if( !(oTarget && oSelect.oLabel && oSelect.oLabel.get(0) == oTarget.get(0)) ){$(this).hide();}
});
};
/* Check for an external click */
var jqTransformCheckExternalClick = function(event) {
if ($(event.target).parents('.jqTransformSelectWrapper').length === 0) { jqTransformHideSelect($(event.target)); }
};
/* Apply document listener */
var jqTransformAddDocumentListener = function (){
$(document).mousedown(jqTransformCheckExternalClick);
};
/* Add a new handler for the reset action */
var jqTransformReset = function(f){
var sel;
$('.jqTransformSelectWrapper select', f).each(function(){sel = (this.selectedIndex<0) ? 0 : this.selectedIndex; $('ul', $(this).parent()).each(function(){$('a:eq('+ sel +')', this).click();});});
$('a.jqTransformCheckbox, a.jqTransformRadio', f).removeClass('jqTransformChecked');
$('input:checkbox, input:radio', f).each(function(){if(this.checked){$('a', $(this).parent()).addClass('jqTransformChecked');}});
};
/***************************
Buttons
***************************/
$.fn.jqTransInputButton = function(){
return this.each(function(){
var newBtn = $('<button id="'+ this.id +'" name="'+ this.name +'" type="'+ this.type +'" class="'+ this.className +' jqTransformButton"><span><span>'+ $(this).attr('value') +'</span></span>')
.hover(function(){newBtn.addClass('jqTransformButton_hover');},function(){newBtn.removeClass('jqTransformButton_hover')})
.mousedown(function(){newBtn.addClass('jqTransformButton_click')})
.mouseup(function(){newBtn.removeClass('jqTransformButton_click')})
;
$(this).replaceWith(newBtn);
});
};
/***************************
Text Fields
***************************/
$.fn.jqTransInputText = function(){
return this.each(function(){
var $input = $(this);
if($input.hasClass('jqtranformdone') || !$input.is('input')) {return;}
$input.addClass('jqtranformdone');
var oLabel = jqTransformGetLabel($(this));
oLabel && oLabel.bind('click',function(){$input.focus();});
var inputSize=$input.width();
if($input.attr('size')){
inputSize = $input.attr('size')*10;
$input.css('width',inputSize);
}
$input.addClass("jqTransformInput").wrap('<div class="jqTransformInputWrapper"><div class="jqTransformInputInner"><div></div></div></div>');
var $wrapper = $input.parent().parent().parent();
$wrapper.css("width", inputSize+10);
$input
.focus(function(){$wrapper.addClass("jqTransformInputWrapper_focus");})
.blur(function(){$wrapper.removeClass("jqTransformInputWrapper_focus");})
.hover(function(){$wrapper.addClass("jqTransformInputWrapper_hover");},function(){$wrapper.removeClass("jqTransformInputWrapper_hover");})
;
/* If this is safari we need to add an extra class */
$.browser.safari && $wrapper.addClass('jqTransformSafari');
$.browser.safari && $input.css('width',$wrapper.width()+16);
this.wrapper = $wrapper;
});
};
/***************************
Check Boxes
***************************/
$.fn.jqTransCheckBox = function(){
return this.each(function(){
if($(this).hasClass('jqTransformHidden')) {return;}
var $input = $(this);
var inputSelf = this;
//set the click on the label
var oLabel=jqTransformGetLabel($input);
oLabel && oLabel.click(function(){aLink.trigger('click');});
var aLink = $('');
//wrap and add the link
$input.addClass('jqTransformHidden').wrap('<span class="jqTransformCheckboxWrapper"></span>').parent().prepend(aLink);
//on change, change the class of the link
$input.change(function(){
this.checked && aLink.addClass('jqTransformChecked') || aLink.removeClass('jqTransformChecked');
return true;
});
// Click Handler, trigger the click and change event on the input
aLink.click(function(){
//do nothing if the original input is disabled
if($input.attr('disabled')){return false;}
//trigger the envents on the input object
$input.trigger('click').trigger("change");
return false;
});
// set the default state
this.checked && aLink.addClass('jqTransformChecked');
});
};
/***************************
Radio Buttons
***************************/
$.fn.jqTransRadio = function(){
return this.each(function(){
if($(this).hasClass('jqTransformHidden')) {return;}
var $input = $(this);
var inputSelf = this;
oLabel = jqTransformGetLabel($input);
oLabel && oLabel.click(function(){aLink.trigger('click');});
var aLink = $('');
$input.addClass('jqTransformHidden').wrap('<span class="jqTransformRadioWrapper"></span>').parent().prepend(aLink);
$input.change(function(){
inputSelf.checked && aLink.addClass('jqTransformChecked') || aLink.removeClass('jqTransformChecked');
return true;
});
// Click Handler
aLink.click(function(){
if($input.attr('disabled')){return false;}
$input.trigger('click').trigger('change');
// uncheck all others of same name input radio elements
$('input[name="'+$input.attr('name')+'"]',inputSelf.form).not($input).each(function(){
$(this).attr('type')=='radio' && $(this).trigger('change');
});
return false;
});
// set the default state
inputSelf.checked && aLink.addClass('jqTransformChecked');
});
};
/***************************
TextArea
***************************/
$.fn.jqTransTextarea = function(){
return this.each(function(){
var textarea = $(this);
if(textarea.hasClass('jqtransformdone')) {return;}
textarea.addClass('jqtransformdone');
oLabel = jqTransformGetLabel(textarea);
oLabel && oLabel.click(function(){textarea.focus();});
var strTable = '<table cellspacing="0" cellpadding="0" border="0" class="jqTransformTextarea">';
strTable +='<tr><td id="jqTransformTextarea-tl"></td><td id="jqTransformTextarea-tm"></td><td id="jqTransformTextarea-tr"></td></tr>';
strTable +='<tr><td id="jqTransformTextarea-ml"> </td><td id="jqTransformTextarea-mm"><div></div></td><td id="jqTransformTextarea-mr"> </td></tr>';
strTable +='<tr><td id="jqTransformTextarea-bl"></td><td id="jqTransformTextarea-bm"></td><td id="jqTransformTextarea-br"></td></tr>';
strTable +='</table>';
var oTable = $(strTable)
.insertAfter(textarea)
.hover(function(){
!oTable.hasClass('jqTransformTextarea-focus') && oTable.addClass('jqTransformTextarea-hover');
},function(){
oTable.removeClass('jqTransformTextarea-hover');
})
;
textarea
.focus(function(){oTable.removeClass('jqTransformTextarea-hover').addClass('jqTransformTextarea-focus');})
.blur(function(){oTable.removeClass('jqTransformTextarea-focus');})
.appendTo($('#jqTransformTextarea-mm div',oTable))
;
this.oTable = oTable;
if($.browser.safari){
$('#jqTransformTextarea-mm',oTable)
.addClass('jqTransformSafariTextarea')
.find('div')
.css('height',textarea.height())
.css('width',textarea.width())
;
}
});
};
/***************************
Select
***************************/
$.fn.jqTransSelect = function(){
return this.each(function(index){
var $select = $(this);
if($select.hasClass('jqTransformHidden')) {return;}
if($select.attr('multiple')) {return;}
var oLabel = jqTransformGetLabel($select);
/* First thing we do is Wrap it */
var $wrapper = $select
.addClass('jqTransformHidden')
.wrap('<div class="jqTransformSelectWrapper"></div>')
.parent()
.css({zIndex: 10-index})
;
/* Now add the html for the select */
$wrapper.prepend('<div><span></span></div><ul></ul>');
var $ul = $('ul', $wrapper).css('width',$select.width()).hide();
/* Now we add the options */
$('option', this).each(function(i){
var oLi = $('<li>'+ $(this).html() +'</li>');
$ul.append(oLi);
});
/* Add click handler to the a */
$ul.find('a').click(function(){
$('a.selected', $wrapper).removeClass('selected');
$(this).addClass('selected');
/* Fire the onchange event */
//if ($select[0].selectedIndex != $(this).attr('index') && $select[0].onchange) { $select[0].selectedIndex = $(this).attr('index'); $select[0].onchange(); }
if ($select[0].selectedIndex != $(this).attr('index')) { $select[0].selectedIndex = $(this).attr('index'); $select.change(); }
//Redundent code
//$select[0].selectedIndex = $(this).attr('index');
$('span:eq(0)', $wrapper).html($(this).html());
$ul.hide();
return false;
});
/* Set the default */
$('a:eq('+ this.selectedIndex +')', $ul).click();
$('span:first', $wrapper).click(function(){$("a.jqTransformSelectOpen",$wrapper).trigger('click');});
oLabel && oLabel.click(function(){$("a.jqTransformSelectOpen",$wrapper).trigger('click');});
this.oLabel = oLabel;
/* Apply the click handler to the Open */
var oLinkOpen = $('a.jqTransformSelectOpen', $wrapper)
.click(function(){
//Check if box is already open to still allow toggle, but close all other selects
if( $ul.css('display') == 'none' ) {jqTransformHideSelect();}
if($select.attr('disabled')){return false;}
$ul.slideToggle('fast', function(){
var offSet = ($('a.selected', $ul).offset().top - $ul.offset().top);
$ul.animate({scrollTop: offSet});
});
return false;
})
;
// Set the new width
var iSelectWidth = $select.outerWidth();
var oSpan = $('span:first',$wrapper);
var newWidth = (iSelectWidth > oSpan.innerWidth())?iSelectWidth+oLinkOpen.outerWidth():$wrapper.width();
$wrapper.css('width',newWidth);
$ul.css('width',newWidth-2);
oSpan.css({width:iSelectWidth});
// Calculate the height if necessary, less elements that the default height
//show the ul to calculate the block, if ul is not displayed li height value is 0
$ul.css({display:'block',visibility:'hidden'});
var iSelectHeight = ($('li',$ul).length)*($('li:first',$ul).height());//+1 else bug ff
(iSelectHeight < $ul.height()) && $ul.css({height:iSelectHeight,'overflow':'hidden'});//hidden else bug with ff
$ul.css({display:'none',visibility:'visible'});
});
};
$.fn.jqTransform = function(options){
var opt = $.extend({},defaultOptions,options);
/* each form */
return this.each(function(){
var selfForm = $(this);
if(selfForm.hasClass('jqtransformdone')) {return;}
selfForm.addClass('jqtransformdone');
$('input:submit, input:reset, input[type="button"]', this).jqTransInputButton();
$('input:text, input:password', this).jqTransInputText();
$('input:checkbox', this).jqTransCheckBox();
$('input:radio', this).jqTransRadio();
$('textarea', this).jqTransTextarea();
if( $('select', this).jqTransSelect().length > 0 ){jqTransformAddDocumentListener();}
selfForm.bind('reset',function(){var action = function(){jqTransformReset(this);}; window.setTimeout(action, 10);});
//preloading dont needed anymore since normal, focus and hover image are the same one
/*if(opt.preloadImg && !jqTransformImgPreloaded){
jqTransformImgPreloaded = true;
var oInputText = $('input:text:first', selfForm);
if(oInputText.length > 0){
//pour ie on eleve les ""
var strWrapperImgUrl = oInputText.get(0).wrapper.css('background-image');
jqTransformPreloadHoverFocusImg(strWrapperImgUrl);
var strInnerImgUrl = $('div.jqTransformInputInner',$(oInputText.get(0).wrapper)).css('background-image');
jqTransformPreloadHoverFocusImg(strInnerImgUrl);
}
var oTextarea = $('textarea',selfForm);
if(oTextarea.length > 0){
var oTable = oTextarea.get(0).oTable;
$('td',oTable).each(function(){
var strImgBack = $(this).css('background-image');
jqTransformPreloadHoverFocusImg(strImgBack);
});
}
}*/
}); /* End Form each */
};/* End the Plugin */
})(jQuery);
You could also get the same here: http://pastebin.com/Q1pYMKZ2

Related

How to dynamically add elements via jQuery

The script below creates a slider widget the takes a definition list and turns it into a slide deck. Each dt element is rotated via css to become the "spine", which is used to reveal that dt's sibling dd element.
What I'm trying to do is to enhance it so that I can have the option to remove the spines from the layout and just use forward and back buttons on either side of the slide deck. To do that, I set the dt's to display:none via CSS and use the code under the "Remove spine layout" comment to test for visible.
This works fine to remove the spines, now I need to dynamically create 2 absolutely positioned divs to hold the left and right arrow images, as well as attach a click handler to them.
My first problem is that my attempt to create the divs is not working.
Any help much appreciated.
jQuery.noConflict();
(function(jQuery) {
if (typeof jQuery == 'undefined') return;
jQuery.fn.easyAccordion = function(options) {
var defaults = {
slideNum: true,
autoStart: false,
pauseOnHover: true,
slideInterval: 5000
};
this.each(function() {
var settings = jQuery.extend(defaults, options);
jQuery(this).find('dl').addClass('easy-accordion');
// -------- Set the variables ------------------------------------------------------------------------------
jQuery.fn.setVariables = function() {
dlWidth = jQuery(this).width()-1;
dlHeight = jQuery(this).height();
if (!jQuery(this).find('dt').is(':visible')){
dtWidth = 0;
dtHeight = 0;
slideTotal = 0;
// Add an element to rewind to previous slide
var slidePrev = document.createElement('div');
slidePrev.className = 'slideAdv prev';
jQuery(this).append(slidePrev);
jQuery('.slideAdv.prev').css('background':'red','width':'50px','height':'50px');
// Add an element to advance to the next slide
var slideNext = document.createElement('div');
slideNext.className = 'slideAdv next';
jQuery(this).append(slideNext);
jQuery('.slideAdv.next').css('background':'green','width':'50px','height':'50px');
}
else
{
dtWidth = jQuery(this).find('dt').outerHeight();
if (jQuery.browser.msie){ dtWidth = jQuery(this).find('dt').outerWidth();}
dtHeight = dlHeight - (jQuery(this).find('dt').outerWidth()-jQuery(this).find('dt').width());
slideTotal = jQuery(this).find('dt').size();
}
ddWidth = dlWidth - (dtWidth*slideTotal) - (jQuery(this).find('dd').outerWidth(true)-jQuery(this).find('dd').width());
ddHeight = dlHeight - (jQuery(this).find('dd').outerHeight(true)-jQuery(this).find('dd').height());
};
jQuery(this).setVariables();
// -------- Fix some weird cross-browser issues due to the CSS rotation -------------------------------------
if (jQuery.browser.safari){ var dtTop = (dlHeight-dtWidth)/2; var dtOffset = -dtTop; /* Safari and Chrome */ }
if (jQuery.browser.mozilla){ var dtTop = dlHeight - 20; var dtOffset = - 20; /* FF */ }
if (jQuery.browser.msie){ var dtTop = 0; var dtOffset = 0; /* IE */ }
if (jQuery.browser.opera){ var dtTop = (dlHeight-dtWidth)/2; var dtOffset = -dtTop; } /* Opera */
// -------- Getting things ready ------------------------------------------------------------------------------
var f = 1;
var paused = false;
jQuery(this).find('dt').each(function(){
jQuery(this).css({'width':dtHeight,'top':dtTop,'margin-left':dtOffset});
// add unique id to each tab
jQuery(this).addClass('spine_' + f);
// add active corner
var corner = document.createElement('div');
corner.className = 'activeCorner spine_' + f;
jQuery(this).append(corner);
if(settings.slideNum == true){
jQuery('<span class="slide-number">'+f+'</span>').appendTo(this);
if(jQuery.browser.msie){
var slideNumLeft = parseInt(jQuery(this).find('.slide-number').css('left'));
if(jQuery.browser.version == 6.0 || jQuery.browser.version == 7.0){
jQuery(this).find('.slide-number').css({'bottom':'auto'});
slideNumLeft = slideNumLeft - 14;
jQuery(this).find('.slide-number').css({'left': slideNumLeft})
}
if(jQuery.browser.version == 8.0 || jQuery.browser.version == 9.0){
var slideNumTop = jQuery(this).find('.slide-number').css('bottom');
var slideNumTopVal = parseInt(slideNumTop) + parseInt(jQuery(this).css('padding-top')) - 20;
jQuery(this).find('.slide-number').css({'bottom': slideNumTopVal});
slideNumLeft = slideNumLeft - 10;
jQuery(this).find('.slide-number').css({'left': slideNumLeft})
jQuery(this).find('.slide-number').css({'marginTop': 10});
}
} else {
var slideNumTop = jQuery(this).find('.slide-number').css('bottom');
var slideNumTopVal = parseInt(slideNumTop) + parseInt(jQuery(this).css('padding-top'));
jQuery(this).find('.slide-number').css({'bottom': slideNumTopVal});
}
}
f = f + 1;
});
if(jQuery(this).find('.active').size()) {
jQuery(this).find('.active').next('dd').addClass('active');
} else {
jQuery(this).find('dt:first').addClass('active').next('dd').addClass('active');
}
jQuery(this).find('dt:first').css({'left':'0'}).next().css({'left':dtWidth});
jQuery(this).find('dd').css({'width':ddWidth,'height':ddHeight});
// -------- Functions ------------------------------------------------------------------------------
jQuery.fn.findActiveSlide = function() {
var i = 1;
this.find('dt').each(function(){
if(jQuery(this).hasClass('active')){
activeID = i; // Active slide
} else if (jQuery(this).hasClass('no-more-active')){
noMoreActiveID = i; // No more active slide
}
i = i + 1;
});
};
jQuery.fn.calculateSlidePos = function() {
var u = 2;
jQuery(this).find('dt').not(':first').each(function(){
var activeDtPos = dtWidth*activeID;
if(u <= activeID){
var leftDtPos = dtWidth*(u-1);
jQuery(this).animate({'left': leftDtPos});
if(u < activeID){ // If the item sits to the left of the active element
jQuery(this).next().css({'left':leftDtPos+dtWidth});
} else{ // If the item is the active one
jQuery(this).next().animate({'left':activeDtPos});
}
} else {
var rightDtPos = dlWidth-(dtWidth*(slideTotal-u+1));
jQuery(this).animate({'left': rightDtPos});
var rightDdPos = rightDtPos+dtWidth;
jQuery(this).next().animate({'left':rightDdPos});
}
u = u+ 1;
});
setTimeout( function() {
jQuery('.easy-accordion').find('dd').not('.active').each(function(){
jQuery(this).css({'display':'none'});
});
}, 400);
};
jQuery.fn.activateSlide = function() {
this.parent('dl').setVariables();
this.parent('dl').find('dd').css({'display':'block'});
this.parent('dl').find('dd.plus').removeClass('plus');
this.parent('dl').find('.no-more-active').removeClass('no-more-active');
this.parent('dl').find('.active').removeClass('active').addClass('no-more-active');
this.addClass('active').next().addClass('active');
this.parent('dl').findActiveSlide();
if(activeID < noMoreActiveID){
this.parent('dl').find('dd.no-more-active').addClass('plus');
}
this.parent('dl').calculateSlidePos();
};
jQuery.fn.rotateSlides = function(slideInterval, timerInstance) {
var accordianInstance = jQuery(this);
timerInstance.value = setTimeout(function(){accordianInstance.rotateSlides(slideInterval, timerInstance);}, slideInterval);
if (paused == false){
jQuery(this).findActiveSlide();
var totalSlides = jQuery(this).find('dt').size();
var activeSlide = activeID;
var newSlide = activeSlide + 1;
if (newSlide > totalSlides) {newSlide = 1; paused = true;}
jQuery(this).find('dt:eq(' + (newSlide-1) + ')').activateSlide(); // activate the new slide
}
}
// -------- Let's do it! ------------------------------------------------------------------------------
function trackerObject() {this.value = null}
var timerInstance = new trackerObject();
jQuery(this).findActiveSlide();
jQuery(this).calculateSlidePos();
if (settings.autoStart == true){
var accordianInstance = jQuery(this);
var interval = parseInt(settings.slideInterval);
timerInstance.value = setTimeout(function(){
accordianInstance.rotateSlides(interval, timerInstance);
}, interval);
}
jQuery(this).find('dt').not('active').click(function(){
var accordianInstance = jQuery(this); //JSB to fix bug with IE < 9
jQuery(this).activateSlide();
clearTimeout(timerInstance.value);
timerInstance.value = setTimeout(function(){
accordianInstance.rotateSlides(interval, timerInstance);
}, interval);
});
if (!(jQuery.browser.msie && jQuery.browser.version == 6.0)){
jQuery('dt').hover(function(){
jQuery(this).addClass('hover');
}, function(){
jQuery(this).removeClass('hover');
});
}
if (settings.pauseOnHover == true){
jQuery('dd').hover(function(){
paused = true;
}, function(){
paused = false;
});
}
});
};
})(jQuery);
Creating elements in jQuery is easy:
$newDiv = $('<div />');
$newDiv.css({
'position': 'absolute',
'top': '10px',
'left': '10px'
});
$newDiv.on('click', function() {
alert('You have clicked me');
});
$('#your_container').append($newDiv);

collapsible/expandable table behaviour

need help with some jquery/js/jsp functionality..
I have a collapsible table script:
(function($){
$.fn.extend({
setupCollapstable: function(options) {
var defaults = {
displayStyle: "Image",
autoCheckbox: true,
toggleMinus: "/resource/images/collapse_close.gif",
togglePlus: "/resource/images/collapse_open.gif"
};
var options = $.extend(defaults, options);
var toggleMinus = options.toggleMinus
var togglePlus = options.togglePlus
return this.each(function() {
//Creating a reference to the object
var obj = $(this);
//Break out the individual tbody elements
var rowGroups = $('tbody', obj);
//Loop through every tbody to setup collapsable and click events
$.each( rowGroups, function( intIndex, objValue ){
parentRow = $('th:first-child', objValue);
childCount = parentRow.parent().siblings().length;
if (childCount != 0) {
//console.log ("ParentRow: " + parentRow + " - ChildCount is: " + childCount);
parentRow.prepend('<img src="' + togglePlus + '" alt="collapse this section" />');
parentRow.parent().siblings().fadeOut('fast');
$('img', parentRow).addClass('clickable').click(function(e) {
e.preventDefault();
var toggleSrc = $(this).attr('src');
if ( toggleSrc == toggleMinus ) {
$(this).attr('src', togglePlus).parents('tr').siblings().fadeOut('fast');
} else{
$(this).attr('src', toggleMinus).parents('tr').siblings().fadeIn('fast');
};
});
var parentCheckbox = $(':checkbox', parentRow.siblings())
var childCheckboxes = $(':checkbox', parentRow.parent().siblings());
parentCheckbox.click(function(e){
var checked_status = parentCheckbox.attr('checked')?1:0;
childCheckboxes.each(function(){
this.checked = checked_status;
});
});
} else {
parentRow.addClass("indented");
}
});
//console.dir (objValue);
});
}
});
})(jQuery);
From my JSP I call it as such....
<script type="text/javascript" src="/resource/js/jquery.collapstable.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('table.collapstable').setupCollapstable();
});
</script>
usage:
<table class="collapstable NoTableBorder">
when I click on the image icon the table properly collapses and expands, however I want it to be initially expanded if a certain checkbox is checked (on the JSP).
so I would have an onclick="showOrHide()" function for that checkbox input which would collapse or expand the table.
i've attached an image to for a visual representation, the collpase table is the "+/-" icon (next to the bold VISA header) while the checkbox which decides if it should be expanded for shown is the "active" checkbox..
any help with this would be amazing...
You can add a condition just before the collapse / expand function call
<script type="text/javascript">
$(document).ready(function(){
if (checkboxname.checked){
// Set flags to show the table expanded
}else{
// Set flags to show the table collapsed
}
$('table.collapstable').setupCollapstable();
});
</script>

jQuery + Get and Compare Element VALUE and ALT

I am trying to modify following script to do this check:
Check if input VALUE and ALT are the same.
If yes: empty VALUE
If no: keep VALUE
This is the script I am working on: (the part that i commented out, is where i tryed to figure out how to make the changes myself).
<script language="Javascript" type="text/javascript">
//<![CDATA[
jQuery.fn.placeholder = function(){
return this.each(function(){
var element = $(this)
var insertedNow =element.after("<span class='placeholder-spanbox'>"+ element.attr('alt')+ "</span>").attr("alt","").next('.placeholder-spanbox');
var leftOffset = (element.innerWidth() - element.width())/2+parseInt(element.css("border-left-width"));
var topOffset = ((element.innerHeight() - element.height())/2)+parseInt(element.css("border-top-width"));
var inputWidth = element.width();
var inputHeight = element.height();
var placeholderPos = inputHeight + topOffset + leftOffset;
insertedNow.css("padding-left",leftOffset+"px").css("padding-top",topOffset+"px").css("opacity",0.5).css("display","block").css("margin-top",-placeholderPos).css("cursor","text");
var objCSS = {'-webkit-transition':'opacity 100ms ease-in','-moz-transition':'opacity 100ms ease-in','-o-transition':'opacity 100ms ease-in','-ms-transition':'opacity 100ms ease-in','transition':'opacity 100ms ease-in','font-size':element.css('font-size'),'font-family':element.css('font-family'),'color':'#000000','font-weight':element.css('font-weight'),'width':element.css('width'),'float':element.css('float')};
insertedNow.css(objCSS);
//insertedNow.offset(element.offset());
element.bind("focus",updateSpanStatusFocus);
element.bind("keydown",updateSpanStatusKeyDown);
element.bind("keyup",updateSpanStatusKeyUp);
element.bind("blur",updateSpanStatusBlur);
insertedNow.bind("click",clickSpanBox);
var inputVal = element.attr("value");
var inputAlt = element.attr("alt");
//$(this).attr("value",+inputVal);
// if(inputVal == inputAlt){
// $(this).attr("value","123");
// }
if(element.val()!==""){
insertedNow.css({'opacity':0});
}
});
function clickSpanBox(event){
event.preventDefault();
var inputBox = $(this).prev();
inputBox.focus();
}
function updateSpanStatusFocus(event){
var $this= $(this);
if($this.val()==""){
var spanBox = $this.next('.placeholder-spanbox');
spanBox.css("opacity","0.3");
}
}
function updateSpanStatusKeyUp(event){
var $this= $(this);
if($this.val()==""){
var spanBox = $this.next('.placeholder-spanbox');
spanBox.css("opacity","0.3");
}
}
function updateSpanStatusKeyDown(event){
var $this = $(this);
if($this.val()=="" && (event.keyCode>54 || event.keyCode == 32)){
var spanBox = $this.next('.placeholder-spanbox');
spanBox.css("opacity","0");
}
}
function updateSpanStatusBlur(){
var $this= $(this);
$this.val(Trim($this.val()+''));
if($this.val()==""){
var spanBox = $this.next('.placeholder-spanbox');
spanBox.css("opacity","0.5");
spanBox.css("color","#000000");
}
}
}
$(document).ready(function(){
$('.spanOverlay').placeholder();
});
//]]>
</script>
And here the html markup example:
<input type='text' name="userName" class='contactInput spanOverlay' alt='* Name' value='test'></input>
Thanks for your help!!
Is this what you want?
if (element.val() == element.attr('alt')) {
element.val("");
}
there's something called .defaultValue in javascript u could use this to compare against current value
here's an example on how its done
http://www.miuaiga.com/index.cfm/2009/8/31/jQuery-form-input-defaultValue

jQuery click event

In the following code, the click event is added explicitly to the body, so that even if click outside the button say on the body the div with ID tip1 should close with a fade effect.
The problem here is that the the div closes even if we click on the div itself.
Any idea on this would help ..
$(document).ready(function(){
$('.button').getit({speed: 150, delay: 300});
});
$.fn.getit = function(options){
var defaults = {
speed: 200,
delay: 300
};
var options = $.extend(defaults, options);
$(this).each(function(){
var $this = $(this);
var tip = $('.tip');
this.title = "";
var offset = $(this).offset();
var tLeft = offset.left;
var tTop = offset.top;
var tWidth = $this.width();
var tHeight = $this.height();
$this.click(
function() {
if($('.tip').hasClass('.active101')) {
$('.tip').fadeOut("slow");
$('.tip').removeClass('.active101').addClass('.inactive101');
}
else {
setTip(tTop, tLeft);
$('body').bind('click',function(e) {
var parentElement = "button1";
var parentElement2 = "tip1"
if( e.target.id != parentElement) {
$('.tip').fadeOut("slow");
$('.tip').removeClass('.active101').addClass('.inactive101');
}
});
$('.tip').removeClass('.inactive101').addClass('.active101');
setTimer();
}
},
function() {
if($('.tip').hasClass('.inactive101')) {
stopTimer();
tip.hide();
}
}
);
setTimer = function() {
$this.showTipTimer = setInterval("showTip()", defaults.delay);
}
stopTimer = function() {
clearInterval($this.showTipTimer);
}
setTip = function(top, left){
var topOffset = tip.height();
var xTip = (left-440)+"px";
var yTip = (top-topOffset+100)+"px";
tip.css({'top' : yTip, 'left' : xTip});
}
showTip = function(){
stopTimer();
tip.animate({"top": "+=20px", "opacity": "toggle"}, defaults.speed);
}
});
};
<div class="main">
<a href="#" class="button" id="button1">
Click Me!
</a>
<div class="tip" id="tip1">Hello again</div>
</div>
Set the click event on your div to 'stopPropagation'
http://api.jquery.com/event.stopPropagation/
Perhaps you can bind a click event to the div itself and prevent the click event from bubbling up?
$("#div").click(function(e) {
e.stopPropagation();
});
Rick.
you should stop the event's propagation
you should check if any of the element's children are clicked (if you click a child of that element, the element would close)
you should probably be more careful with your selectors(if you intend to use this only on one element - because you are verifying with an id ('#button1' which is unique), you shouldn't bind the getit function to all the elements with class '.button')
if( e.target.id != parentElement
&& $(e.target).parents('#'+parentElement).length == 0) {
$('.tip').fadeOut("slow");
$('.tip').removeClass('.active101').addClass('.inactive101');
e.stopPropagation();
}
thanks for your answers. Tried with all of them and each worked. But I also found another solution to this by just adding another condition:
if (e.target.id != parentElement && e.target.id != parentElement2) {
$('.tip').fadeOut("slow");
$('.tip').removeClass('.active101').addClass('.inactive101');
}

Custom styled select box

am trying to use javascript for custom styled select boxes from www.gerrendesign.com/entry_images/selectboxdemo.zip
and as I have plenty entries inside one of select box I need to make but am stuck in creation of scrolling function.
As this select boxes are compatible with almost all older and new browsers. I need only suggestion or solution how to add scroll in this linked/attached files above - if select box is populated with plenty of entries (example cities, states, or exchange rates...)
Am stuck here...
Thanks for your cooperation
Ivan
THIS IS CODE:
$(document).ready(function(){
// first locate all of the select tags on the page and hide them
$("select.changeMe").css('display','none');
//now, for each select box, run this function
$("select.changeMe").each(function(){
var curSel = $(this);
// get the CSS width from the original select box
var gddWidth = $(curSel).css('width');
var gddWidthL = gddWidth.slice(0,-2);
var gddWidth2 = gddWidthL - 28;
var gddWidth3 = gddWidthL - 16;
// build the new div structure
var gddTop = '<div style="width:' + gddWidthL + 'px" class="selectME" tabindex="0"><div class="cornerstop"><div><div></div></div></div><div class="middle"><div><div><div>';
//get the default selected option
var whatSelected = $(curSel).children('option:selected').text();
//write the default
var gddFirst = '<div class="first"><span class="selectME gselected" style="width:'+ gddWidth2 + 'px;">'+ whatSelected +'</span><span id="arrowImg"></span><div class="clears"></div></div><ul class="selectME">';
// create a new array of div options from the original's options
var addItems = new Array();
$(curSel).children('option').each( function() {
var text = $(this).text();
var selVal = $(this).attr('value');
var before = '<li style="width:' + gddWidthL + 'px;"><a href="#" rel="' + selVal + '" tabindex="0" style="width:' + gddWidth3 + 'px;">';
var after = '</a></li>';
addItems.push(before + text + after);
});
//hide the default from the list of options
var removeFirst = addItems.shift();
// create the end of the div selectbox and close everything off
var gddBottom ='</ul></div></div></div></div><div class="cornersbottom"><div><div></div></div></div></div>'
//write everything after each selectbox
var GDD = gddTop + gddFirst + addItems.join('') + gddBottom;
$(curSel).after(GDD);
//this var selects the div select box directly after each of the origials
var nGDD = $(curSel).next('div.selectME');
$(nGDD).find('li:first').addClass("first");
$(nGDD).find('li:last').addClass('last');
//handle the on click functions - push results back to old text box
$(nGDD).click( function(e) {
var myTarA = $(e.target).attr('rel');
var myTarT = $(e.target).text();
var myTar = $(e.target);
//if closed, then open
if( $(nGDD).find('li').css('display') == 'none')
{
//this next line closes any other selectboxes that might be open
$('div.selectME').find('li').css('display','none');
$(nGDD).find('li').css('display','block');
//if user clicks off of the div select box, then shut the whole thing down
$(document.window || 'body').click( function(f) {
var myTar2 = $(f.target);
if (myTar2 !== nGDD) {$(nGDD).find('li').css('display','none');}
});
return false;
}
else
{
if (myTarA == null){
$(nGDD).find('li').css('display','none');
return false;
}
else {
//set the value of the old select box
$(curSel).val(myTarA);
//set the text of the new one
$(nGDD).find('span.gselected').text(myTarT);
$(nGDD).find('li').css('display','none');
return false;
}
}
//handle the tab index functions
}).focus( function(e) {
$(nGDD).find('li:first').addClass('currentDD');
$(nGDD).find('li:last').addClass('lastDD');
function checkKey(e){
//on keypress handle functions
function moveDown() {
var current = $(nGDD).find('.currentDD:first');
var next = $(nGDD).find('.currentDD').next();
if ($(current).is('.lastDD')){
return false;
} else {
$(next).addClass('currentDD');
$(current).removeClass('currentDD');
}
}
function moveUp() {
var current = $(nGDD).find('.currentDD:first');
var prev = $(nGDD).find('.currentDD').prev();
if ($(current).is('.first')){
return false;
} else {
$(prev).addClass('currentDD');
$(current).removeClass('currentDD');
}
}
var curText = $(nGDD).find('.currentDD:first').text();
var curVal = $(nGDD).find('.currentDD:first a').attr('rel');
switch (e.keyCode) {
case 40:
$(curSel).val(curVal);
$(nGDD).find('span.gselected').text(curText);
moveDown();
return false;
break;
case 38:
$(curSel).val(curVal);
$(nGDD).find('span.gselected').text(curText);
moveUp();
return false;
break;
case 13:
$(nGDD).find('li').css('display','none');
}
}
$(document).keydown(checkKey);
}).blur( function() {
$(document).unbind('keydown');
});
});
});
You could render the list inside a div, that has either a fixed height or a max-height (depending on your cross-browser requirements). Presuming the default scroll bar is ok...
If structure is something in the direction of
<div class="select_data_container">
<ul class="select_rows">
<li>row1</li>
<li>row2</li>
</ul>
</div>
CSS-example could be
.select_data_container {overflow-y: auto; height: 200px;}
.select_rows {display:block;}

Categories