jQuery dynamically select checkbox group onChange - javascript

I have a dynamic set of rows with a dropdown and checkboxes in each and need to select all checkboxes onChange if a certain option value is selected.
This works fine for one group but when there's multiple rows and the option value is selected from one row, the onChange is triggering to select all checkboxes from all rows instead of that specific row.
I setup a fiddle to clarify what I mean - pretty sure i need to somehow get a counter of rows and pass in that counter number in the onChange so it doesn't select all checkboxes and only the row the dropdown being changed is in.
http://jsfiddle.net/7brzct64/
<table>
<tr>
<td>
<!--First row eventRegistrations[1]-->
<select name="eventRegistrations[1].eventRegistrationStatusTypeID" id="registrationStatusSelect">
<option value="1">Pending</option>
<option value="2">Attended</option>
</select>
</td>
<td>
<input type="checkbox" name="eventRegistrations[1].markAttendance[1].attendanceDate" value="1">9/21/14
<input type="checkbox" name="eventRegistrations[1].markAttendance[2].attendanceDate" value="2">9/22/14</td>
</tr>
<!--There could be multiple dynamic rows whose input names increment like eventRegistrations[i]-->
<tr>
<td>
<!--Next dynamic row eventRegistrations[2]-->
<select name="eventRegistrations[2].eventRegistrationStatusTypeID" id="registrationStatusSelect">
<option value="1">Pending</option>
<option value="2">Attended</option>
</select>
</td>
<td>
<input type="checkbox" name="eventRegistrations[2].markAttendance[1].attendanceDate" value="1">10/23/14
<input type="checkbox" name="eventRegistrations[2].markAttendance[2].attendanceDate" value="2">10/24/14</td>
</tr>
Works fine for first dropdown changed to "Attended" if I hardcode 1 in eventRegistrations[1].
I think need a counter to get each row somehow, loop or do an each() and pass in the couner number based on which dropdown is selected be eventRegistrations[i] based on which is selected
$("select[name^='eventRegistrations[1]']").change(function () {
if ($(this).val() === '2') {
$("input[name^='eventRegistrations[1]']").prop('checked', true);
/*
var regCount = $(":input[name^='eventRegistrations[i]']").length
for (i = 1; i <= regCount; i++) {
$("input[name^='eventRegistrations[i]']").prop('checked', true);
}*/
}
});
Thanks for the help!

You can bind the change function to all selects. Then you can check which one was used and get the starting string which is identical with the start of the check boxes. Just like this:
$("select").change(function () {
if ($(this).val() === '2') {
var start = $(this).attr("name").split(".")[0];
$("input[name^='" + start + ".markAttendance']").prop('checked', true);
}
});
http://jsfiddle.net/7brzct64/2/

Related

How to differentiate and club together multiple select dropdowns?

I have a table with multiple rows, and 4 columns. Each column contains a select dropdown, the options in the second column depends on the selection of first one, third one depends on second one and so on. I tried giving ids to selects and implementing onclick listeners. but it works only for the first row. Please help me solve this.
Here's the HTML code:`
<table>
{% for int i in (0,x) %}
<tr>
<td>
<select id='Product'>
<option>Car</option>
<option>Bike</option>
<option>Bus</option>
</td>
<td>
<select id='Model'>
</td>
<td>
<select id='Make'>
</td>
<td>
<select id='Color'>
</td>
</tr>
{% endfor%}
Here's the Jquery:
$("#product").change(function (event) {
event.preventDefault();
var val = $(this).val();
if( val == "none"){
$('#Model').empty().append($("<option></option>")
.attr("value","none")
.text("Select"));
$('#Make').empty().append($("<option></option>")
.attr("value","none")
.text("Select"));
$('#Color').val("Red");
}else{
var url_select = "/XYZ/product/?selected_product=" + val;
$(".innerload").css("visibility", "visible");
$.get(url_select, function(data){
$('#Model').empty().append($("<option></option>")
.attr("value","none")
.text("Select"));
$('#Make').empty().append($("<option></option>")
.attr("value","none")
.text("Select"));
$.each(data, function (i, item) {
$('#Model')
.append($("<option></option>")
.attr("value",item.model)
.text(item.model));
});
});
}
});
Similar jqueries for Model and Make onChange.
Please do not use same id in multiple time in loop id same for all time that's way it's not work

when option selected do stuff ( btw, all the elments have dynamic id)

I searched for similar questions, I found some but their solution did't help me.
For example:
First question
Second question
My problem is:
I have a table that the user can add rows dynamically, so I am creating a unique id for each row and all elements inside as well.
each row have two text fields and select with two options, and when you select one of the option the text feild should be dislpay:block and the second will be display: "none", depending on your choice.
I built here some example that will shows the general structure (JSFiddle)
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>
<input id="description-first-1" name="description-first-1" type="text" placeholder = "first">
<input id="description-second-1" name="description-second-2" type="text" placeholder = "second">
<select id="select-1">
<option>
<option id="first-opt-1">1</option>
<option id="second-opt-1">2</option>
</option>
</select>
</td>
</tr>
<tr>
<td>
<input id="description-first-2" name="description-first-1" type="text" placeholder = "first">
<input id="description-second-2" name="description-second-2" type="text" placeholder = "second">
<select id="select-2">
<option>
<option id="first-opt-2">1</option>
<option id="second-opt-2">2</option>
</option>
</select>
</td>
</tr>
$(function() {
$("#select-1").change(function() {
if ($("#first-opt-1").is(":selected")) {
$("#description-first-1").show();
$("#description-second-1").hide();
} else {
$("#description-first-1").hide();
$("#description-second-2").show();
}
}).trigger('change');
});
http://jsfiddle.net/8vz121rq/9/
In my example for that matter you can seen that there are only 2 rows but it can also be 10 rows with different id's.
How to get jquery identify which row and all the elements inside of it i'm changing if the id's of all elements is dynamic ?
First of all, you need event delegation as the rows are dynamically generated, such as:
$("table").on("change", "[id^='select']", function() {
// do your stuf
});
Or in your case:
$("table").on("change", "#select-1", function() {
// do your stuf
});
So, is this what you needed?
$(function() {
$("table").on("change", "[id^='select']", function() {
var $this = $(this);
var $row = $this.closest("tr");
var ID = this.id.replace(/^[^\-]+\-(\d+)$/gi, '$1');
var sIndex = $this.prop('selectedIndex');
var part = sIndex === 2 ? "second" : "first";
if (!sIndex) {
$row.find("input").show();
return;
}
$row.find("input").hide();
$row.find("#description-" + part + "-" + ID).show();
});
});
Demo#Fiddle
P.S. The above is purely based on your markup and ID structure!

JQuery clone and Onchange Events

I have a table with rows and input/select form elements. At the bottom row i have a button to add a new row to the Table. Initially the table is empty with just one row with a button
Like this:
<form name="test" id="test" action="#" >
<table id="matrix">
<tr id="1">
<td><select class="parent" name="parent">
<option value="C" label="C">C</option>
<option selected="selected" value="P" label="P">P</option>
<option value="B" label="B">B</option>
</select></td>
<td><div id="my_data_1">
<span title="parent_val"></span>
</div></td>
<td> </td>
</tr>
<tr >
<td colspan="3"><input type="button" class="add_new" /></td>
</tr>
</table>
</form>
Now when i click on the button with the add_new class i clone the first row, increment its id and then insert it above the last row.
The issue is that i have an onchange event attached to the select with class parent as
$('#matrix').on('change', 'select.parent_type', function() {
var RowID = $(this).closest('tr').attr('id');
var attributes_div = $('#matrix tr#'+RowID).find('div#my_data'+RowID );
new_id = GetParentIDFormat(attributes_div, 3);
$(attributes_div +"span[title='parent_val']").html(new_id);
});
When i added two or more rows, the change function changes the Value for SPAN "parent_val" for ALL the rows rather than the specific row whose SELECT parent was changed.
There were a few errors, without the GetParentIDFormat function, I cannot provide a 100% solution, but here goes:
'select.parent_type' should be 'select.parent'
$('#matrix tr#'+RowID).find('div#my_data'); should be
$('#' + RowID).find('.my_data');.
Note that you require classes, as you cannot have multiple equivalent IDs.
$(attributes_div +"span[title='parent_val']")
Should be
$("span[title='parent_val']", attributes_div)
Resulting in:
$('#matrix').on('change', 'select.parent', function() {
var RowID = $(this).closest('tr').attr('id');
var attributes_div = $('#' + RowID).find('.my_data');
var new_id = GetParentIDFormat(attributes_div, 3);
$("span[title='parent_val']", attributes_div).html(new_id);
});
The attributes_div variable points to a jQuery object, so you can't concatenate that with a string to get a selector to select the element you want. Instead just do this:
attributes_div.find('span[title="parent_val"]').html(new_id);
That will look for the <span title="parent_val"> element inside of the specific <div> referenced by attributes_div, and therefore should be the single element you want.
However, note that if you're cloning that row, you can't use an ID of my_data on all of the <div> elements as they're supposed to be unique; consider changing to a class instead.

How to manage table row associated javascript (control ID) while do clone the row

Initially, table has only one tr (label/header) and then on click of add button click , i create new tr which looks as below. and all other consequence click of add will clone the last tr.
<tr>
<script type="text/javascript">
//fetch the value of select picker control and set into hidden field.
AJS.$('#' + '${field_uid}-resourcetypepicker-new1').change(function () {
AJS.$('#' + '${field_uid}-resourcetype-new1').val(AJS.$(this).attr('value'));
});
//fetch the value of select picker control and set into hidden field.
AJS.$('#' + '${field_uid}-locationpicker-new1').change(function () {
console.log(AJS.$(this).attr('value'));
AJS.$('#' + '${field_uid}-location-new1').val(AJS.$(this).attr('value'));
});
</script>
<td>
<input id="${field_uid}-resourcetype-new1"
name="${field_uid}"
type="hidden"
value="$r.getResourceType()" />
<select id="${field_uid}-resourcetypepicker-new1">
<option value="adad" #if ($r.getResourceType() == "adad") selected="selected"#end >adad</option>
<option value="dada" #if ($r.getResourceType() == "dada") selected="selected"#end >dada</option>
<option value="aadd" #if ($r.getResourceType() == "aadd") selected="selected"#end >aadd</option>
</select>
</td>
<td>
<input id="${field_uid}-location-new1"
name="${field_uid}"
type="hidden"
value="$r.getLocation()" />
<select id="${field_uid}-locationpicker-new1">
<option value="Internal(Local)" #if ($r.getLocation() == "Internal(Local)") selected="selected"#end >Internal(Local)</option>
<option value="Contractor(Local)" #if ($r.getLocation() == "Contractor(Local)") selected="selected"#end >Contractor(Local)</option>
<option value="Contractor(Offshore)" #if ($r.getLocation() == "Contractor(Offshore)") selected="selected"#end >Contractor(Offshore)</option>
</select>
</td>
<td>
<input id="${field_uid}-rate-new1"
name="${field_uid}"
type="text"
value="$r.getRate()" /> <!-- $textutils.htmlEncode($r.getRate()) -->
</td>
<td>
<input id="${field_uid}-effort-new1"
name="${field_uid}"
type="text"
value="$r.getEffort()" />
</td>
</tr>
PROBLEM:
In above stuff, existing javascript that points to specific control id '#' + '${field_uid}-resourcetypepicker-new1' means (render ID looks like customfield-id-111-new1). Now, problem is, each clone row will have different unique ID for select/picker list control. and this javascript will points to first row control only as AJS.$('customfield-id-111-new1'). But it should be AJS.$('customfield-id-111-new2') then for next row AJS.$('customfield-id-111-new3') .
so, what is the best way to write below jquery stuff which can points to each cloned control rather then pointing to first row controls only ? any way through tr reference control or any other way.
AJS.$('#' + '${field_uid}-resourcetypepicker-new1').change(function () {
AJS.$('#' + '${field_uid}-resourcetype- new1').val(AJS.$(this).attr('value'));
});
Also, in cloned row, it did not include this javascript , do i need to append after clone ?
Please let me know if any more details need.
NOTE: AJS.$ is equal to $. it is used in velocity template file in JIRA.
Thank You
In light of the updated question, see the following code
AJS.$('[id^="${field_uid}-resourcetypepicker-"]')
This selector can be used to get any item with ID that starts with ${field_uid}-resourcetypepicker so you don't have to worry about the last part of the id i.e. new1, new2 etc.
Secondly, your change event will bind to all those elements that are present on page load. But if you create elements dynamically (clone or whatever), the events won't work. You should use
AJS.$('[id^="${field_uid}-resourcetypepicker-"]').on('change', function () {
...
});
This will work for all the elements on the page that match the selector

Jquery: Enable/Disable based on value of dropdown is not working for dynamically generated inputs

I have a form where I can add new rows to increase the form elements using jquery. In that form I have two dropdown options (Name:type and accounts) and two text inputs (Name:debit_amount and credit_amount).
Problem:
I have developed a jquery code to enable/disable text inputs based on the selected values from dropdown options. But the code works fine only if I don't add new rows. If I add a new row it only works for the very first row, I mean it disables/enables inputs of the first row only.
For the sake of clarity I have not provided the code for adding new rows below, but to get a live picture of all my codes please check this link, jsfiddle.net
Could you please tell me what change should I bring in my code to be able to make all the inputs (including inputs of generated rows ) disable/enable based on the selected values?
My HTML
<h2>Add Another Input Box</h2>
<table class="dynatable">
<thead>
<tr>
<th>Type</th>
<th>Account Name</th>
<th>Debit</th>
<th>Credit</th>
</tr>
</thead>
<tbody id="p_scents">
<tr>
<td>
<select name="type" id="type">
<option value="Debit">Debit</option>
<option value="Credit">Credit</option>
</select>
</td>
<td>
<select name="accounts" id="accounts">
<option value="">SELECT</option>
<option value="One">One</option>
<option value="Two">Two</option>
</select>
</td>
<td>
<input type="text" name="debit_amount" id="debit_amount" />
</td>
<td>
<input type="text" name="credit_amount" id="credit_amount"/>
</td>
</tr>
</tbody>
Conditions for disabling/Enabling
1. If type selected == Debit and a value from accounts is selected then enable debit_amount input and disable credit_amount input
2. If type selected == Credit and a value from accounts is selected then enable credit_amount input and disable debit_amount input
3. If any of the values of type and accounts is not selected disable both
My Jquery Code for disabling/enabling inputs based on dropdown value
//ON the change of accounts(dropdown select)
$("#accounts").change(function() {
var type = $("select#type").val();
var accounts = $("select#accounts").val();
if (type == "Debit") {
$('#credit_amount').attr("disabled", true);
$('#debit_amount').removeAttr("disabled", true);
}
if (type == "Credit") {
$('#debit_amount').attr("disabled", true);
$('#credit_amount').removeAttr("disabled", true);
}
if (accounts == "") {
$('input[name=credit_amount]').val('');
$('input[name=debit_amount]').val('');
$('#debit_amount').attr("disabled", true);
$('#credit_amount').attr("disabled", true);
}
});
//ON the change of type(dropdown select)
$("#type").change(function() {
var accounts = $("select#accounts").val();
var type = $("select#type").val();
if (type == "Debit" && accounts != '') {
$('input[name=credit_amount]').val('');
$('#credit_amount').attr("disabled", true);
$('#debit_amount').removeAttr("disabled", true);
}
if (type == "Credit" && accounts != '') {
$('input[name=debit_amount]').val('');
$('#debit_amount').attr("disabled", true);
$('#credit_amount').removeAttr("disabled", true);
}
});
The problem is that your input elements all have the same id attribute values, ie: "debit_amount" and "credit_amount", so jQuery doesn't know which ones the "#debit_amount" and "#credit_amount" selectors refer to.
Element ids should be unique in the page, so you should append a sequence number to the end of each eg:
<select name="accounts_1" id="accounts_1">
....
<input type="text" name="debit_amount_1" id="debit_amount_1" />
<input type="text" name="credit_amount_1" id="credit_amount_1" />
Two solutions:
use the jQuery traversal API to find the input elements relative to the select element that triggered the onChange event. This is brittle and will break if you change your markup too much
parse the sequence number out of the <select> id attribute and use it to find the <input>s you want to modify

Categories

Resources