How to differentiate and club together multiple select dropdowns? - javascript

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

Related

How to set index variables in filters and selectors jquery

I have the following row structure that serves as a template to clone it and add it to a table each time a user presses an "Add" button, This template is hidden:
<tr class="plantilla">
<td>
<select class="cmb_arboles" id="cmb_arboles" name="arboles[]">
</select>
</td>
<td>
<input type="text" id="txttoneladas" name="txttoneladas[]"/>
</td>
<td>
<input type="text" id="txtprecio" name="txtprecio[]"/>
</td>
<td>
<select id="cmb_destino" name="destino[]">
</select>
</td>
<td class="eliminar_fila">
Eliminar
</td>
</tr>
When the "add" button is pressed, invokes:
$("#agregar").click(function()
{
nid++;
$("#plantilla tbody tr:eq(0)").clone().attr("id",nid).appendTo("#plantilla tbody");
$("#plantilla tbody tr:eq(nid)").find("td:eq(0)").find("select").attr("id","cmb_arboles_"+nid);
});
The first line, generates the sequence of the row number. The second line clones the entire template as a new row in the table and adds an id = nid to the .
The third line, accesses the row and looks for the select to add the nid sequential to the select id, but this does not work. When doing several tests, I conclude that the problem is that "tr: eq (nid)" does not accept the nid as variable, because when changing the nid by a specific integer, for example 1, it works, adding id to select. The question here is how to put the nid as a parameter in the: eq () so that it works correctly and do what I have explained ????
The same situation happens in the following line of code:
$(document).on('change', '.cmb_arboles', function () {
var $select = $(this);
var $row = $select.closest('tr');
var idd = $row.attr('id');
var valor=$("#tabla tbody tr[id=idd]").find("td:eq(0)").find("select").val();
});
Of lines 1 to 3, you get the number of the row in which you have selected in the select component.
The last line gets the value of the select that was selected, with the information of the row number where the selection was made, but this does not work. When doing several tests, I conclude that the problem is in "tr [id = idd]", which does not correctly process the variable "idd". I made the test of changing the idd by a specific integer, for example 1 and then I generate a new line in the table with id = 1 and the line of code works correctly, returning the option that was selected in the select element.
With these two examples, I want to check if someone can tell me how to place the parameters I mentioned in the two cases, so that the functionality is executed correctly and does what is expected.
I will be enormously grateful.
the issue is you have to give
("#plantilla tbody tr:eq(nid)" as (("#plantilla tbody tr:eq('"+nid+"')"
I have created a fiddle. check it out. I didn't use jquery for the same.
<style>
#template {
display: none;
}
</style>
<table><tbody id="template">
<tr class="plantilla">
<td>
<select class="cmb_arboles" id="cmb_arboles" name="arboles[]">
</select>
</td>
<td>
<input type="text" id="txttoneladas" name="txttoneladas[]" />
</td>
<td>
<input type="text" id="txtprecio" name="txtprecio[]" />
</td>
<td>
<select id="cmb_destino" name="destino[]">
</select>
</td>
<td class="eliminar_fila">Eliminar</td>
</tr></tbody>
</table>
<input type="button" id="agregar" value="Add">
<table>
<tbody id="plantilla"></tbody>
</table>
<script>
var nid = -1;
document.getElementById('agregar').onclick = function(){
var table = document.getElementById('plantilla');
var newRow = document.getElementById('template').innerHTML;
nid++;
newRow = newRow.replace('id="cmb_arboles"', 'id="cmb_arboles_'+nid+'"');
newRow.replace('id="cmb_arboles"', 'id="cmb_arboles_'+nid+'"');
table.innerHTML += newRow;
}
</script>
https://jsfiddle.net/nugee3s6/
You are hard coding the id value in $("#tabla tbody tr[id=idd]") not using the variable above it
If you wanted to use the variable it would be:
$("#tabla tbody tr[id=" +idd +"]")
But it makes no sense to use the ID to search again for the same row since you already have that row element as $row
So change to:
$(document).on('change', '.cmb_arboles', function () {
var $select = $(this);
var $row = $select.closest('tr');
var valor=$row.find("td:eq(0) select").val();
});
Then don't worry about using ID's, you don't need them

Dynamically populate user input corresponding json data with jquery

I have a json data that is like this,
[
{
"metalTypeId": 1,
"metalTypeName": "copper"
},
{
"metalTypeId": 3,
"metalTypeName": "steel"
}
]
My html is structured like this:
<table id="lineItemTable">
<tr class="row_to_clone">
<td>
<select>
<option>Select One Option</option>
<option>copper</option>
<option>steel</option>
</select>
</td>
<td>
<p></p>
</td>
</tr>
<tr class="row_to_clone">
<td>
<select>
<option>Select One Option</option>
<option>copper</option>
<option>steel</option>
</select>
</td>
<td>
<p></p>
</td>
</tr>
</table>
What I want to do is when the user select one of the options in the dropdown, I want to populate the corresponding json data to the p tag in my td. And my table contains two identical rows.
So for example, if user select copper for the first table row, and select steel for the second table row, the corresponding p will populate text "1" and "3" to the html page. If user do not select both rows, only the row that is selected will populate corresponding data to the p tag.
I am green to jQuery so I wrote some js code but it does not work as expected:
the variable that stores the json data is named as jasonData:
$('select').on('change', function (e){
$.each(jasonData, function(i, v) {
if (jasonData.metalTypeName == $('select').val()) {
$('p').text(v.metalTypeId);
return;
}
}); //end each()
}); // end on()
By looking at my code I already know one issue, the p and select select both two table row fields, but I do not know how to correctly fix it. The code may have other issues, please advice.
Your code is very close to working. You just need to cache the active select when it triggers the change event so you can reference it later; compare the active object in your each (you were incorrectly referencing the whole array); and use a few selectors to find the right paragraph. However, you may want to consider using something closer to David's answer. It's a bit cleaner than this method.
var jasonData = [
{
"metalTypeId": 1,
"metalTypeName": "copper"
},
{
"metalTypeId": 3,
"metalTypeName": "steel"
}
];
$('select').on('change', function (e){
var selected = this;
$.each(jasonData, function(i, v) {
if (v.metalTypeName === selected.value) {
$(selected).closest('.row_to_clone').find('p').text(v.metalTypeId);
return;
}
}); //end each()
}); // end on()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="lineItemTable">
<tr class="row_to_clone">
<td>
<select>
<option>Select One Option</option>
<option>copper</option>
<option>steel</option>
</select>
</td>
<td>
<p></p>
</td>
</tr>
<tr class="row_to_clone">
<td>
<select>
<option>Select One Option</option>
<option>copper</option>
<option>steel</option>
</select>
</td>
<td>
<p></p>
</td>
</tr>
</table>
I really recommend you not to use selectors so general such as "select" and "p"; while you are expanding your code, you'll get into issues because of these so generalized; I recommend you using some classes to help you or ID's.
Also, if you can change the structure of that JSON you won't need to do that each, basically you're forcing a O(n) problem there when you can something easier.
Here's an example I wrote for you doing the functionality that you want
http://jsfiddle.net/6v4zzgjj/
Now, if you want to make the selection of the results easier you can try the following
//Rename this variable better IE jsonData;
var jasonData = {"copper": { "metalTypeId": 1,"metalTypeName": "copper"}, "steel": {"metalTypeId": 3,"metalTypeName": "steel"}};
//Now the selector could be something like
$('.metalSelector').on('change', function (e){
var value = $(this).val();
$('#result').text(jasonData[value].metalTypeId);
});
That easy!

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 dynamically select checkbox group onChange

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/

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

Categories

Resources