onclick clone shipping address fields values to billing address fields values - javascript

Hi i have this javascript code
copyAddress : function(swapMode, container){
var thisInstance = this;
var addressMapping = this.addressFieldsMappingInModule;
if(swapMode == "false"){
for(var key in addressMapping) {
var fromElement = container.find('[name="'+key+'"]');
var toElement = container.find('[name="'+addressMapping[key]+'"]');
toElement.val(fromElement.val());
}
} else if(swapMode){
var swappedArray = thisInstance.swapObject(addressMapping);
for(var key in swappedArray) {
var fromElement = container.find('[name="'+key+'"]');
var toElement = container.find('[name="'+swappedArray[key]+'"]');
toElement.val(fromElement.val());
}
this code working fine if elements are input text fields
but not for select dropdown elements
I my form I have only input text and select fields and i want to modyfy this code to work with select fields too
I made a change to code like this
if(!(fromElement).is("select")) {
toElement.val(fromElement.val());
}else{
var $options = $(fromElement+" > option").clone();
toElement.append($options);
}
but without success.
Maybe anyone can help me please?
Thanks!

This will do your work.
I have added a check that if the element to copy is Select or not. In case of select element all the options of From element will be copied and appended to To element.
Try it and let me in case of any issue.
copyAddress : function(swapMode, container){
var thisInstance = this;
var addressMapping = this.addressFieldsMappingInModule;
if(swapMode == "false"){
for(var key in addressMapping) {
var fromElement = container.find('[name="'+key+'"]');
var toElement = container.find('[name="'+addressMapping[key]+'"]');
if(fromElement[0].tagName == "Select")
{
toElement.find('option').remove();
toElement.append(fromElement.find('option'));
}
toElement.val(fromElement.val());
}
} else if(swapMode){
var swappedArray = thisInstance.swapObject(addressMapping);
for(var key in swappedArray) {
var fromElement = container.find('[name="'+key+'"]');
var toElement = container.find('[name="'+swappedArray[key]+'"]');
if(fromElement[0].tagName == "Select")
{
toElement.find('option').remove();
toElement.append(fromElement.find('option'));
}
toElement.val(fromElement.val());
}

The solution was toElement.val(fromElement.val()).trigger("liszt:updated"); this work for all elements in form that use chosen.js

Related

How to make other JQuery run when a separate function runs?

I have the JS code below which filters based on checkboxes being checked or not (I don't think you need to see all the HTML because my question is rather simple/general, I think). All this code works fine, but I added a new function at the bottom (I noted it in the code) that simply has an uncheck all button for one of the sets of checkboxes (because there are like 30 checkboxes and I don't want the user to have to uncheck them all manually).
Anyway, the new script works properly too, except that the overall unrelated script that compares all checkboxes needs to run each time the new Uncheck All/Check All button is clicked.
Is there a simple way to make sure all the other JS runs when this new script is run?
I could be wrong, but I think I just need to somehow trigger this function inside the NEW FUNCTION:
$checkboxes.on('change', function() {
but am not sure how to do that.
ALL JS:
<script>
$(window).load(function(){
Array.prototype.indexOfAny = function(array) {
return this.findIndex(function(v) {
return array.indexOf(v) != -1;
});
}
Array.prototype.containsAny = function(array) {
return this.indexOfAny(array) != -1;
}
function getAllChecked() {
// build a multidimensional array of checked values, organized by type
var values = [];
var $checked = $checkboxes.filter(':checked');
$checked.each(function() {
var $check = $(this);
var type = $check.data('type');
var value = $check.data('value');
if (typeof values[type] !== "object") {
values[type] = [];
}
values[type].push(value);
});
return values;
}
function evaluateReseller($reseller, checkedValues) {
// Evaluate a selected reseller against checked values.
// Determine whether at least one of the reseller's attributes for
// each type is found in the checked values.
var data = $reseller.data();
var found = false;
$.each(data, function(prop, values) {
values = values.split(',').map(function(value) {
return value.trim();
});
found = prop in checkedValues && values.containsAny(checkedValues[prop]);
if (!found) {
return false;
}
});
return found;
}
var $checkboxes = $('[type="checkbox"]');
var $resellers = $('.Row');
$checkboxes.on('change', function() {
// get all checked values.
var checkedValues = getAllChecked();
// compare each resellers attributes to the checked values.
$resellers.each(function(k, reseller) {
var $reseller = $(reseller);
var found = evaluateReseller($reseller, checkedValues);
// if at least one value of each type is checked, show this reseller.
// otherwise, hide it.
if (found) {
$reseller.show();
} else {
$reseller.hide();
}
});
});
//NEW FUNCTION for "UNCHECK ALL" Button
$(function() {
$(document).on('click', '#checkAll', function() {
if ($(this).val() == 'Check All') {
$('input.country').prop('checked', true);
$(this).val('Uncheck All');
} else {
$('input.country').prop('checked', false);
$(this).val('Check All');
}
});
});
});
New button HTML for the new UNCHECK portion:
<input id="checkAll" type="button" value="Uncheck All">
I kept researching and discovered the trigger() function to handle this.
http://api.jquery.com/trigger/

Get input value from each row in JavaScript

function shortDescription(a){
var descriptionInput;
var tbl = $(document.getElementById('21.125-mrss-cont-none-content'));
tbl.find('tr').each(function () {
$(this).find("input[name$='6#if']").keypress(function (e) {
if (e.which == 13) {
descriptionInput = $(this).val();
$(this).val(descriptionInput);
$(document.getElementById('__AGIM0:U:1:4:2:1:1::0:14')).val(descriptionInput);
}
console.log(descriptionInput);
});
});
});
}
This code works perfectly but how do I write this in pure JavaScript? I'm mainly interested in this: How do I perform these tasks without jQuery?
for each row, find the input name that ends in 6#if (the column I want)
on enter, get this input value and add to the console it so I know it's there
input id = "grid#21.125#1,6#if" type="text" value"" name="grid#21.125#1,6#if
oninput = shortDescription(this);
It would be great if you could share a piece of HTML on wich we could try some things, but for the moment, here's what your code looks like written in pure JS :
var descriptionInput;
var tbl = document.getElementById('21.125-mrss-cont-none-content')
Array.from(tbl.getElementsByTagName('tr')).forEach(function(tr) {
Array.from(tr.querySelectorAll("input[name$='6#if']")).forEach(function(input) {
input.onkeypress = function(e) {
if (e.keyCode == 13) {
descriptionInput = input.value;
input.value = descriptionInput; // why ??
document.getElementById('__AGIM0:U:1:4:2:1:1::0:14').value = descriptionInput;
}
console.log(descriptionInput);
}
});
});
If you're not OK with the querySelectorAll, you can use getElementsByTagName, it returns a NodeList that you can turn into an array with the Array.from method and the use filter on the name to find the input with a name containing "6#if".
Best practices ...
Since an ID is unique and the methods getElementsByTageName or getElementsByTagName returns a Live HTMLCollection, it's better if you use these elements as unique variables, so you won't ask your browser to fetch them many times.
Since I don't know what your elements means, I will name the variables with trivial names, here's a better version of the code :
var descriptionInput;
var tbl = document.getElementById('21.125-mrss-cont-none-content');
var tr1 = tbl.getElementsByTagName('tr');
var el1 = document.getElementById('__AGIM0:U:1:4:2:1:1::0:14');
var inputsInTr = Array.from(tr1).map(function(tr) {
return Array.from(tr.getElementsByTagName('input'));
}).reduce(function(pv, cv) {
return pv.concat(cv);
});
var myInputs = inputsInTr.filter(function(input) {
return input.name.indexOf('6#if') != 0;
});
myInputs.forEach(function(input) {
input.onkeypress = function(e) {
if (e.keyCode == 13) {
descriptionInput = input.value;
el1.value = descriptionInput;
}
console.log(descriptionInput);
}
});
I didn't try it, hope it's OK.
Hope it helps,
Best regards,

Control duplicate entries with angular.js

I’m using angular.js to get some form data from some input fields. I need to build a feature that prevents a user from entering duplicate fields. So if a user entered duplicate fields I need alert the user with a alert box and than remove the duplicate. I know how to do this with jQuery, look at the code below. What is the most efficient way to achieve this with angular.js? Any help is greatly appreciated, I have template fiddle here to make it easier.
/** Handle Duplicate Barcodes **/
$(".alldifferent").on('keyup paste',function(){
var $this = $(this);
keyupDelay(function() {
var val = $this.val();
$this.attr('value', val);
if (val != '') {
var $dupes = $('input[value="' + val + '"]:gt(0)').val('');
if ($dupes.length > 0) alert('Error: Duplicates barcodes are not allowed!');
}
}, 300);
});
var keyupDelay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
Try ng-blur as a blur event fires when an element has lost focus.
If you can know the index at which the duplicate entry is being entered you can filter that item in the array and clear it.
$scope.check = function(val, index){
if(val !== '') {
for(var i = 0; i < $scope.num.length; i++ ){
var itm = $scope.num[i].text;
if(itm == val && i != index) {
$scope.num[index].text = '';
alert('Error: Duplicates barcodes are not allowed!');
break;
}
}
}
}
Working Plunker

Changing value separation from "," to "-" (JS/Jquery)

I received some Jquery code for an HTML checkbox. Essentially, when checked, the value of the checkbox is placed in an input box. When I uncheck the box, the value is cleared from the input. However, when you check multiple checkboxes, a "," separates the values. Is there a way to seperate the values by "-" instead of ","? I tried playing around with the code and it just breaks the code. I am fairly new to JS/Jquery so if it is a simple answer, I apologize. I can provide more information if needed. A working JSFiddle with "," is here: https://jsfiddle.net/m240Laka/25/
My code is located here:
var $choiceDisplay = $("#choiceDisplay"), //jquery selector for the display box
$none = $("#none"),
$choice = $(".choice");
$choice.on("change", function () {
var $this = $(this), //jquery selector for the changed input
isThisChecked = $this.prop("checked"), //boolean true if the box is checked
choiceSelectionsArray = $choiceDisplay.val().split(",").filter(function(e){return e !== ""}), //array of values that are checked
isThisValueInDisplayedSelection = $.inArray($this.val(), choiceSelectionsArray) !== -1; //boolean true when $this value displayed
if (isThisChecked) {
if (isThisValueInDisplayedSelection) {
return false; //odd, the value is already displayed. No work to do.
} else {
choiceSelectionsArray.push($this.val());
$choiceDisplay.val(choiceSelectionsArray.join());
}
} else { //box has been unchecked
if (isThisValueInDisplayedSelection) {
choiceSelectionsArray = choiceSelectionsArray.filter(function(e){return e !== $this.val()})
$choiceDisplay.val(choiceSelectionsArray.join());
}
}
});
$none.on("change", function () {
var $this = $(this),
isThisChecked = $this.prop("checked");
if(isThisChecked){
$choice.prop({
disabled: true,
checked : false
});
$choiceDisplay.val("");
}else{
$choice.prop({disabled: false});
return false;
}
});
In the functions join() and split(), you need to pass in the delimiter you want, '-'. I suggest creating a local variable that you use, so it is easier to change this if needed.
var $choiceDisplay = $("#choiceDisplay"), //jquery selector for the display box
$none = $("#none"),
$choice = $(".choice"),
delimiter = '-';
$choice.on("change", function () {
var $this = $(this), //jquery selector for the changed input
isThisChecked = $this.prop("checked"), //boolean true if the box is checked
choiceSelectionsArray = $choiceDisplay.val().split(delimiter).filter(function(e){return e !== ""}), //array of values that are checked
isThisValueInDisplayedSelection = $.inArray($this.val(), choiceSelectionsArray) !== -1; //boolean true when $this value displayed
if (isThisChecked) {
if (isThisValueInDisplayedSelection) {
return false; //odd, the value is already displayed. No work to do.
} else {
choiceSelectionsArray.push($this.val());
$choiceDisplay.val(choiceSelectionsArray.join(delimiter));
}
} else { //box has been unchecked
if (isThisValueInDisplayedSelection) {
choiceSelectionsArray = choiceSelectionsArray.filter(function(e){return e !== $this.val()})
$choiceDisplay.val(choiceSelectionsArray.join(delimiter));
}
}
});
Here is it in a jsfiddle.
In $.join() add the separator string parameter:
$choiceDisplay.val(choiceSelectionsArray.join("-"));
UPDATE:
add the same in $.split()
choiceSelectionsArray = $choiceDisplay.val().split("-")....

How to unselect the parent checkbox when their child checkbox is unchecked using jQuery?

I am using asp.net tree view control. And using jQuery to select all the corresponding child check box when its parent is checked. The working jQuery and the rendered HTML is in this JS Fiddle
jQuery to select the checkbox :
$('.tree').on('change', ':checkbox', function () {
var checked = this.checked;
var $elem = $(this).closest('table');
var depth = $elem.find('div').length;
var $childs = $elem.nextAll('table');
$childs.each(function () {
var $child = $(this);
var d = $child.find('div').length;
if (d <= depth) {
return false;
}
$child.find(':checkbox').prop('checked', checked);
});
});
But I do not know how to unselect the parent node when one of its child item is checked.
This is one of the weirdest structure i ever saw, anyway here is your solution
http://jsfiddle.net/Gak2h/6/
if you want to uncheck when all elements is unchecked change
$this.prop('checked', nbOfCheckeds == 0);
Insert this after the $childs.each({...}); (which you migh want to rename to children.each)
if(!checked){
$elem.prev("table").find(":checkbox:first").prop('checked',false);
}
it traverses up the DOM to find the preceeding table element that's is the parent in the tree to the current node and then finds the first checkbox in that which should be the parent check box
it would then be
$('.tree').on('change', ':checkbox', function () {
var checked = this.checked;
var $elem = $(this).closest('table');
var depth = $elem.find('div').length;
var $childs = $elem.nextAll('table');
$childs.each(function () {
var $child = $(this);
var d = $child.find('div').length;
if (d <= depth) {
return false;
}
$child.find(':checkbox').prop('checked', checked);
});
if(!checked){
var len = $elem.find("tr:first>td").length;
for(;
$elem.find("tr:first>td").length=len;
$elem = $elem.prev("table")){}
$elem.find(":checkbox:first").prop('checked',false);
}
});

Categories