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

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'),

Related

How to generate one object key with an array of stored values from multiple on click events using localstorage and Jquery

I'm new to coding, and I need to display past search values from an input field using localstorage. The only way I can think of is by using one object key with an array of stored values from an on click event. Problem is, I can only get one position to appear as a value, with each value generated replacing the last. I've tried for loops and can't seem to get it to work. This is the code I have so far:
$('.search-city').on('click', function(e){
e.preventDefault();
var textArr = [];
var text = $(".form-control").val();
textArr.push(text);
localStorage.setItem("value1", textArr);
});
$('.search-city').on('click', function(e){
e.preventDefault();
var search = localStorage.getItem("value1")
This would work:
$('.search-city').on('click', function(e){
e.preventDefault();
// get the value from local storage
var localValue = localStorage.getItem('value1');
// if we had a value, parse it back to an array, if we dont, create an empty array
var textArr = localValue ? JSON.parse(localValue) : [];
// get the text from the search input, dont use "form-control"
// you're likely to have several of those on the page
// give the element a custom class like "search-input" and use that (id would be even better)
var text = $('.search-input').val();
// add the text to the array
text = trim(text);
if (text) {
textArr.push(text);
}
// enforce a size limit here by removing the 0 index item if the count has grown too large
var maxAllowed = 10;
while (textArr.length > maxAllowed) {
textArr.shift();
}
// localstorage can only hold simple strings so we'll JSON stringify our object and store that
localValue = JSON.stringify(textArr);
localStorage.setItem("value1", localValue);
});

How to use two IDs from JS?

On my page with payment I need two inputs with total payment value:
- one that the client can see
- another one which is hidden.
I wrote a code which pass price of every element to the input when a client check a box with a product they want to pay for, but it works only with the one input.
I was trying to use different options (like getElementsByName and getElementsByClassName) but I am learning JS now and I have no idea how to solve this problem. :(
function select(selector, parent){
return Array.from((parent||document).querySelectorAll(selector));
}
var inputs = select('.sum'),
**totalElement = document.getElementById('payment-total');**
function sumUpdate(){
totalElement.value = inputs.reduce(function(result, input){
return result + (input.checked ? parseFloat(input.value) : 0);
}, 0).toFixed(0);
}
WHAT I TRIED:
var inputs = select('.sum'),
**totalElement = document.getElementsByName('payment-total')[0][1];**
var inputs = select('.sum'),
**totalElement = document.getElementsByName('payment-total, payment-total2')[0][1];**
var inputs = select('.sum'),
**totalElement = document.getElementsByName('payment-total).getElementsByName('payment-totalTwo);**
If I'm understanding you right, you want to put the computed value in both the id="payment-total" element and the id="payment-total2" element.
If so, just do what you've already done for payment-total, but for payment-total2 as well, see *** comments:
var inputs = select('.sum'),
totalElement = document.getElementById('payment-total'),
totalElement2 = document.getElementById('payment-total2'); // ***
function sumUpdate(){
//vvvvvvvvvvvvvvvvvvvvvv---- ***
totalElement2.value = totalElement.value = inputs.reduce(function(result, input){
return result + (input.checked ? parseFloat(input.value) : 0);
}, 0).toFixed(0);
}
I don't immediately see the reason for having both a visible and a hidden input, but if you need that for some reason, that's how you'd do it.
If it got to the point there were three or more elements you wanted to update, I'd probably give them all a class and select them the way you've selected your .sum elements, then compute the total once and assign it to all of them in a loop. But for just two, repeating the lookup and assignment seems fine.

How to remove multiple select options based on dynamic value

I have 2 select boxes, with the second showing a subset of all options based on the category in the first box. The second box contains ids and names, where the option value equals the id. I already filtered out the id's I am interested in and have them in an array. This will change each time and can be different sizes (filtering all users by groups). What I would like to do is take a clone of the complete options and then only show those whos id (or value) is present. So, compare the array of filtered values to the complete set. I did see a couple ways to remove options, but most were for only one value at a time or for fixed values, so it didn't exactly fit what I need and I can't figure out how to do this last step! Looks like the following:
<select id = 'doctor_select' >
<option value = '1' > John Doe </option>
<option value = '2' > Jane Doe </option>
.... etc
edit: solved for now by hiding all and doing a for each loop to enable the ones I need.
I wouldn't do it like this, but you could clone the original combo and simply remove the unnecessary options from the DOM. Something like:
var newDoctorSelect=$("#doctor_select").clone();
$(newDoctorSelect).children("option").each(function() {
if(some condition) $(this).remove();
});
$("#somewhere").append(newDoctorSelect);
But I'd recommend either using AJAX or storing the options in an object and populating the select when needed.
var optionsByCategory={
"1":{"1":"One","3":"Three"},
"2":{"2":"Two"}
};
$("#categorySelect").on("change",function() {
var options=optionsByCategory[$(this).val()];
//OR some AJAX call to retreive the options from the server instead
$("#doctor_select option").remove();
for(var k in options) $("#doctor_select").append($("<option>").val(k).text(options[k]));
});
You could do this:
var options = getElementsByTagName("option"),
elem,
length = options.length;
for (var i = 0; i<length; i++) {
if (!((elem = options[i]).value === IDYouWantToMatch)); elem.parentNode.removeChild(elem);
}
I think you want something like the following using filter()
var $sel = $('#doctor_select'),
$opts = $sel.children();
var $filteredOpts = $opts.clone().filter(function(){
return someArray.indexOf(this.value)>-1;
})
$sel.empty().append($filteredOpts);
The stored $opts can now be re-used for future changes

get latest option of multiple select with jQuery

How to get last choosen option in multiple select?
$('#select').change(function(event) {
...
});
I do not need all values provided by val(), but LATEST choosen option which triggered change.
Thanks
I fear that you can't have it so easily, even with jQuery. But you can store the old values and compare with the current value.
var last = [];
$('#select').change(function(event) {
var val = $(this).val();
var newValues = val.filter(function(element)) {
// You may need a more specific test for your values
return last.indexOf(element) == -1;
});
// newValues are the new selected options in the select
last = val;
});
But WARNING : If the user cancel an option, the change event is triggered too. And newValues will be empty (because there's no new values, only a missing value).

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});

Categories

Resources