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

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!

Related

How can I get selected row using jQuery?

This is my table row within the tbody of my table. I get dropdown value, text value but I can't get selected row value. My row value returns "undefined".
$(document).on("click", "#skorKartDegerle", function() {
$("#modal_evaluation").modal("show");
});
$(document).on("click", "#btnKaydet", function() {
var arrList = [];
var isEmptyAnswer = false;
$("#evaluationTable > tbody > tr").each(function() {
var line = $(this).find(".answerLine").val();
var ddlVal = $(this).find(".answerddl").val();
var txtVal = $(this).find(".answertxt").val();
var obj = '{"line":"' + line + '","ddlVal":"' + ddlVal + '","txtVal":"' + txtVal + '"}';
arrList.push(obj);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr class="answerLine" value="2">
<td>FR002</td>
<td>Koton Mağazacılık</td>
<td>1800</td>
<td>A</td>
<td>Kabul</td>
<td class="select" value="0">
<select class="answerddl">
<option value="1">Kabul</option>
<option value="2">Ret</option>
</select>
</td>
<td><input type="text" class="answertxt"></td>
</tr>
</tbody>
</table>
Part of the issue is because tr elements do not have a value attribute. To do what you require you could use a data attribute instead, to store custom metadata on the element. The other part is that this is a reference to the tr element. You're then calling find() on the element you're looking to target, so it will not be found as that method looks for descendants only.
In addition it's worth noting that you can make the logic more succinct by using map() to build the array instead of explicitly looping with each() and also that it would be better practice to store objects in the array and only JSON encode it before transferring via AJAX.
$(document).on("click", "#btnKaydet", function() {
var isEmptyAnswer = false;
let arrList = $("#evaluationTable > tbody > tr").map((i, tr) => {
let $tr = $(tr);
return {
line: $tr.data('value'),
ddlVal: $tr.find(".answerddl").val(),
txtVal: $tr.find(".answertxt").val()
}
}).get();
console.log(arrList);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="evaluationTable">
<tbody>
<tr class="answerLine" data-value="2">
<td>FR002</td>
<td>Koton Mağazacılık</td>
<td>1800</td>
<td>A</td>
<td>Kabul</td>
<td class="select" value="0">
<select class="answerddl">
<option value="1">Kabul</option>
<option value="2">Ret</option>
</select>
</td>
<td><input type="text" class="answertxt"></td>
</tr>
</tbody>
</table>
<button id="btnKaydet">Click me</button>

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

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

Show hide input element based on selection

Hi I am trying to show hide input element based on selection value of another element.
However I am unable to achieve it. I am not sure what is wrong I am doing.
The JS Fiddle is here :
https://jsfiddle.net/rovvLt9e/1/
<div>
<table>
<tr id="type">
<td height="30">Type</td>
<td>
<input type="radio" name="type" value="Document" checked>Document
<input type="radio" name="type" value="Parcel">Parcel
</td>
</tr>
</br>
</br>
<tr id="height">
<td height="40">Approx weight of consignment</td>
<td>
<select name="weight">
<option selected>200gms</option>
<option>200 - 500gms</option>
<option>500 - 750gms</option>
<option>750gms - 1Kg</option>
<option>1Kg - 5Kg</option>
<option> > 5Kg</option>
</select>
</td>
</tr>
</table>
</div>
</br></br>
<div id="text"> text</div>
The Jquery is :
$(document).ready(function () {
if ($('#type').val() == "Parcel") {
$('#height').show();
}
else {
$('#height').hide();
}
});
https://jsfiddle.net/rovvLt9e/1/
Try to use change event to accomplish your task,
$(document).ready(function() {
var elem = $('#height');
var radios = $(':radio[name=type]').change(function() {
elem.toggle(radios.filter(":checked").val() == "Parcel");
});
});
And note, you have to use attribute selector here as there was no element with id type.
DEMO
There is no element with id type. Bind change event to input[name=type] and toggle visibility like following.
$('input[name=type]').change(function() {
$('#height').toggle(this.value=="Parcel");
});
$('input[name=type]:checked').change(); //to set initial state
UPDATED FIDDLE
Try using selector #type input , .change() event
$(document).ready(function() {
var h = $("#height");
$("#type input").change(function() {
if (this.checked && this.value == "Parcel") {
h.show();
} else {
h.hide();
}
}).change()
});
jsfiddle https://jsfiddle.net/rovvLt9e/6/

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.

Categories

Resources