remove array element in jquery - javascript

i have an dynamic array of multiple checkboxes. when i checked any checkbox then it get its value and put this in array. i want when i uncheck this then value of this checkbox remove from array. thnku..
$(document).ready(function (e) {
var myCheckboxescolour = new Array();
var myCheckboxesprice = new Array();
var mycolour;
var myprice;
$(".searchcheck").click(function () {
mycolour = '';
myprice = '';
if ($(this).attr('title') == 'colour') {
if (this.checked == true) {
myCheckboxescolour.push($(this).val());
} else {
if (jQuery.inArray($(this).val(), myCheckboxescolour)) {
myCheckboxescolour.pop($(this).val());
}
}
})
};

var removeValue = $(this).val();
myCheckboxescolour = jQuery.grep(myCheckboxescolour, function(value) {
return value != removeValue;
});

Related

How to get parameter name as array?

in my code i'm using google map api. here i used onclick method for button. if i clicked that dynamically it shows multiple textboxes. here i enter values for all text fields. But when i passing the parameter name into servlet page it takes only the first value of text box. how to get all the values?
My code
var button = document.getElementById('waypoint-input');
button.addEventListener("click", function () {
var parentNode = document.getElementById('waypoints-list');
var input = document.createElement('input');
input.type = 'text';
input.placeholder = 'Enter a waypoint location';
input.id = 'waypoint' + me.waypointIndex;
input.inputId = me.waypointIndex;
**input.name = 'waypointlist';**
input.addEventListener('input', function () {
if (input.value == "") {
var waypoint = me.waypts.filter(function (obj) {
return obj.key === input.inputId;
})[0];
if (waypoint != null && typeof waypoint !== "undefined") {
var waypointIndexToRemove = me.waypts.map(function (el) {
return el.key;
}).indexOf(input.inputId);
me.waypts.splice(waypointIndexToRemove, 1);
me.route();
}
}
});
var removeInput = document.createElement('button');
removeInput.innerHTML = 'Remove';
removeInput.onclick = function () {
parentNode.removeChild(input);
parentNode.removeChild(removeInput);
var childInputs = parentNode.getElementsByTagName('input');
if (childInputs.length > 0) {
for (var i = 0; i < childInputs.length; i++) {
childInputs[i].inputId = i;
}
}
if (input.value != "" && input.value != null) {
var waypointIndexToRemove = me.waypts.map(function (el) {
return el.key;
}).indexOf(input.inputId);
me.waypts.splice(waypointIndexToRemove, 1);
for (var i = input.inputId; i < me.waypts.length; i++) {
me.waypts[i].key = me.waypts[i].key - 1;
}
me.route();
}
me.waypointIndex--;
}
parentNode.appendChild(input);
parentNode.appendChild(removeInput);
var waypointAutocomplete = new google.maps.places.Autocomplete(input, { placeIdOnly: true });
me.setupPlaceChangedListener(waypointAutocomplete, 'WAYPOINT', input.inputId);
me.waypointIndex++;
}, false);
I found the solution to my question.
There is no changes to my script. I simply call the parameter name in servlet page. The name is waypointlist. And I change my servlet code little bit.
That is
String[] waypointlist=request.getParameterValues("waypointlist");
String waypointarray="";
for(int i=0;i<waypointlist.length;i++)
{
waypointarray += waypointlist[i] +"/";
}

How to check if $valueInput2 is equal with the generated value ? My code is returning a false value

How to check if $valueInput2 is equal with the generated value ? My code is returning a false value.
$(document).ready(function() {
var $buttonValue = $(".value_generate");
var $divValue = $(".generated_value");
var $generatedP = $(".generated_p");
var $valueInput2 = $(".value_input_2");
var $submitPages2 = $(".submit_pages_2");
function valueGenerator(value) {
var valueString="";
var lettersNumbers="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(var i = 0; i < value; i++)
valueString += lettersNumbers.charAt(Math.floor(Math.random()* lettersNumbers.length));
return valueString;} // generate a random value
$buttonValue.click(function generate() {
var $key = valueGenerator(12);
$generatedP.html($key);
}); // click to display the generated value
$submitPages2.click(function() {
if($valueInput2 == $generatedP.html() ){
alert("yes");
} else {
alert("no");
}
}); // check if input == generated value
I am new to jquery

Populate selected values using select2 multiple select

I have a select2 to select multiple options from a dropdown, i also have it selecting multiple options. Is there anyway of populating the input field with values that are selected on page load by changing its value in some way, so when the page is loaded there are options already selected.
part of my code as follows:
$('#fruitSelect').select2({
multiple: true,
placeholder: "Select fruits...",
data: FRUIT_GROUPS,
query: function (options) {
var selectedIds = options.element.select2('val');
var data = jQuery.extend(true, {}, FRUIT_GROUPS);
var selectableGroups = $.map(data, function (group) {
var areAllChildrenSelected = true,
parentMatchTerm = false,
anyChildMatchTerm = false;
if (group.text.toLowerCase().indexOf(options.term.toLowerCase()) >= 0) {
parentMatchTerm = true;
}
var i = group.children.length
while (i--) {
var child = group.children[i];
if (selectedIds.indexOf(child.id) < 0) {
areAllChildrenSelected = false;
};
if (options.term == '' || (child.text.toLowerCase().indexOf(options.term.toLowerCase()) >= 0)) {
anyChildMatchTerm = true;
}
else if (!parentMatchTerm) {
var index = group.children.indexOf(child);
if (index > -1) {
group.children.splice(index, 1);
};
};
};
return (!areAllChildrenSelected && (parentMatchTerm || anyChildMatchTerm)) ? group : null;
});
options.callback({ results: selectableGroups });
}
}).on('select2-selecting', function (e) {
var $select = $(this);
if (e.val == '') {
e.preventDefault();
$select.select2('data', $select.select2('data').concat(e.choice.children));
$select.select2('close');
}
});
JS Fiddle

Send single CheckBox value in array to server

I am having multiple checkboxes on form and I am going to submit the form.
$.fn.serializeObject = function () {
'use strict';
debugger;
var result = {};
var extend = function (i, element) {
var node = result[element.name];
// If node with same name exists already, need to convert it to an array as it
// is a multi-value field (i.e., checkboxes)
if ('undefined' !== typeof node && node !== null) {
if ($.isArray(node)) {
node.push(element.value);
} else {
result[element.name] = [node, element.value];
}
} else {
result[element.name] = element.value;
}
};
$.each(this.serializeArray(), extend);
return result;
};
and code is like
var that = $(this);
var temp = $(JSON.stringify());
form_data = that.serializeObject(temp);
form_data = JSON.stringify(form_data);
everything works fine but if I single select a checkbox then the value is like
"checkboxName":"value1"
and if I select multiple values of checkboc then the vale is like
"checkboxName":["value1","value2","value3"]
I want that a single value should also be selected in array format that is
"checkboxName":["value1"]
Thanks in advance.
If you try:
$.fn.serializeObject = function () {
'use strict';
debugger;
var result = {};
var extend = function (i, element) {
var node = result[element.name];
// If node with same name exists already, need to convert it to an array as it
// is a multi-value field (i.e., checkboxes)
if ('undefined' !== typeof node && node !== null) {
if ($.isArray(node)) {
node.push(element.value);
} else {
result[element.name] = [node, element.value];
}
} else {
//Here you are the checkbox condition
if(element.tagName == "INPUT" && element.getAttribute("type") == "checkbox") {
result [element.name] = [element.value];
} else {
result[element.name] = element.value;
}
}
};
$.each(this.serializeArray(), extend);
return result;
};

Dynamically building array, appending values

i have a bunch of options in this select, each with values like:
context|cow
context|test
thing|1
thing|5
thing|27
context|beans
while looping through the options, I want to build an array that checks to see if keys exist, and if they don't they make the key then append the value. then the next loop through, if the key exists, add the next value, comma separated.
the ideal output would be:
arr['context'] = 'cow,test,beans';
arr['thing'] = '1,5,27';
here's what i have so far, but this isn't a good strategy to build the values..
function sift(select) {
vals = [];
$.each(select.options, function() {
var valArr = this.value.split('|');
var key = valArr[0];
var val = valArr[1];
if (typeof vals[key] === 'undefined') {
vals[key] = [];
}
vals[key].push(val);
});
console.log(vals);
}
Existing code works by changing
vals=[];
To
vals={};
http://jsfiddle.net/BrxuM/
function sift(select) {
var vals = {};//notice I made an object, not an array, this is to create an associative array
$.each(select.options, function() {
var valArr = this.value.split('|');
if (typeof vals[valArr[0]] === 'undefined') {
vals[valArr[0]] = '';
} else {
vals[valArr[0]] += ',';
}
vals[valArr[0]] += valArr[1];
});
}
Here is a demo: http://jsfiddle.net/jasper/xtfm2/1/
How about an extensible, reusable, encapsulated solution:
function MyOptions()
{
var _optionNames = [];
var _optionValues = [];
function _add(name, value)
{
var nameIndex = _optionNames.indexOf(name);
if (nameIndex < 0)
{
_optionNames.push(name);
var newValues = [];
newValues.push(value);
_optionValues.push(newValues);
}
else
{
var values = _optionValues[nameIndex];
values.push(value);
_optionValues[nameIndex] = values;
}
};
function _values(name)
{
var nameIndex = _optionNames.indexOf(name);
if (nameIndex < 0)
{
return [];
}
else
{
return _optionValues[nameIndex];
}
};
var public =
{
add: _add,
values: _values
};
return public;
}
usage:
var myOptions = MyOptions();
myOptions.add("context", "cow");
myOptions.add("context","test");
myOptions.add("thing","1");
myOptions.add("thing","5");
myOptions.add("thing","27");
myOptions.add("context","beans");
console.log(myOptions.values("context").join(","));
console.log(myOptions.values("thing").join(","));
working example: http://jsfiddle.net/Zjamy/
I guess this works, but if someone could optimize it, I'd love to see.
function updateSiftUrl(select) { var
vals = {};
$.each(select.options, function() {
var valArr = this.value.split('|');
var key = valArr[0];
var val = valArr[1];
if (typeof vals[key] === 'undefined') {
vals[key] = val;
return;
}
vals[key] = vals[key] +','+ val;
});
console.log(vals);
}
Would something like this work for you?
$("select#yourselect").change(function(){
var optionArray =
$(":selected", $(this)).map(function(){
return $(this).val();
}).get().join(", ");
});
If you've selected 3 options, optionArray should contain something like option1, option2, option3.
Well, you don't want vals[key] to be an array - you want it to be a string. so try doing
if (typeof vals[key] === 'undefined') {
vals[key] = ';
}
vals[key] = vals[key] + ',' + val;

Categories

Resources