Disable button after form reload - javascript

After I submit an invalid form page it redirects back to the same form page.
I want to be able to disable the "Find address" button and "House No" input field.
At the moment only "House No" input stays disabled and not the "Find address" button.
Please help.
var enableDisableFindAddress = function(postcodeLookupAvailabilityCountries) {
var $this = $( ".find-address-country"),
addressType = $this.data( "addresstype" ),
countryISO = $this.val(),
availableCountries = postcodeLookupAvailabilityCountries;
var foundAvailableISO = false,
HouseNameOrNoFieldId = "#" + addressType + "_house_no_or_name",
searchBtnID = "#" + addressType + "_search_btn";
for( i = 0; i < availableCountries.length; i++ ){
if( countryISO == availableCountries[i] ){
foundAvailableISO = true;
break;
}
}
if ( foundAvailableISO ) {
$( HouseNameOrNoFieldId ).prop( "disabled", false );
$( searchBtnID ).prop( "disabled", false );
} else {
$( HouseNameOrNoFieldId ).prop( "disabled", true );
$( searchBtnID ).prop( "disabled", true );
alert("I am suppose to disable this")
}
}
// THIS IS NOT WORKING
if ( $( ".find-address-country").val() !== "" ) {
enableDisableFindAddress( postcodeLookupAvailabilityCountries );
}
// THIS IS WORKING
$( ".find-address-country" ).change( function() {
enableDisableFindAddress( postcodeLookupAvailabilityCountries );
});

Related

Javascript problem with loop for hiding/showing element depending on checkbox

I'm trying to hide/show an element depending on if the corresponding checkbox is checked or not.
There are two checkbox each one corresponding to an element. The name of thos checkboxes and elements depends on a variable stored in vendorIds array.
The problem is that the code only works for ths second variable stocked in the array.
I suppose that the problem comes from the "for" loop but I'am beginner and I don't see what's wrong.
Here is the code :
<script>
jQuery(function($){
console.log(vendorIds);
for (var i=0; i<vendorIds.length; i++) {
var vendorId = vendorIds[i];
console.log(vendorId);
var vendorId = vendorIds[i];
console.log(vendorId);
var ism = 'input[name^="shipping_method['+vendorId+']"]', ismc = ism+':checked',
csa = 'input#ship-to-different-address-checkbox',
rq = '-required', vr = 'validate'+rq, w = 'woocommerce', wv = w+'-validated',
iv = '-invalid', fi = '-field', wir = w+iv+' '+w+iv+rq+fi,
b = '#wcfmd_delvery_time_'+vendorId,
livraison = 'Livraison:1';
console.log(b);
}
(function(i){
// Utility function to shows or hide checkout fields
function showHide( action='show', selector='' ){
if( action == 'show' )
$(selector).show(function(){
$(this).addClass(vr);
$(this).removeClass(wv);
$(this).removeClass(wir);
if( $(selector+' > label > abbr').html() == undefined )
$(selector+' label').append('<?php echo $required_html; ?>');
});
else
$(selector).hide(function(){
$(this).removeClass(vr);
$(this).removeClass(wv);
$(this).removeClass(wir);
if( $(selector+' > label > abbr').html() != undefined )
$(selector+' label > .required').remove();
});
}
// Initializing at start after checkout init (Based on the chosen shipping method)
setTimeout(function(){
if( $(ismc).val() == livraison ) // Choosen "livraison" (Hidding "Take away")
{
showHide('show',b);
}
else
{
showHide('hide',b);
}
}, 100);
// When shipping method is changed (Live event)
$( 'form.checkout' ).on( 'change', ism, function() {
if( $(ismc).val() == livraison )
{
showHide('show',b);
}
else
{
showHide('hide',b);
}
});
})(i);
});
</script>
Thanks in advance.
Have an nice day.
Fred
Here is the answer if one day someone need it
<script>
jQuery(document).ready(function($){
for (var i=0; i<vendorIds.length; i++) {
var vendorId = vendorIds[i];
var ism = 'input[name^="shipping_method['+vendorId+']"]', ismc = ism+':checked',
b = '#livraison_'+vendorId,
livraison = 'Livraison:1';
// When shipping method is changed (Live event)
$( 'form.checkout' ).on( 'change', ism, function(e) {
var name = e.currentTarget.name;
var dataValue = $('input[name ="'+name+'"]').attr('data-index');
var b = '#livraison_'+dataValue;
var ismc = 'input[name^="shipping_method['+dataValue+']"]:checked';
var livraison = 'Livraison:1';
if( $(ismc).val() == livraison )
{
$(b).show();
}
else
{
$(b).hide();
}
});
// Initializing at start after checkout init (Based on the chosen shipping method)
setTimeout(function(){
$( "input.shipping_method" ).each(function() {
var name = $(this).attr("name");
var type = $(this).attr("type");
var dataValue = $(this).attr('data-index');
var b = '#livraison_'+dataValue;
var ismc = 'input[name^="shipping_method['+dataValue+']"]:checked';
var livraison = 'Livraison:1';
if( ($(this).attr("type") == 'hidden') ) {
if( $(this).val() == 'Livraison:1' ) // Choosen "retrait sur place" (Hidding "Take away")
{
$(b).show();
} else
{
$(b).hide();
}
} else {
if($(this).is(':checked'))
{
if( $(this).val() == 'Livraison:1' ) // Choosen "retrait sur place" (Hidding "Take away")
{
$(b).show();
} else
{
$(b).hide();
}
}
}
});
}, 100);
}
});
</script>

Drag and Drop to a specific area

I have tried to create a game where the user will have to place each card in a specific order. I can drag and drop the names into the dropable area but how will i be able to assign a specific card to a specific slot.
Here is my js code:
var correctCards = 0;
$( init );
function init() {
// Hide the success message
$('#successMessage').hide();
$('#successMessage').css( {
left: '580px',
top: '250px',
width: 0,
height: 0
} );
// Reset the game
correctCards = 0;
$('#cardPile').html( '' );
$('#cardSlots').html( '' );
// Create the pile of shuffled cards
var cards = ["Aiba", "Ninomiya", "Ohno", "Sakurai", "Matsumoto"];
cards.sort( function() { return Math.random() - .5 } );
for ( var i=0; i<cards.length; i++ ) {
$('<div>' + cards[i] + '</div>').data('img',i ).appendTo( '#cardPile' ).draggable( {
containment: '#content',
stack: '#cardPile div',
cursor: 'move',
revert: true
} );
}
// Create the card slots
var slots = [ ' ', ' ', ' ', ' ', ' '];
for ( var i=1; i<=slots.length; i++ ) {
$('<div>' + slots[i-1] + '</div>').data( 'number', i ).appendTo( '#cardSlots' ).droppable( {
accept: '#cardPile div',
hoverClass: 'hovered',
drop: handleCardDrop
} );
}
}
function handleCardDrop( event, ui ) {
var slotNumber = $(this).data( 'name' );
var cardNumber = ui.draggable.data( 'name' );
// If the card was dropped to the correct slot,
// change the card colour, position it directly
// on top of the slot, and prevent it being dragged
// again
if ( slotNumber == cardNumber ) {
ui.draggable.addClass( 'correct' );
ui.draggable.draggable( 'disable' );
$(this).droppable( 'disable' );
ui.draggable.position( { of: $(this), my: 'left top', at: 'left top' } );
ui.draggable.draggable( 'option', 'revert', false );
correctCards++;
}
// If all the cards have been placed correctly then display a message
// and reset the cards for another go
if ( correctCards == 10 ) {
$('#successMessage').show();
$('#successMessage').animate( {
left: '380px',
top: '200px',
width: '400px',
height: '100px',
opacity: 1
} );
}
}
If you give a unique id to each div where a card is (so for example cardSlot1, cardSlot2...), you could use document.getElementById('cardSlot1').value to get the name of the card back.
It would look similar to this:
for ( var i=0; i<cards.length; i++ ) {
$('<div id="cardSlot'+i+'">' + cards[i] + '</div>').data('img',i ).appendTo( '#cardPile' ).draggable( {
containment: '#content',
stack: '#cardPile div',
cursor: 'move',
revert: true
} );
}

jQuery - the autocomplete properties not getting applied to dynamically created combobox?

Below is the code in which the autocomplete works fine with the first combobox. if i just copy paste the combobox it is working but when the second combobox is created dynamically on button click the autocomplete is not working ?
current code :
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Combobox</title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<style>
.custom-combobox {
position: relative;
display: inline-block;
}
.custom-combobox-toggle {
position: absolute;
top: 0;
bottom: 0;
margin-left: -1px;
padding: 0;
height:17px;
background:transparent;
border-radius:0px;
}
.custom-combobox-input {
margin: 0;
padding: 0px 0px;
width:150px;height:17px;
background:transparent;
border-radius:0px;
}
.ui-menu .ui-menu-item {
position: relative;
margin: 0;
padding: 0px 0em 0px 0em;
cursor: pointer;
min-height: 0;
background:transparent;
}
</style>
<script>
function sendvalues()
{
alert();
}
function combo()
{
alert();
$( ".combobox" ).combobox();
}
(function( $ ) {
$.widget( "custom.combobox", {
_create: function() {
this.wrapper = $( "<span>" )
.addClass( "custom-combobox" )
.insertAfter( this.element );
this.element.hide();
this._createAutocomplete();
this._createShowAllButton();
},
_createAutocomplete: function() {
var selected = this.element.children( ":selected" ),
value = selected.val() ? selected.text() : "";
this.input = $( "<input>" )
.appendTo( this.wrapper )
.val( value )
.attr( "title", "" )
.addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy( this, "_source" )
})
.tooltip({
tooltipClass: "ui-state-highlight"
});
this._on( this.input, {
autocompleteselect: function( event, ui ) {
ui.item.option.selected = true;
this._trigger( "select", event, {
item: ui.item.option
});
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function() {
var input = this.input,
wasOpen = false;
$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
.tooltip()
.appendTo( this.wrapper )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "custom-combobox-toggle ui-corner-right" )
.mousedown(function() {
wasOpen = input.autocomplete( "widget" ).is( ":visible" );
})
.click(function() {
input.focus();
// Close if already visible
if ( wasOpen ) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
});
},
_source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( this.element.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text,
value: text,
option: this
};
}) );
},
_removeIfInvalid: function( event, ui ) {
// Selected an item, nothing to do
if ( ui.item ) {
sendvalues();
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children( "option" ).each(function() {
if ( $( this ).text().toLowerCase() === valueLowerCase ) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if ( valid ) {
return;
}
// Remove invalid value
this.input
.val( "" )
.attr( "title", value + " didn't match any item" )
.tooltip( "open" );
this.element.val( "" );
this._delay(function() {
this.input.tooltip( "close" ).attr( "title", "" );
}, 2500 );
this.input.autocomplete( "instance" ).term = "";
},
_destroy: function() {
this.wrapper.remove();
this.element.show();
}
});
})( jQuery );
$(function() {
$( ".combobox" ).combobox();
$( "#toggle" ).click(function() {
$( ".combobox" ).toggle();
});
});
</script>
</head>
<body>
<script>
function loada()
{
document.getElementById("two").innerHTML=document.getElementById("one").innerHTML;
}
</script>
<div id="one">
<select class="combobox" id="one" onchange="sendvalues()" onload="combo()">
<option value="">Select one...</option>
<option value="abc">abc</option>
<option value="kkk">kkk</option>
<option value="sd">asf</option>
<option value="abdfac">abasdfsac</option>
<option value="kgfjkgkk">kkyk</option>
<option value="sghkd">asgyjf</option>
<option value="abyuic">abftfjvhjc</option>
<option value="kkkgyjhk">kkgjk</option>
<option value="sml,hud">asnjmf</option>
</select>
</div>
<br><br><br><br>
<button onclick="loada()" >click</button>
<div id="two" onload="">
</div>
</body>
</html>
There are certain points which I observed in your code which are little bit not correct to do with html. Chances are there you would have written in hurry so please ignore the points
Div Id is 'one' and in side selector also having id as one make sure ids are unique.
your loada() function is just doing a copy paste job auto complete binding is missing .
So here I have changed your loada() function replace then it will work.
var counter = 0;
function loada() {
// document.getElementById("two").innerHTML = document.getElementById("one").innerHTML;
$("#one").clone().find('select').addClass('newControl' + counter).appendTo("#two");
$('.newControl' + counter).combobox();
counter++;
}

callback.call is not a function

I am getting this error and having a difficult time correcting it. I get the following error message: callback.call is not a function
I have posted code snippets below for comment, it seems that the error is being triggered when validateCheckBox(o) is invoked. I understand that the error is triggered from a function being out of context but not exactly sure how to fix.
function checkLength( o, n, min, max ) {
console.log( arguments.length );
if ( arguments.length < 4 ) {
// issue here with callback.call is not a function
if ( validateCheckBox(o) ){
validateCheckBox(o);
}
}else {
if ( o.val().length > max || o.val().length < min ) {
o.addClass( "ui-state-error" );
updateTips( "Length of " + n + " must be between " +
min + " and " + max + "." );
return false;
} else {
return true;
}
}
}
function validateCheckBox( o ) {
var css = $(".border").css({
"border-color": "",
"border-weight": "",
"border-style" : "",
"background-color": "",
"background-image": "",
"background-repeat":"",
"background-position":""
});
//console.log(css);
var invalidChkBox = {
"border-color":"#cd0a0a",
"border-weight":"1px",
"border-style":"solid",
"background-color": "#feflec",
"background-image": "url('lib/jquery-ui/css/images/ui-bg_glass_95_fef1ec_1x400.png')",
"background-repeat": "repeat-x",
"background-position": "50% 50%"
}
// throwing error callback is not defined
var isChecked = $( "#verification" ).is(":checked");
if ( isChecked == false || isChecked == undefined ) {
$( ".border" ).css( invalidChkBox );
o.addClass( "ui-state-error" );
$( ".validateTips" ).text( "You must agree that all information is accurate and true, by checking the box." );
}else{
// reported bug callback.call is not a function #error below
$( ".validateTips" ).css( 'display', null ).text( "" );
$( ".border" ).css( css );
}
}
valid = valid && checkLength ( verification, "Verification", 1 );
Thanks in advance.
thanks for the help. It turned out to be something simple. I was trying to assign css rules to the class with the rules already defined on it...
var css = $(".border").css({
"border-color": "",
"border-weight": "",
"border-style" : "",
"background-color": "",
"background-image": "",
"background-repeat":"",
"background-position":""
});
$( ".border" ).css( css ); --> line throwing error....
Based on your comment, the problem could be the 1st argument of checkLength being a string instead of a JQuery object. Looks like the calls should be more like
checkLength($("#first_name"), "First name", 3, 30 );
Note the $("#first_name") which passes through a JQuery object representing the element with id #first_name rather than just the string "#first_name".

How to disable a search/filter on a specific column on a datatable?

My datatable has 5 columns and I need to disable filtering for the 3rd, 4th and last column.
please help!!!
this is the javascript:
<script type="text/javascript" language="javascript" class="init">
$(document).ready(function() {
// Setup - add a text input to each footer cell
$('#example tfoot th').each( function () {
var title = $('#example thead th').eq( $(this).index() ).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" />' );
} );
// DataTable
var table = $('#example').DataTable();
// Apply the search
table.columns().eq( 0 ).each( function ( colIdx ) {
$( 'input', table.column( colIdx ).footer() ).on( 'keyup change', function () {
table
.column( colIdx )
.search( this.value )
.draw();
} );
} );
} );
</script>
You can use .not to exclude the columns you want to add input text too. Furthermore, you can also add code to avoid adding event handlers to any input boxes in the excluded columns (although if no input boxes exist in those cells it doesn't matter):
$(document).ready(function() {
// Setup - add a text input to each footer cell
$('#example tfoot th').not(":eq(2),:eq(3),:eq(4)") //Exclude columns 3, 4, and 5
.each( function () {
var title = $('#example thead th').eq( $(this).index() ).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" />' );
} );
// DataTable
var table = $('#example').DataTable();
// Apply the search
table.columns().eq( 0 ).each( function ( colIdx ) {
if (colIdx == 2 || colIdx == 3 || colIdx == 4) return; //Do not add event handlers for these columns
$( 'input', table.column( colIdx ).footer() ).on( 'keyup change', function () {
table
.column( colIdx )
.search( this.value )
.draw();
} );
} );
} );
See Fiddle: http://jsfiddle.net/30phqqqg/1/
The same story for columns with filtering. 2nd column filtering disable:
$(document).ready(function() {
$('#example').DataTable( {
initComplete: function () {
this.api().columns().every( function () {
var column = this;
var some = column.index();
if (column.index() == 1) return;
var select = $('<select><option value=""></option></select>')
.appendTo( $(column.footer()).empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
} );
}})
};

Categories