The following function is supposed to remove a selected value from the selectbox,
and update a hidden field with all values.
I have two problems with it:
Lets say I have the following options in the selectbox : 1071,1000,1052
After removing the first option (1071), the hidden field is getting a value of 1052,1000,1000,
if I remove the second option (1000) the hidden field is 1052,1052,1071
if I remove the third one (1052), I get an options[...].value is null or not an object
Can someone plz help me fix this ?
function removeOptions() {
var selectbox = document.getElementById('zipcodes');
var zipcodes = document.getElementById('zip');
var tmpArray = [];
var i;
for (i = selectbox.options.length - 1; i >= 0; i--) {
if (selectbox.options[i].selected){
selectbox.remove(i);
}
tmpArray.push(selectbox.options[i].value);
}
zipcodes.value = tmpArray.join(',');
}
Assuming you don't need the selected value in hidden value, place the portion to push in tmpArray in else part
if (selectbox.options[i].selected){
selectbox.remove(i);
}else{
tmpArray.push(selectbox.options[i].value);
}
Related
I have a list with names. I want to sort this names if I check there checkbox, but i don't know how to select those checkboxes that are checked and use them.
I tryed to use the checkbox id's to compare them if they where checked, but that did'nt work out :(
I found a solution, by putting the checked checkboxes in an array and giving the checkboxes an id that contains the name. I can compare the id with the list of names and make out that way what is checked.
function box_checked() {
var box = document.getElementsByClassName('box');
var box_array = [];
i = 0;
il = box.length;
for (;i < il; i += 1) {
if (box[i].checked) {
box_array.push(box[i].id);
}
}
}
Please include your HTML code or any attempts you made so others can help you.
This is how I do it.
let checked = document.querySelectorAll("input[name=name_of_your_checkbox]:checked")
let checkboxValues = [] // TEMP VARIABLE
// CHECKS IF NO SELECTION MADE
if (Object.keys(checked).length == 0) {
alert("Please select atleast 1")
return
}
// PUT THE SELECTED VALUES TO THE TEMP VARIABLE
checked.forEach(r => {
checkboxValues.push(r.value)
});
I have a scenario where a user is able to select multiple cells on a grid. I would like to validate the users selection and deselect any invalid cells. I am trying to achieve this in the change function on my grid. My current approach is to get the currently selected cells, determine which cells are valid and select the list of valid cells I have found.
According to Kendo's documentation, the grid.select() function does take a parameter, but only takes an array of rows as a parameter. This explains why the below isnt working.
I need a solution which allows me to set which cells are highlighted and also retrieve the highlighted cells (I currently can get selected cells via the grid.select() method).
Is there a reasonable way to do this?
$scope.myKendoGridOptions = {
selectable: "multiple, cell",
change: function (e) {
if (!$scope.jsSelectChangeEvent) {
var grid = $('#myKendoGrid').data("kendoGrid");
var selectedItems = grid.select();
if (selectedItems.length > 1) {
var validItems = [];
var validRowIndex = selectedItems[0].closest("tr").rowIndex;
for (var i = 0; i < selectedItems.length; i++) {
if (selectedItems[i].closest("tr").rowIndex === validRowIndex) {
validItems.push(selectedItems[i]);
}
}
//Avoids Infinite loop
$scope.jsSelectChangeEvent = true;
//im expecting this to select my valid cells, but it has no effect
grid.select(validItems);
}
} else {
$scope.jsSelectChangeEvent = false;
}
}
};
The grid.select(validItems) does accept cells as a parameter. The problem is that I need to call grid.clearSelect() prior to calling grid.select to get the desired effect.
I have 2 drop downs and I can move the objects from one to another using the buttons. I want to get the updated values after I am done with moving them from one drop down to another. the values in the array is coming out to be null.
How can I get the updated value of all the options in an array. I need to pass the updated values to the controller from one function like function AddFiles(iniIdArray,afterIdArray)
http://jsfiddle.net/678hmujh/1/
var varInitialId = document.getElementById('iniId');
for (i = 0; i < varInitialId.options.length; i++) {
iniIdArray[i] = varInitialId.options[i].value;
}
var varAfterId = document.getElementById('afterId');
for (i = 0; i < varAfterId.options.length; i++) {
afterIdArray[i] = varAfterId.options[i].value;
}
You could use map: http://jsfiddle.net/678hmujh/4/
$('#listButton').on('click', function() {
var first = $('#iniId option').map(function(){ return this.value; });
var second = $('#afterId option').map(function(){ return this.value; });
console.log( first.toArray() );
console.log( second.toArray() );
});
By doing first.toArray() or second.toArray() you can get a basic javascript array of what was built.
$('select#iniId > option').each(function() {
$(this).text(); //is your option text
$(this).val(); //is your option value
});
I have multiple checkboxes in a view and each one has some data attributes, example:
Once the button is clicked I'm iterating through all the checkboxes which are selected and what I want to do is get the data-price and value fields for each selected checkbox and create JSON array.
This is what I have so far:
var boxes2 = $("#modifiersDiv :checkbox:checked");
var selectedModifiers = [];
var modifierProperties = [];
for (var i = 0; i < boxes2.length; i++) {
for (var k = 0; k < boxes2[i].attributes.length; k++) {
var attrib = boxes2[i].attributes[k];
if (attrib.specified == true) {
if (attrib.name == 'value') {
modifierProperties[i] = attrib.value;
selectedModifiers[k] = modifierProperties[i];
}
if (attrib.name == 'data-price') {
modifierProperties[i] = attrib.value;
selectedModifiers[k] = modifierProperties[i];
}
}
}
}
var jsonValueCol = JSON.stringify(selectedModifiers);
I'm not able to get the values for each checkbox and I'm able to get the values only for the first one and plus not in correct format, this is what I'm getting as JSON:
[null,"67739",null,"1"]
How can I get the correct data?
You can use $.each to parse a jquery array, something like:
var jsonValueObj = [];
$("#modifiersDiv :checkbox:checked").each(function(){
jsonValueObj.push({'value':$(this).val(),'data-price':$(this).attr('data-price')});
});
jsonValueCol = JSON.stringify(jsonValueObj);
Please note it's generally better to use val() than attr('value'). More information on this in threads like: What's the difference between jQuery .val() and .attr('value')?
As for your code, you only had one answer at most because you were overwriting the result every time you entered your loop(s). Otherwise it was okay (except the formatting but we're not sure what format you exactly want). Could please you provide an example of the result you would like to have?
if you want to get an object with all checked values, skip the JSON (which is just an array of objects) and make your own....
var checked =[];
var getValues = function(){
$('.modifiers').each(function(post){
if($(this).prop('checked')){
checked.push({'data-price':$(this).attr('data-price'),'value':$(this).attr('value')});
}
});
}
getValues();
sure i'm missing something obvious here.. but mind is elsewhere
This should give an array with values (integers) and prices (floats):
var selected = [];
$("#modifiersDiv :checkbox:checked").each(function()
{
var val = parseInt($(this).val(), 10);
var price = parseFloat($(this).data("price"));
selected.push(val);
selected.push(price);
});
Edit: Updated answer after Laziale's comment. The $(this) was indeed not targeting the checked checkbox. Now it should target the checkbox.
I have a simple question. I have a select list like this:
var myarray = ["one", "two", "three"];
var container = document.createElement("select");
for (var i = 0; i < myarray.length; i++) {
var element = document.createElement("option");
var textlabel = document.createTextNode(myarray[i]);
if (element.nodeValue == "two") {
element.selected = true;
}
element.appendChild(textlabel);
container.appendChild(element);
}
document.body.appendChild(container);
I have two questions about it:
1) I am pretty sure that the element that should be selected right now is "two"... isn't it?
2) Since the option elements are being created dinamically inside a loop (there are no three different option variables for me to play with, but just one that gets renewed as the loop goes forward), how do I reference the selected one for future uses?
For example, imagine that later on I get user input, and according to that input I want that this list has as a selected item, "three".
Thank you for any help! Here is the fiddle if you want to use it...
1) I am pretty sure that the element that should be selected right now
is "two"... isn't it?
No, it's not: you check element.nodeValue, while in fact you should've been checking textLabel's one - or just the content itself:
if (myarray[i] === 'two') {
element.selected = true;
}
2) Since the option elements are being created dinamically inside a
loop (there are no three different option variables for me to play
with, but just one that gets renewed as the loop goes forward), how do
I reference the selected one for future uses?
See, <select> elements has two useful properties: options (which contains all the options in it, and is updated dynamically) and selectedIndex. You can combine them to get the selected option:
container.addEventListener('change', function() {
console.log(this.options[this.selectedIndex]);
}, false);
But if what you want is to know the value of selected element, that's even easier - with container.value.
For example, imagine that later on I get user input, and according to
that input I want that this list has as a selected item, "three".
That's piece of cake if you know the position of the option that corresponds to this: just use selectedIndex property again:
container.selectedIndex = 3;
Just change the following in the for loop to fix the selection problem:
if (myarray[i] == "two")
Try to use console.log (on chrome or firefox with firebug) to debug your script :
Try this :
var myarray = ["one", "two", "three"];
var container = document.createElement("select");
container.id = "mySelect" ;
for (var i = 0; i < myarray.length; i++) {
var element = document.createElement("option");
var textlabel = document.createTextNode(myarray[i]);
element.appendChild(textlabel);
if (element.value == "two") {
element.selected = true;
}
container.appendChild(element);
}
document.body.appendChild(container);
in order to refer to your selected element you should give your select element an id and access to it like below:
el = document.getElementById('mySelect');
el.selectedIndex ; // give you the selected index
el.options[el.selectedIndex]; // give you the value