selecting multiple ids by the same class - javascript

$('.myclass').attr('id');
myclass is the class of the selected table cells which have unique ids. No more than 2 table cells can be selected at once by the user. I need to capture the ids of the selected table cells and assign them to var1 and var2. Users can deselect cells and choose new ones... I thought about using an array but that's probably not the best way.

I'd go with the array option using map(), eg
var ids = $('.myclass').map(function() {
return this.id;
}).get();
if (ids.length >= 2) {
var var1 = ids[0];
var var2 = ids[1];
}

var selectedCells = [];
$('.myclass').each(function() { selectedCells.push($(this).attr('id')) });

Create an array and assign it to var1 and var 2 depending upon size.
arr = $.map($('.myclass'), function (element) {
return element.id;
});

Related

How to make my Array to be empty again and reusable for my Edit Text Function

Newbie here.. I was making an expense note app(just a noob app). I have this button function on which when I select one table row.. It will be deleted and the table row input text value will return to the input bar text area(name, date, amount, remarks). I was happy when it work.
But it only work once.
Because when I select different table row data. It will be deleted but the same "first input data value" will always return to the input text bar..
It seems the first table data are being saved in the empty array function that can be reuse again. What I am hoping for is when I use the empty array function it will be empty again to be use in another different table row data.
I am using array methods but failed or my If statement is wrong. Hopefully you can answer this :) thanks
document
.getElementById("editSelection")
.addEventListener("click", editSelection);
function editSelection() {
var editName = [];
var editDate = [];
var editAmount = [];
var editRemarks = [];
let selectedRows = document.getElementsByClassName("selected-row ");
while (selectedRows.length > 0) {
editName.push(cell0.innerText);
editDate.push(cell1.innerText);
editAmount.push(cell2.innerText);
editRemarks.push(cell3.innerText);
selectedRows[0].parentNode.removeChild(selectedRows[0]);
var name = document.getElementById("inputName");
name.value = editName.join("\n");
var date = document.getElementById("inputDate");
date.value = editDate.join("\n");
var amount = document.getElementById("inputAmount");
amount.value = editAmount.join("\n");
var remarks = document.getElementById("inputRemarks");
remarks.value = editRemarks.join("\n");
}
if (name || date || amount || remarks) {
editName.splice([0], editName.length);
editDate.splice([0], editDate.length);
editAmount.splice([0], editAmount.length);
editRemarks.splice([0], editRemarks.length);
}
}
If you define an empty array
var editName = [];
and fill it with values you can empty it again with
editName = [];

Iterate through Id's, store values, put into an array

I want to be able to iterate through a number of ids called "#option1", "#option2" etc. The problem is its for an interactive form and I don't know how many options there will be. So I need a way to iterate through the amount in the DOM when the user clicks ("#dothis").
Then I need to get the values of the those options, put into an array called arraylist.
$("#doThis").on("click", function() {
var optionone = $("#option1").val();
var optiontwo = $("#option2").val();
var optionthree = $("#option3").val();
var optionfour = $("#option4").val();
var optionfive = $("#option5").val();
var arrayList = [optionone, optiontwo, optionthree,
optionfour, optionfive];
var decide = arrayList[Math.floor(Math.random() *
arrayList.length)];
$("#verdict").text(decide);
}); // end of dothis click event
As Andy said, give every option the same class. In my example it's "option-item".
$("#doThis").on("click", function() {
var arrayList = [];
$('.option-item').each(function(i) {
arrayList[i] = $(this).val();
});
var decide = arrayList[Math.floor(Math.random() *
arrayList.length)];
$("#verdict").text(decide);
});
Every value is now stored in the array.
see fiddle.
greetings timmi
With your code as is, you can use a selector that selects everything with an ID that starts with 'option', like so [id^="option"], here's how to use it:
$("#doThis").on("click", function () {
var arrayList = [];
$('[id^="option"]').each(function (index, element) {
arrayList.push($(element).val() );
});
var decide = arrayList[Math.floor(Math.random() *
arrayList.length)];
$("#verdict").text(decide);
}); // end of dothis click event

Getting value of selected checkbox with jquery from checkboxes without id's

I have a number of checkboxes that are generated from a JavaScript API call from a database. I need to be able to pass the values of the checkboxes which are then selected by the user, and sent to the processing page. The issue is that the checkboxes don't have ID's associated with them(or this wouldn't be a problem) They all have the same name, but no ID's.
What is the best way to find which check boxes are selected, and pass their values to the following page?
One way I started was with an array:
var options = ["option1","option2","option3"];
var option 1 = [0];
var option 2 = [1];
var option 3 = [2];
On the processing page, using:
var option1 = getFromRequest('option1') || '';
var option2 = getFromRequest('option2') || '';
var option3 = getFromRequest('option3') || '';
Is there a better way of doing this?
I've changed the implementation to the following:
var values = []
$("input:checkbox.subIndustry").each(function(){
values.push(this.value);
});
passing the values to the success page with
window.location.href = REGISTER_SUCCESS +'&values='values.join(",")
which should then get the value with
var variablname = getFromRequest('values') || "";
This is returning Undefined. Any help?
An easy way to select them would be something like $("input[type=checkbox]:checked")
However, if you wanted to keep up with them as they are checked, even if they are added after you load, you could create a variable, then asign a delegation to the "change" state of each input that is a checkbox and update this variable on each change.
It's as simple as:
var checked, checkedValues = new Array();
$(function() {
$(document).on("change", "input[type=checkbox]", function(e) {
checked = $("input[type=checkbox]:checked");
// if you wanted to get an array of values of the checked elements
checkedValues = checked.map(function(i) { return $(this).val() }).get();
// make a string of the values as simple as joining an array!
var str = checkedValues.join(); // would return something like: value1,value2,ext...
});
})
Working Example
Since all your checkboxes have the same name, you can retrieve the checked ones using a variation of:
var checked = $('input[name=ckboxname]:checked');
see: :checked selector for more information
you can simply get the values of checked checkboxes by using
$('input[name=checkboxname]:checked').val();
this will give you the value of checkbox which is checked and for all values simply use
each function of jquery.
Turns out, the answer was to utilize indexOf in the underscore.js library. The solution had to be applied in the API being used to send data.
(_.indexOf(values, '9') != -1 ? 1 : '0'),

getting the value of multiple checkboxes and using ajax to preform an action with their values

I have a table that has checkboxes, if a checkbox is selected i want a raw in the DB to be deleted - using ajax.
with normal form i would simply name all the chexboxs some name lets say name="checkbox[]"
and then simply use foreach($_POST['checkbox'] as $value){}
now i am trying to get all the values of marked checkboxes then put them into an array. seems i am missing something though. here is what i go so far:
var checkboxes = jQuery('input[type="checkbox"]').val();
var temp = new Array();
jQuery.each(checkboxes, function(key, value) {
temp[] = value;
});
Late on i will just pass temp as variable to ajax call.
Is there anything i am missing ?
You can use :checked selector and map method:
var arr = $('input[type="checkbox"]:checked').map(function(){
return this.value
}).get();
You are trying to iterate over the Checkbox values which is wrong . Try this
var $checkboxes = jQuery('input[type="checkbox"]') ;
var temp = new Array();
jQuery.each($checkboxes, function(i) {
var value = $(this).attr('value');
temp[i] = value;
});
If you want to pass only checked items just add a condition.
if($(this).is(':checked')){
var value = $(this).attr('value');
temp[i] = value;
}
Just wrap the table in a form tag, and do this:
var myData = jQuery('#myform').serialize();
jQuery.ajax('myscript.php', {data:myData});

jQuery Selecting Elements That Have Class A or B or C

I working on something where I need two functions.
1 - I need to look at a group of children under the same parent and based on a class name, "active", add that element's ID to an array.
['foo-a','foo-b','foo-d']
2 - I then iterate through all the children in another parent and for each element I want to find out if it has any class name that match the ids in the array.
Does this element have class foo-a, foo-b or foo-d?
For the first part, I'd use map and get:
var activeGroups = $('#parent .active').map(function() {
return this.id;
}).get();
This gives you an array of id values (say, ['foo-a', 'foo-d']). You can then make a selector like .foo-a, .foo-b, .foo-c (the multiple selector) using join:
var activeSelector = '.' + activeGroups.join(', .');
This makes a valid jQuery selector string, e.g. '.foo-a, .foo-d'. You can then use this selector to find the elements you want using find:
var activeEls = $('#secondParent').find(activeSelector);
You can then do whatever you need to with activeEls.
var active = $("#foo").find(".active").map(function() {
return this.id;
}).get();
$("#anotherParent *").each(function() {
var that = this;
var classes = $(this).attr("class");
if(classes.indexOf(" ") !== -1) {
classes = classes.split(" ");
} else {
classes = [ classes ];
}
$.each(classes, function(i, val) {
if($.inArray(val, active)) {
// this element has one of 'em, do something with it
$(that).hide();
}
});
});
There's always .is('.foo-a, .foo-b, .foo-d'). Or if you actually just wanted to select them, instead of iterating and deciding for each element, $('.foo-a, .foo-b, .foo-d', startingPoint).

Categories

Resources