How do you reference a checkbox array name value? - javascript

I have a sequence of checkboxes and associated select lists. If the checkbox is checked I need to take the value of the corresponding select option and then change the total, but I can't seem to reference this value. Here is a simplified version of the HTML code:
<table>
<tr>
<td>
<input type="checkbox" name="checkboxCK[]" id="checkboxAR1" class="check" />
</td>
<td>
<select name="addonR[]" class="select-colour">
<option value="50">1 ($50)</option>
<option value="100">2 ($100)</option>
<option value="150">3 ($150)</option>
<option value="200">4 ($200)</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="checkboxCK[]" id="checkboxAR2" class="check" />
</td>
<td>
<select name="addonR[]" class="select-colour">
<option value="50">1 ($50)</option>
<option value="100">2 ($100)</option>
<option value="150">3 ($150)</option>
<option value="200">4 ($200)</option>
</select>
</td>
</tr> <tr>
<td>
<input type="checkbox" name="checkboxCK[]" id="checkboxAR3" class="check" />
</td>
<td>
<select name="addonR[]" class="select-colour">
<option value="50">1 ($50)</option>
<option value="100">2 ($100)</option>
<option value="150">3 ($150)</option>
<option value="200">4 ($200)</option>
</select>
</td>
</tr>
<table>
$<span id="theTotalAmount">150</span>
And the javascript code:
$("input.check:checkbox").click(function(){
//run through allcheckboxes that are checked and pull corresponding select option value
for (var i = 0; i < document.getElementsByName('checkboxCK[]').length; i++)
{
//get the value of the selected option
var s = document.getElementsByName('addonR['+i+']');
var theAmount = s.options[s.selectedIndex].value;
console.log(theAmount);
//check the checkbox is checked and if so add the corresponding select value
if(document.getElementsByName('checkboxCK['+i+']').checked)
{
totalCost = totalCost+document.getElementsByName('addonR['+i+']').value;
}
}
//rewrite the html for total amount
document.getElementById("theTotalAmount").innerHTML = totalCost;
});
I am struggling to reference the s variable.. It keeps being undefined. Can anyone see why?
Or is there a better way to achieve what I am trying to do?

The names of the checkboxes don't have a number between the square brackets in the HTML. You shouldn't put one there with your JavaScript.
document.getElementsByName('addonR[]') will give you an (array-like) HTML Collection of all the elements with that name.

Write
var s = document.getElementsByName('addonR[]')[i];

Related

How can I add/remove select boxes from DOM when all select boxes have one name so that upon Submit I get value from active select box?

TL;DR: I want to be able to make a selection using currently-active HTML select box, when I have multiple select boxes with the same name, but only one of them is to be active at any one time.
--
My question is this - I have multiple filename select boxes, that upon submit, always send the value of the last select box that is at the bottom of HTML that has filename name in HTTP Request. I want to find a way to send only the filename that is associated with the currently-active a_XX_row box, and not any others.
i.e. I select id of 40, I should only see the box that says "A-40 Designer and Specs", and not the 800 box. When I press submit I want POST['filename'] to have the "A-40 Designer and Specs", but instead I always get the "A-800 Designer E.xlsm", because it is the last select in the HTML file.
$('#modelid').on('change', function() {
if (this.value == 40)
$('.a_40_row').show();
else
$('.a_40_row').hide();
if (this.value == 800)
$('.a_800_row').show();
else
$('.a_800_row').hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form><table>
<tr>
<td>
<select name="id" id="modelid">
<option value="0">--select--
<option value="40">40
<option value="800">800
</select>
</td>
</tr>
<tr class="a_40_row" style="display: none;">
<td>Version</td>
<td>
<select name="filename">
<option selected>A-40 Designer and Specs B.xlsm</option>
<option>A-40 Designer and Specs A.xlsm</option>
</select>
</td>
</tr>
<tr class="a_800_row" style="display: none;">
<td>Version</td>
<td>
<select name="filename">
<option>A-800 Designer E.xlsm</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit"></td>
</tr>
</table></form>
don't show/hide selects form.
you just need to update the second select when the first is changed
the way to do that:
const
myForm = document.forms['my-form']
, filenames =
[ { model: '40', cod: 'A-40-B', fn:'A-40 Designer and Specs B.xlsm' }
, { model: '40', cod: 'A-40-A', fn:'A-40 Designer and Specs A.xlsm' }
, { model: '800', cod: 'A-800-E', fn:'A-800 Designer E.xlsm' }
]
myForm.modelid.onchange = () =>
{
myForm.filename.innerHTML = ''
filenames
.filter(x=>x.model===myForm.modelid.value)
.forEach( filename=>
{
myForm.filename.add( new Option(filename.fn,filename.cod))
}
)
}
select,
button {
display : block;
float : left;
clear : left;
margin : .3em;
}
select {
min-width : 8em;
padding : 0 .3em;
}
<form name="my-form">
<select name="modelid" >
<option value="" selected disable >--select--</option>
<option value="40" > 40 </option>
<option value="800" > 800 </option>
</select>
<select name="filename"></select>
<button type="submit">submit</button>
</form>
Two options,
Enable/disable the element as you show it.
Populate one field with what you need.
Option 1 :
$('#modelid').on('change', function() {
//Set visibility
$('.a_40_row').toggle(this.value == 40);
//Toggle disabled
$('.a_40_row [name=filename]').prop("disabled", this.value != 40);
$('.a_800_row').toggle(this.value == 800)
$('.a_800_row [name=filename]').prop("disabled", this.value != 800);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form><table>
<tr>
<td>
<select name="id" id="modelid">
<option value="0">--select--</option>
<option value="40">40</option>
<option value="800">800</option>
</select>
</td>
</tr>
<tr class="a_40_row" style="display: none;">
<td>Version</td>
<td>
<select name="filename" disabled>
<option selected>A-40 Designer and Specs B.xlsm</option>
<option>A-40 Designer and Specs A.xlsm</option>
</select>
</td>
</tr>
<tr class="a_800_row" style="display: none;">
<td>Version</td>
<td>
<select name="filename" disbled>
<option>A-800 Designer E.xlsm</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit"></td>
</tr>
</table></form>
Option 2 : - This uses HTML 5 which has issues in IE 10 and less
$('#modelid').on('change', function() {
$(".row").show();
var selVal = $(this).val();
//Go through the options
$("[name=filename] option").each(function(){
//Dont use jquerys data here, it will convert to a number when it can
//Get array of values where can display from the data attribute
var arrDisplay = this.dataset.display.split(",");
//Add the hidden property if not contained in array -- wont work in IE 10 and older
$(this).prop("hidden", !arrDisplay.includes(selVal));
//Set a default
$(this).prop("selected", $(this).data("optiondefault") && !arrDisplay.includes(selVal) )
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form><table>
<tr>
<td>
<select name="id" id="modelid">
<option value="0">--select--</option>
<option value="40">40</option>
<option value="800">800</option>
</select>
</td>
</tr>
<tr class="row" style="display: none;">
<td>Version</td>
<td>
<select name="filename">
<option data-display="40" data-optiondefault="true">A-40 Designer and Specs B.xlsm</option>
<option data-display="40">A-40 Designer and Specs A.xlsm</option>
<option data-display="800" data-optiondefault="true">A-800 Designer E.xlsm</option>
<option data-display="40,800">Hybrid</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit"></td>
</tr>
</table></form>

How can I make dynamically created dependent select/dropdowns using just jQuery

I have a table with dynamically created rows, on each row I want to have 2 dropdowns/selects that are dependent on each other.
I have found 2 fiddles, the first is the exact output i want but the code is confusing and uses json. the second code is the easiest to understand but is not dynamic. Is there a way to make them work together?
// http://jsfiddle.net/C2xsj/5/ <----- this is the output i want but the code is kinda confusing for me
// https://jsfiddle.net/fwv18zo1/ <--- this has the simpler code
lets assume this is my table:
<INPUT type="button" value="Add Row" id="button"/>
<form id="myForm">
<TABLE id="addTable" >
<TR><TD>
<select id="selectCategory">
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>
</TD>
<TD>
<select id="selectSubCategory" >
<option value="1">Banana</option>
<option value="1">Apple</option>
<option value="1">Orange</option>
<option value="2">Wolf</option>
<option value="2">Fox</option>
<option value="2">Bear</option>
<option value="3">Eagle</option>
<option value="3">Hawk</option>
<option value="4">BWM<option>
</select>
</TD></TR>
</TABLE>
</form>
when someone clicks the add row button, it creates a new row
using something similar to this all the options are coded into this function such as ():
$('#button').click(function() {
var table = $('#addTable');
table.append('<tr><td data-label="Task"><select class="ui fluid search dropdown" required><option value="1">Fruit</option><option value="2">Animal</option><option value="3">Bird</option><option value="4">Car</option></select><select class="ui fluid search dropdown" required><option value="1">Banana</option><option value="1">Apple</option><option value="1">Orange</option><option value="2">Wolf</option><option value="2">Fox</option><option value="2">Bear</option><option value="3">Eagle</option><option value="3">Hawk</option><option value="4">BWM<option></select></tr>');
}
so my issue is that since they cant all have the same id such as the ones in the fiddle, how i make the pair of selects on each row dependent
Here i used clone function. read comment on JS to know more.
$(document).on("change",".select1",function(){
var thisParent = $(this).parents("tr"); // detect the parent of the select1.
$(".select2",thisParent).find('option[value]').addClass('hidden'); // hide all option values.
$(".select2",thisParent).find('option[value="' + this.value + '"]').removeClass('hidden'); // show only values that match the 'select1' value.
});
$(".addNew").click(function(){ // clone button
$(".cloneThis").clone().appendTo("tbody"); // clone the class 'cloneThis' and append it into tbody.
$("tr:last").removeClass("cloneThis"); // remove 'cloneThis' class from the last appended child, so you can clone it again from the original one.
$("button:last").removeClass("addNew").addClass("removeThis").html("Remove"); // replace 'Add' with 'Remove' and add class 'removeThis' to be able to remove this tr.
});
$(document).on("click",".removeThis",function(){ // remove function.
$(this).parents("tr").remove(); // find this button parent and remove it.
});
table{
width:100%;
}
select, button{
width:30%;
}
.hidden{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr class="cloneThis">
<td>
<select name="select1" class="select1">
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>
<select name="select2" class="select2">
<option>Select type first</option>
<option value="1" class="hidden">Banana</option>
<option value="1" class="hidden">Apple</option>
<option value="1" class="hidden">Orange</option>
<option value="2" class="hidden">Wolf</option>
<option value="2" class="hidden">Fox</option>
<option value="2" class="hidden">Bear</option>
<option value="3" class="hidden">Eagle</option>
<option value="3" class="hidden">Hawk</option>
<option value="4" class="hidden">BWM<option>
</select>
<button class="addNew">Add</button>
</td>
<tr>
</tbody>
</table>

Chained Dropdown(s) and Textbox in HTML

I am having a use case for a design:
There are students who have to pay their fees every month in a class.
So I am trying to do the following:
1. Dropdown #1: Contains Student Names
2. Dropdown #2: Contains Month Names
3. Textbox: Contains Fees amount for the selected month.
I am using the following code:
$(document).ready(function() {
$("#myDropdown").change(function() {
var selectedValue = $(this).val();
$("#txtBox").val(selectedValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="tab1">
<tr>
<td>Select Affiliate Source:</td>
<td>
<select id="myDropdown">
<option value="jan" label="2000">January</option>
<option value="apr" label="2500">April</option>
<option value="jul" label="2000">July</option>
<option value="oct" label="2500">October</option>
</select>
<div>
<input id="txtBox" type="text" readonly='1'>
</div>
</td>
</tr>
</table>
taken from stackoverflow. but i am unable to:
1. add a dropdown (for students) in a chained fashion, such that once a student is selected only then the months dropdown gets active.
2. once a month is selected, the value in its label attribute should be displayed in the textbox.
Any inputs will be more than appreciated.
Regards,
GenXCoders
Enable month select box onchange of student select box.
Get the value of month select box on onchange and set in text box.
$(document).ready(function() {
$("#student").change(function() {
$('#month').prop('disabled', false);
});
$("#month").change(function() {
var selectedValue = $('#month :selected').attr('label');
$("#txtBox").val(selectedValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="tab1">
<tr>
<td>Select Affiliate Source:</td>
<td>
<select id="student">
<option value="Student1">Student1</option>
<option value="Student2">Student2</option>
<option value="Student3">Student3</option>
</select>
<select id="month" disabled>
<option value="jan" label="2000">January</option>
<option value="apr" label="2500">April</option>
<option value="jul" label="2000">July</option>
<option value="oct" label="2500">October</option>
</select>
<div>
<input id="txtBox" type="text" readonly='1'>
</div>
</td>
</tr>
</table>

Onchange select item value set on the next column input field for each row in jquery

I'm trying to get the selected item's data-price to set on the next column's input field. It's working for first row but not working for each row.
How do I get this done?
<td>
<select class="clientType" name="type[]">
<option value="" disabled selected>Type</option>
<option data-price="3" value="3">R</option>
<option data-price="10" value="10">EB</option>
<option data-price="3" value="3">ND</option>
<option data-price="" value="">Special</option>
</select>
</td>
<td>
<input class="clientAmt" type="number" name="amount[]">
</td>
jQuery:
$('.clientType').change(function () {
$(this).each(function() {
$('.clientAmt').val($('option:selected', this).data('price'));
})
})
remove the each and go to the closest row to find the .clientAmt
$('.clientType').change(function() {
$(this).closest('tr').find('.clientAmt').val($('option:selected', this).data('price'));
});
DEMO
$('.clientType').change(function() {
$(this).closest('tr').find('.clientAmt').val($('option:selected', this).data('price'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<select class="clientType" name="type[]">
<option value="" disabled selected>Type</option>
<option data-price="3" value="3">R</option>
<option data-price="10" value="10">EB</option>
<option data-price="3" value="3">ND</option>
<option data-price="" value="">Special</option>
</select>
</td>
<td>
<input class="clientAmt" type="number" name="amount[]">
</td>
</tr>
<tr>
<td>
<select class="clientType" name="type[]">
<option value="" disabled selected>Type</option>
<option data-price="3" value="3">R</option>
<option data-price="10" value="10">EB</option>
<option data-price="3" value="3">ND</option>
<option data-price="" value="">Special</option>
</select>
</td>
<td>
<input class="clientAmt" type="number" name="amount[]">
</td>
</tr>
</table>
Problem : The problem in your code is
$(this).each(function() {
$('.clientAmt').val($('option:selected', this).data('price'));
})
Here $(this) is just one select element, so your loop will be executed only once anyways. The main problem is this $('.clientAmt').val(...) Here you are selecting all the input elements with the class clientAmt, The selector returns you array of elements, And when you set any attribute on this array of elements it will be applied only for the first element in the array. Hence it always applies to your first input. You have to select the appropriate input and assign the value to only this one.
Solution :
So you have two options to resolve this
1) Using parent().next() : use parent() on the select tag which will give you the td of this select tag and then do next on this td which will take you to the next td that has the input in it. Now set the value of this input
$('.clientType').change(function() {
$(this).parent().next().find('.clientAmt').val($('option:selected', this).data('price'));
});
2) Using closest('tr').find('.clientAmt'): use closest() to find the closest tr which wraps this entire row, that is the tr which wraps this td and other td which holds the input. Now from this tr find the input with class clientAmt with in it
$('.clientType').change(function() {
$(this).closest('tr').find('.clientAmt').val($('option:selected', this).data('price'));
});
$(document).on('change', 'select', function () {
let next_select = $(this);
// console.log(next_select.toArray())
if (!next_select.parent().parent().next().find('select').length) {
next_select.parent().parent().parent().next().find('input[type="text"]').click()
console.log(next_select.parent().parent().parent().next());
} else if (next_select.parent().parent().next().find('select').prop("disabled")) {
setTimeout(function () {
next_select.parent().parent().next().find('select').select2('open')
}, 1000)
console.log('b');
} else if (next_select.parent().parent().next().find('select').length) {
next_select.parent().parent().next().find('select').select2('open')
console.log('c');
}
});

cloned form fields not submitting (no $_POST data)

I have a form in a table with the option to duplicate a certain row (thus allowing users to add more fields as needed). The cloning works fine and the events data and handlers work fine. However when the form is submitted, the cloned form field data does not post. Below is my code for cloning the fields which works fine and solves any issue of duplicate IDs. Any suggestions/help as to why the cloned field do not submit would be absolutely appreciated.
$('#btnAddNewField').click(function() {
var currLength = $('.cloneInput').length;
var newID = new Number(currLength + 1);
var clonedField = $('#field_id' + currLength).clone(true);
clonedField[0].setAttribute('id', 'field_id' + newID);
clonedField.find(':text').each(function() {
this.setAttribute('id', this.getAttribute('id') + newID);
this.setAttribute('name', this.getAttribute('name') + newID);
});
$('#field_id' + currLength).after(clonedField);
HTML:
<tr id="field_id_1">
<td>
<table>
<tr>
<td>Pick option</td>
<td>
<select name="choice_1" id="choice_1" parent="true">
<option value="null" selected="selected">Select</option>
<option value="1">option 1</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
</select>
</td>
</tr>
<tr>
<td>Pick next option</td>
<td>
<select name="next_choice_1" id="next_choice_1">
<option value="null" selected="selected">Select next</option>
</select>
</td>
</tr>
<tr>
<td>Image:</td>
<td><input type="file" name="image_1" id="image_1"/></td>
</tr>
</table>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="button" value="Add New" id="btnAddNewField" />
<input type="button" value="Remove" id="btnDelField" />
</td>
</tr>
I don't see anywhere where you are changing the name property of the cloned form fields. You will need to change this in order to not have the posted data just overwritten by the additional fields.
I think you are mistaken by how post works. You should actualy create a new name for the cloned field, as that is what is used for posting the variables. Creating a new id is only nessecary to produce valid html, but has nothing to do with the actual posting.

Categories

Resources