Repeatable block functionlaity - javascript

I am trying to develop functionality for repeatable blocks within my web form, the issue being the buttons do nothing when I click them I have tested them in the console and they do work, they just dont do anything and am unsure why, been working on this for 2 days and am at a standstill, anyone who can point me in the right direction would be much appreciated.
It should generate the fields contained within that field set and generate a identical empty field set, and not sure whats wrong with the plus or minus functions.
$('input, fieldset').each(function(){
if ($(this).attr('data-maxOccurs') != 1){
$(plusMinusButtons).insertAfter(this);
}
});
$('.glyphicon-plus-sign').hover(function(){
$(this).addClass('green');
},
function(){
$(this).removeClass('green');
}
);
$('.glyphicon-minus-sign').hover(function(){
$(this).addClass('red');
},
function(){
$(this).removeClass('red');
}
);
$('body').on("click", '.glyphicon-plus-sign', function (){
prevInput = $(this).prev('input');
count = $(prevInput).attr('data-count');
countIncremented = count++;
br = '<br/><br/>';
inputElement = '<input type="'+$(prevInput).attr("type")+'" name="'+$(prevInput).attr("name")+countIncremented+'" data-count="'+countIncremented+'"/>';
$(br + inputElement + plusMinusButtons).insertAfter('.'+$(prevInput).attr("name")+':last');
}
);
$('body').on("click", '.glyphicon-minus-sign', function (){
prevInput = $(this).prev('input');
$(this).remove(prevInput).remove(this);
}
);
$("button").click(function(){
console.log("here");
x=$('#form').serializeArray();
$.each(x, function(i, field){
console.log(field.name + ":" + field.value + " ");
});
});
});
And here is the JSfiddle: Fiddle

The code Used in order to duplicate the field set.
$('body').on("click ", '.glyphicon-plus-sign', function() {
console.log("here ");
prevInput = $(this);
count = $(prevInput).attr('data-count=')||0;
countIncremented = count++;
br = '<br/><br/>';
$($(this).parent()).clone().insertAfter($(this).parent());

Related

Javascript fires twice Wordpress admin metabox

I added a inline Javascript code to my metabox callback function.
add_action( 'add_meta_boxes', function() {
add_meta_box( 'catalog-item', 'Gegevens', 'catalog_details_callback', 'catalog', 'advanced' );
});
function catalog_details_callback( $post ) {
<input type="text" class="price" name="price" id="price"/>
<script type="text/javascript">
document.getElementById('price').onfocusout = function() {
var regex = /^(\d+[,]+\d{2})$/;
if (regex.test(this.value) == false ) {
this.value = this.value.replace(/([^(\d|,)]|,{2})/g, "");
}
var before = this.value.replace(",", ".");
var roundoff = parseFloat(before).toFixed(2);
var after = roundoff.replace(".", ",");
alert(after);
}
</script>
}
If the function is triggered the function fires the alert twice.
Does anybody know how I fix this?
There could be multiple reason for this:
Please check if you have multiple event listeners. If so, try to check your condition. understand about event listeners here: https://developer.mozilla.org/en-US/docs/Web/API/Element/focusout_event
onfocusout bubbles, means if you have any event written on parent as well as child then both gets called. try to add
document.getElementById('price').onfocusout = function(event) {
event.preventDefault();
event.stopPropagation();
var regex = /^(\d+[,]+\d{2})$/;
if (regex.test(this.value) == false ) {
this.value = this.value.replace(/([^(\d|,)]|,{2})/g, "");
}
var before = this.value.replace(",", ".");
var roundoff = parseFloat(before).toFixed(2);
var after = roundoff.replace(".", ",");
alert(after);
}
If still issue persists then try to add the debugger in the function can check the call trace in google developers console.
I had the same issue with Wordpress.
This works for me
const price_field = document.getElementById('price');
price_field.addEventListener('focusout', (event) => {
var regex = /^(\d+[,]+\d{2})$/;
if (regex.test(price_field.value) == false ) {
this.value = price_field.value.replace(/([^(\d|,)]|,{2})/g, "");
}
var before = price_field.value.replace(",", ".");
var roundoff = parseFloat(before).toFixed(2);
var after = roundoff.replace(".", ",");
price_field.value = after;
alert(after);
});

localStorage clears on refresh, parse & stringify not working

Working on a practice app with localStorage, but the stored data is getting cleared on page refresh. Based on answers to similar questions, I've used JSON.stringify(); on setItem, and JSON.parse(); on getItem, but still no luck. Am I using those methods in the wrong way? For reference, #petType and #petName are input IDs, and #name and #type are ul IDs. Thanks!
var animalArray = [];
var addPet = function(type,name) {
var type = $("#petType").val();
var name = $("#petName").val();
localStorage.setItem("petType", JSON.stringify(type));
localStorage.setItem("petName", JSON.stringify(name));
animalArray.push(type,name);
};
var logPets = function() {
animalArray.forEach( function(element,index) {
//empty array
animalArray.length = 0;
//empty input
$("input").val("");
var storedName = JSON.parse(localStorage.getItem("petName"));
var storedType = JSON.parse(localStorage.getItem("petType"));
//append localStorage values onto ul's
$("#name").append("<li>" + storedName + "</li>");
$("#type").append("<li>" + storedType + "</li>");
});
};
//click listPets button, call logPets function
$("#listPets").on("click", function() {
logPets();
$("#check").html("");
});
//click enter button, call addPet function
$("#enter").on("click", function() {
addPet(petType,petName);
$("#check").append("<i class='fa fa-check' aria-hidden='true'></i>");
});
It appears to clear because you are not loading data from it when the page loads. There are multiple bugs in the code:
It appears that you're only saving the last added pet to localStorage, which would create inconsistent behaviour
Setting animalArray.length to 0 is incorrect
animalArray.push(type, name); is probably not what you want, since it adds 2 items to the array, do something like animalArray.push({type: type, name: name});
logPets can just use the in memory array, since it's identical to the one saved
Fixed code:
var storedArray = localStorage.getItem("animalArray");
var animalArray = [];
if(storedArray) {
animalArray = JSON.parse(storedArray);
}
var addPet = function(type,name) {
var type = $("#petType").val();
var name = $("#petName").val();
animalArray.push({type: type, name: name});
localStorage.setItem("animalArray", JSON.stringify(animalArray));
};
var logPets = function() {
animalArray.forEach( function(element,index) {
//empty input
$("input").val("");
//append localStorage values onto ul's
$("#name").append("<li>" + element.name + "</li>");
$("#type").append("<li>" + element.type + "</li>");
});
};
//click listPets button, call logPets function
$("#listPets").on("click", function() {
logPets();
$("#check").html("");
});
//click enter button, call addPet function
$("#enter").on("click", function() {
addPet(petType,petName);
$("#check").append("<i class='fa fa-check' aria-hidden='true'></i>");
});
A quick fiddle to demo it: https://jsfiddle.net/rhnnvvL0/1/

Store a selector in a variable Javascript and then use a method on it

I have check some others post, and document myself but I dont know what is the problem here.
I have 2 image (would like to have like 20 at the end) where you can click on an icon and show and hide and image in the webpage. If you click on image A it should show image A, if you click on image B image A should hide and image B should be sown.
var firsttime = 1;
var $lastletter;
$(function() {
$('#A').click(function() {
if (firsttime = 0){
$lastletter.toggle();
$('#AL').toggle();
$lastletter = $( '#AL' );
}
else
{
firsttime = 0;
$('#AL').toggle();
$lastletter = $( '#AL' );
}
});
});
$(function() {
$('#B').click(function() {
if (firsttime = 0){
$lastletter.toggle();
$('#BL').toggle();
$lastletter = $( '#BL' );
}
else
{
firsttime = 0;
$('#BL').toggle();
$lastletter = $( '#BL' );
}
});
});
This is the solution im using:
$(function() {
$('.imgLetter').click(function() {
if (lastletter != this.id) {
$('#' + lastletter + 'L').toggle();
lastletter=this.id;
}
$('#' + this.id + 'L').toggle();
});
});
Assuming you're conventionally assigning the "last letter" by appending an "L" to the ID: this could get a lot simpler. Decorate all of your #<x> elements with a class name that makes it easy to select all of them at once. I'm going to choose "letter".
I don't think you even need to track the "first time". It sounds like you just want one element to toggle another. That would look like:
$(function() {
$('.letter').click(function() {
$('#' + this.id + 'L').toggle();
});
});

Jquery adding forms, works on JSFiddle but in production does not

Hi guys this might be a really stupid error but im using jquery to add a formset to a page it also does other things such as updating the number of forms but that does not seem to be a issue.
http://jsfiddle.net/b5Y8f/
$(document).ready(function () {
function updateElementIndex(el, prefix, ndx) {
var id_regex = new RegExp('(' + prefix + '_set-\\d+-)');
var replacement = prefix + '_set-' + ndx + '-';
if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement));
if (el.id) el.id = el.id.replace(id_regex, replacement);
if (el.name) el.name = el.name.replace(id_regex, replacement);
}
function changeDeleteForms(el, prefix, formid) {
var idstring = 'id_' + prefix + '_set-' + formid + '-DELETE';
//$('<input>').attr({type: 'hidden', id: 'id_' + idstring, name: idstring}).appendTo('.command-delete');
$('#' + idstring).prop('checked', true);
}
function deleteForm(btn, prefix) {
var formCount = parseInt($('#id_' + prefix + '_set-TOTAL_FORMS').val());
if (formCount > 1) {
// Delete the item/form
$(btn).parents('.command').hide();
$(btn).parents('.command').attr('class', 'command-delete');
var dc = $(".command-delete");
$(dc).children().children().children().each(function () {
var formid = this.id.match(/\d+/g);
changeDeleteForms(this, prefix, formid);
//$(this).val("");
});
var forms = $('.command'); // Get all the forms
var formsdelete = $('.command-delete'); // Get all the forms
var fl = parseInt(forms.length);
var fdl = parseInt(formsdelete.length);
var finalcount = fl + fdl
// Update the total number of forms (1 less than before)
//$('#id_' + prefix + '_set-TOTAL_FORMS').val(forms.length);
var i = 0;
} // End if
else {
alert("Please enter atleast 1 command for this item.");
}
return false;
}
function addForm(btn, prefix) {
var formCount = parseInt($('#id_' + prefix + '_set-TOTAL_FORMS').val());
var maxCount = parseInt($('#id_' + prefix + '_set-MAX_NUM_FORMS').val());
var forms = parseInt($('.command-delete').length); // Get all the forms
var newcount = formCount + forms;
// You can only submit a maximum of 10 todo items
if (newcount < maxCount) {
// Clone a form (without event handlers) from the first form
var row = $(".command:first").clone(false).get(0);
// Insert it after the last form
$(row).removeAttr('id').hide().insertAfter(".command:last").slideDown(300);
// Remove the bits we don't want in the new row/form
// e.g. error messages
$(".errorlist", row).remove();
$(row).children().removeClass("error");
// Relabel or rename all the relevant bits
$(row).children().children().children().children().each(function () {
updateElementIndex(this, prefix, newcount);
$(this).val("");
});
// Add an event handler for the delete item/form link
$(row).find(".delete").click(function () {
return deleteForm(this, prefix);
});
// Update the total form count
$("#id_" + prefix + "_set-TOTAL_FORMS").val(newcount + 1);
} // End if
else {
alert("Sorry, you can only enter a maximum of 1000 items.");
}
return false;
}
// Register the click event handlers
$("#add").click(function () {
return addForm(this, "itemcommands");
});
$(".delete").click(function () {
return deleteForm(this, "itemcommands");
});
$('.command input:checkbox').hide();
});
If you go to the link above you can see the code works perfectly fine it update the form count and add the new form with the new number in the id and everything however in production when you click the add command button for the first 3 times it does not show however the code has been enter into the page and the form is technically there but not shown.
on the fourth time you press the button it works and the row has been added after the last ('.command') in the element.
What could be causing it to work on JSFiddle but not on production?
-------------------UPDATE--------------------------
It seems if i remove the overflow hidden from the 3 that dont show when you press the button the first 3 times it will show them in the correct place.
Why would overflow no be removed from the first 3 form rows but the rest after fine?
----------------------UPDATE--------------------------
Think i have found the issue and its nothing to do with the JQUERY at all it seems to be bootstraps responsive layout hiding the forms i think if i add them specifically to their own rows i can fix this.
Thanks for the help though guys.
I don't see a src="*jQuery source*" in your file. Since JSFiddle already adds the source to the file, you may have forgotten to put it in.

how to add a value onto the url using javascript var

Is there a way to add the select-result on the url when the pop up window appears? The select-result gives the value of the boxes selected and i want to pass the values selected gto a form but i am not ussing a form. can i pass the values ussing the url?
i want to add the selected values like form.php?id=2882,222,22412,23
$(function() {
$(".selectable").selectable({
filter: "td.cs",
stop: function() {
var result = $("#select-result").empty();
var result2 = $("#result2");
$('.ui-selecting:gt(31)').removeClass("ui-selecting");
confirmation($(".ui-selected").length + " box selected. " + ($(".ui-selected").length));
function confirmation() {
var answer = confirm($(".ui-selected").length + " box selected. " + ($(".ui-selected").length));
if (answer) {
window.open("form.php", "mywindow", "menubar=no,resizable=no,width=650,height=700");
}
else {}
}
$('#divmsg').html($(".ui-selected").length + " box selected")
$('#divmsg2').html($(".ui-selected").length)
if ($(".ui-selected").length > 90) {
alert("Selection of only 90 boxes allowed");
$('#divmsg').html($('#divmsg').html() + ",<br><b>Message: Selection of only 90 pixels allowed!!</b>");
$(".ui-selected").each(function(i, e) {
if (i > 3) {
$(this).removeClass("ui-selected");
}
});
return;
}
$(".ui-selected", this).each(function() {
var cabbage = this.id + ', ';
result.append(cabbage);
});
var newInputResult = $('#select-result').text();
newInputResult = newInputResult.substring(0, newInputResult.length - 1);
result2.val(newInputResult);
}
});
});​
this is the fiddle http://jsfiddle.net/dw6Hf/57/
i have tried
window.open ("form.php?id="+ select-result, "mywindow",....
but it won't work!! any idea???
Thanks in advance ​
If you're asking what I think you're asking, and selectable does what I think it does, then try this:
window.open("form.php?id=" + $('#select-result').text(), "mywindow", "menubar=no,resizable=no,width=650,height=700");
If that doesn't work, then I've obviously misunderstood your answer. I'd suggest clearing it up, and maybe getting a working example up and running for us to see.
Firstly the fiddle you have posted is broken. But no worries i have fixed it along with the solution at http://jsfiddle.net/paragnair/dw6Hf/61/
I have added the following line:
var selectedIds = $.map($('.ui-selected'),function(a){ return $(a).attr('id');}).join(',');
The above line gets the list of ids for all the elements which have the class ui-selected. Then you can append the variable selectedIds to window.open like so:
window.open("form.php?id=" + selectedIds, "mywindow", "menubar=no,resizable=no,width=650,height=700");

Categories