JQuery set select from string - javascript

I have the following table
<table id="table_device">
<tr>
<td> First td </td>
<td> Second td </td>
<td>
<select class="base_MD">
<option>A value</option>
<option>Another value</option>
<option>And another one</option>
...
</select>
</td>
<td> The value </td>
</tr>
<tr></tr>
<tr></tr>
...
</table>
How do I set the <select> where the <option> matches with the 4th child (named 'The value') for each <tr> tag?
EDIT
I tried the following
$('#table_device').find('tr').each(function()
{
var value = $(this).find(':nth-child(4)').html();
$('select').each(function()
{
if($(this).text() == value)
{
var id = $(this).val();
}
$(this).eq(id).prop('selected', true);
})
});
But it did not work ...
I'm sure it's not that complicated but my head will explode soon

You can iterate over each select element. get the text from next td and use it to set option by text. Like this:
$('#table_device select').each(function(){
var nexttdtext = $(this).parent().next('td').text();
$(this).find("option").filter(function() {
return this.text == nexttdtext;
}).attr('selected', true);​
});
Working Demo

Bind an onchange event to the list. Find the selected option and the text inside it. And put it in the first row, last cell...
$(function() {
$('.base_MD').on('change', function() {
var value = $(this).find(':selected').text();
$('#table_device tr:first-child td:last-child').text( value );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table_device">
<tr>
<td> First td </td>
<td> Second td </td>
<td>
<select class="base_MD">
<option>A value</option>
<option>Another value</option>
<option>And another one</option>
...
</select>
</td>
<td> The value </td>
</tr>
<tr></tr>
<tr></tr>
...
</table>

Related

How to give value from select box everytime increase button of dynamically Input Jquery

I am using jQuery dynamic table inputs in my form.Whenever i select country,i get the value from select box.But when i increase dynamic button (+) and again select the country from select box from another input field.i get same value of country from first selectbox field
<table class="dynamic-fields-table">
<thead>
<tr>
<th >Country</th>
<th >City</th>
<th></th>
</tr>
</thead>
<tbody data-role="dynamic-fields">
<tr class="form-inline">
<td>
<select name="country[]" class="form-control">
<option value="1">USA</option>
<option value="2">Russia</option>
<option value="3">Japan</option>
</select>
</td>
<td>
<input type="text" name="city[]" class="form-control">
</td>
<td>
button data-role="add">Add</button>- // button for increasing or decreasing input
</td>
</tr>
</tbody>
</table>
In script file.When I select country at first it will come value right in console.but when i increase input form then i select again another country then value of country will give same as first time selected.So how should i give value of country i selected everytime i increase dynamically input button
$(document).on(
'click',
'[data-role="dynamic-fields"],
function(e) {
e.preventDefault();
var container = $(this).closest('[data-role="dynamic-fields"]');
new_field_group = container.children().filter('.form-inline:first- child').clone();
new_field_group.find('input').each(function(){
$(this).val('');
});
container.append(new_field_group);
updatecity()
}
);
$(document).on('change', " select[name='country[]']", function(){
updatecity();
});
function updatecity(){
$country = $(" select[name='country[]']").val();
console.log($country)
}
Currently, updatecity always gives you the value of the first result of $(" select[name='country[]']"). While the values of the other dropdown lists are ignored.
function updatecity(){
$country = $("select[name='country[]']").val();
console.log($country)
}
To make each dropdown list's call to updatecity behave with respect to its own value, you can add a parameter to updatecity to tell which country to update.
function updatecity($target){
$country = $target.val();
console.log($country);
}
Having the function signature changed, you will also need to update places where you call updatecity
$(document).on(
'click',
'[data-role="add"]',
function(e) {
// ...
updatecity($("select[name='country[]']"))
});
$(document).on('change', "select[name='country[]']", function(e){
updatecity($(this));
});
Also, the code you're showing will insert a new inline-form whenever <tbody> is clicked, so I changed the selector from [data-role="dynamic-fields"] to [data-role="add"]
As a sidenote, I notice that updatecity doesn't actually do anything except logging a value. You might want to have its behavior match its name.
Below I've attached a code snippet for demonstration.
$(document).on(
'click',
'[data-role="add"]',
function(e) {
e.preventDefault();
var container = $(this).closest('[data-role="dynamic-fields"]');
new_field_group = container.children().filter('.form-inline:first-child').clone();
new_field_group.find('input').each(function(){
$(this).val('');
});
container.append(new_field_group);
updatecity($("select[name='country[]']"))
}
);
$(document).on('change', "select[name='country[]']", function(e){
updatecity($(this));
});
function updatecity($target){
$country = $target.val();
console.log($country)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<table class="dynamic-fields-table">
<thead>
<tr>
<th >Country</th>
<th >City</th>
<th></th>
</tr>
</thead>
<tbody data-role="dynamic-fields">
<tr class="form-inline">
<td>
<select name="country[]" class="form-control">
<option value="1">USA</option>
<option value="2">Russia</option>
<option value="3">Japan</option>
</select>
</td>
<td>
<input type="text" name="city[]" class="form-control">
</td>
<td>
<button data-role="add">Add</button><!-- button for increasing or decreasing input-->
</td>
</tr>
</tbody>
</table>

JavaScript, append HTML and reference IDs in function

I have a form that shows a drop-down menu and a text field next to it:
<html>
<body>
<table>
<tbody class="project_wrapper">
<tr>
<td scope="row">
<select id="test_project" name="test_project[]">
<option selected>Select</option>
<option>10</option>
<option>20</option>
</select>
</td>
<td><input id="test_value" name="test_value[]" type="text" placeholder="Enter value"></td>
<td><div id="test_calc"></div></td>
</tr>
</tbody>
<tbody>
<tr>
<td colspan="3">
Add another project
</td>
</tr>
</tbody>
</table>
</body>
</html>
You can select one of the values in the drop-down, and when you enter a numeric value into the text field, on each keyup, it'll display the value multiplied by the selected value. You can also click the "Add another project" link and it'll append/create another drop-down and text field. This already works, and is done with the following Jquery code:
<script type="text/javascript">
$(document).ready(function(){
var addProject = $('.add_project');
var wrapper = $('.project_wrapper');
var projectHTML = `<tr>
<td scope="row">
<select id="test_project2" name="test_project[]" class="custom-select">
<option selected>Select</option>
<option>10</option>
<option>20</option>
</select>
</td>
<td><input id="test_value2" name="test_value[]" type="text" placeholder="Enter value"></td>
<td><div id="test_calc2"></div></td>
</tr>`;
$(addProject).click(function(){
$(wrapper).append(projectHTML);
});
});
$('#test_value').keyup(function(){
$('#test_calc').text(Math.round($(this).val() * $("#test_project option:selected").val()));
});
The problem is I can't get the multiplication function to work/display the result for any newly appended lines. Above you can see I tried hardcoding the values of test_value2 and test_calc2 and then added this below:
$('#test_value2').keyup(function(){
$('#test_calc2').text(Math.round($(this).val() * $("#test_project2 option:selected").val()));
});
I would expect the result (at least for one new appended line) to appear in the same way as for the first line, but nothing seems to happen. My goal is to get the results to appear for the appended line, and then also find a way to have that keyup calculation function work for any number of appended lines (rather than hardcode 2, 3, 4, etc. values).
The ids, I think, will need to be dynamically assigned as the lines are appended, and then the name will stay the same to hold the arrays for test_array and test_value which I'm going to receive and process via PHP.
Thanks!
Remove all your IDs from the template rows, use classes or name="" instead as your selectors
Assign an ID to your TBODY, we'll use it as the .on() event delegator
Use the "input" event, not the "keydown" event. You can also copy/paste values, remember?
on "input" - refer to the parent TR using .closest() before descending back (using .find()) to find the elements specific for that row
Use parseInt() or parseFloat() to handle input strings. Also remember to always fallback to a number i.e: 0 to prevent NaN results
jQuery(function($) {
const projectHTML = `<tr>
<td>
<select name="test_project[]" class="custom-select">
<option value="" selected>Select</option>
<option value="10">10</option>
<option value="20">20</option>
</select>
</td>
<td><input name="test_value[]" type="type" placeholder="Enter value"></td>
<td><div class="result"></div></td>
</tr>`;
const $projects = $("#projects"); // assign an ID to your tbody
const $addProject = $('.add_project');
const arrRow = () => $projects.append(projectHTML);
// Create new row on click
$addProject.on("click", arrRow);
// Add the first row
arrRow();
// use a delegator which is not dymanic (the TBODY in this case),
// and use delegated events to any ":input" element:
$projects.on("input", ":input", function(ev) {
const $tr = $(this).closest("tr");
const $project = $tr.find('[name="test_project[]"]');
const $value = $tr.find('[name="test_value[]"]');
const $result = $tr.find(".result");
const project = parseInt($project.val(), 10) || 0;
const value = parseFloat($value.val()) || 0;
const result = project * value;
$result.text(result);
});
});
<table>
<tbody id="projects"></tbody>
<tbody>
<tr>
<td colspan="3">
Add another project
</td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
The IDs must be unique, instead whenever you add another row you duplicate the IDs.
Instead of IDs I changed them to class in order to combine this keyword with .closest() and .find() to get the values of interest.
Moreover, because you add new elements to the table you need to delegate the event.
If you change the select you need to calculate again, not only on typing into the input field.
var addProject = $('.add_project');
var wrapper = $('.project_wrapper');
var projectHTML = '<tr>\
<td scope="row">\
<select class="test_project" name="test_project[]" class="custom-select">\
<option selected>Select</option>\
<option>10</option>\
<option>20</option>\
</select>\
</td>\
<td><input class="test_value" name="test_value[]" type="number" placeholder="Enter value"></td>\
<td><div class="test_calc"></div></td>\
</tr>';
$(addProject).click(function () {
$(wrapper).append(projectHTML);
});
$(document).on('input', '.test_value', function (e) {
$(this).closest('tr').find('.test_calc').text(Math.round($(this).val() * $(this).closest('tr').find('.test_project option:selected').val() || 0));
});
$(document).on('change', '.test_project', function(e) {
$(this).closest('tr').find('.test_value').trigger('input');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody class="project_wrapper">
<tr>
<td scope="row">
<select class="test_project" name="test_project[]">
<option selected>Select</option>
<option>10</option>
<option>20</option>
</select>
</td>
<td><input class="test_value" name="test_value[]" type="number" placeholder="Enter value"></td>
<td>
<div class="test_calc"></div>
</td>
</tr>
</tbody>
<tbody>
<tr>
<td colspan="3">
Add another project
</td>
</tr>
</tbody>
</table>

How to use closest and parents javascript methods to get td value in angular 6

I am trying to get table tr and second td values using parents('tr) and closest('tr') javascript methods and after selected dropdown.But not working i have searched in google nut no use.If anyone know please help to find the solutions.
app.component.html:
<table>
<thead>
<tr>
<td>Emp id</td>
<td>Roll id</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<tr>
<td>12345</td>
<td>18956</td>
<td>12356</td>
<td>
<select (change)="getTdValue(e)">
<option value="gettdvalue">Get second td value of this row</option>
</select>
</td>
</tr>
<tr>
<td>12345</td>
<td>18906</td>
<td>12356</td>
<td>
<select (change)="getTdValue(e)">
<option value="gettdvalue">Get second td value of this row</option>
</select>
</td>
</tr>
<tr>
<td>12345</td>
<td>98956</td>
<td>12356</td>
<td>
<select (change)="getTdValue(e)">
<option value="gettdvalue">Get second td value of this row</option>
</select>
</td>
</tr>
<tr>
<td>12345</td>
<td>13956</td>
<td>12356</td>
<td>
<select (change)="getTdValue(e)">
<option value="gettdvalue">Get second td value of this row</option>
</select>
</td>
</tr>
</tbody>
</table>
app.component.ts:
getTdValue(e){
let target = e.target.closest('tr');
if (target && target.id) {
let td = target.find('td:nth-child(2)');
if (td) {
console.log("Second td value is ="+ td.value )
}
}
}
https://stackblitz.com/edit/angular-peioe6?file=src/app/app.component.html
First you need to have a second option element inside your select element in order to get any change events triggered.
<select (change)="getTdValue($event)">
<option></option>
<option>Get second td value of this row</option>
</select>
Then you can rewrite your getTdValue method as follows:
getTdValue(mouseEvent: MouseEvent) {
let target = <HTMLSelectElement> mouseEvent.target;
let td = <HTMLTableCellElement> target.closest('tr').childNodes.item(1);
console.log("This row ID is " + td.innerHTML);
}
See following StackBlitz
UPDATE
When target.closest doesn't work (Angular 6), it can be replaced by target.parentElement.parentElement as follows:
getTdValue(mouseEvent: MouseEvent) {
let target = <HTMLSelectElement> mouseEvent.target;
let td = <HTMLTableCellElement> target.parentElement.parentElement.childNodes.item(1);
console.log("This row ID is " + td.innerHTML);
}
You have an if statement that evaluates the following condition: target && target.id. Since none of your <tr> element have an ID, the statement will evaluate to false, and none of the logic contained therein will be executed.
Since you are not using the ID for anything, you can simply remove it:
getTdValue(e){
let target = e.target.closest('tr');
if (target) {
let td = target.find('td:nth-child(2)');
if (td) {
console.log("Second td value is ="+ td.value )
}
}
}

Filter table with three select inputs using jQuery

I have 3 <select> from which I would like to filter a table and at the same time filter each other using their options. I will first show you the code:
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div>
Select A type
<select id="A">
<option>Toate</option>
<option>A1</option>
<option>A2</option>
<option>A3</option>
</select>
</div>
<div>
Select B type
<select id="B">
<option>Toate</option>
<option>B1</option>
<option>B2</option>
<option>B3</option>
<option>B4</option>
<option>B5</option>
<option>B6</option>
</select>
</div>
<div>
Select C type
<select id="C">
<option>Toate</option>
<option>C1</option>
<option>C2</option>
<option>C3</option>
<option>C4</option>
<option>C5</option>
<option>C6</option>
<option>C7</option>
<option>C8</option>
<option>C9</option>
<option>C10</option>
</select>
</div>
<br/>
<table id="X">
<thead>
</thead>
<tbody>
<tr>
<td>A1,B1,C1</td>
</tr>
<tr>
<td>A1,B1,C2</td>
</tr>
<tr>
<td>A1,B1,C3</td>
</tr>
<tr>
<td>A1,B2,C4</td>
</tr>
<tr>
<td>A1,B2,C5</td>
</tr>
<tr>
<td>A1,B3,C6</td>
</tr>
<tr>
<td>A2,B4,C7</td>
</tr>
<tr>
<td>A2,B5,C8</td>
</tr>
<tr>
<td>A2,B5,C9</td>
</tr>
<tr>
<td>A3,B6,C10</td>
</tr>
</tbody>
</table>
</body>
</html>
and the script I managed to pull off so far is this:
$('#A,#B,#C').on('change', function() {
$('table tbody tr td').css("display", "none");
var optiuneaSelectata = this.value;
$('table tbody tr td:contains("' + optiuneaSelectata + '")').css("display", "table-cell");
})
If I choose for example A1, I want to show in the table all the td that contain A1, if I choose A2 show all the td that contain A2 and so on. My code does just that so far. The problem is that I want to restrict the other selects too. For example if I choose C10, in the first select I should only be able to choose A3 and in the second one B6.
You could use the following code. It has a helper function which will build a CSS selector based on the 3 selected values in the 3 select boxes. The function can accept parameters in which case an exception can be made for one select box. The CSS selector will then use a specified value instead of the selected value in that particular select box.
The function will apply that CSS selector and return the rows that match.
The click handler will first use the above function to show only the rows in the table that match the three selected values. Then it will check which values in a select box can be combined with the two other selected values to find at least one row, again using the above helper function:
// Helper function: returns rows that meet the condition in the 3
// select boxes. The optional arguments can specify one of the select boxes
// and which value to use instead of the selected value in that select box
function getRows(override, value) {
var filter = "table tbody tr td";
$("#A,#B,#C").each(function() {
var test = this === override ? value : $(this).val();
if (test !== "Toate") filter += ":contains(" + test + ")";
});
return $(filter).parent();
}
$('#A,#B,#C').on('change', function() {
$('table tbody tr').hide();
getRows().show();
$('#A,#B,#C').each(function (i, select) {
$('option', this).each(function () {
$(this).toggle(getRows(select, $(this).text()).length > 0);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Select A type
<select id="A">
<option>Toate</option>
<option>A1</option>
<option>A2</option>
<option>A3</option>
</select>
</div>
<div>
Select B type
<select id="B">
<option>Toate</option>
<option>B1</option>
<option>B2</option>
<option>B3</option>
<option>B4</option>
<option>B5</option>
<option>B6</option>
</select>
</div>
<div>
Select C type
<select id="C">
<option>Toate</option>
<option>C1</option>
<option>C2</option>
<option>C3</option>
<option>C4</option>
<option>C5</option>
<option>C6</option>
<option>C7</option>
<option>C8</option>
<option>C9</option>
<option>C10</option>
</select>
</div>
<br/>
<table id="X">
<thead>
</thead>
<tbody>
<tr>
<td>A1,B1,C1</td>
</tr>
<tr>
<td>A1,B1,C2</td>
</tr>
<tr>
<td>A1,B1,C3</td>
</tr>
<tr>
<td>A1,B2,C4</td>
</tr>
<tr>
<td>A1,B2,C5</td>
</tr>
<tr>
<td>A1,B3,C6</td>
</tr>
<tr>
<td>A2,B4,C7</td>
</tr>
<tr>
<td>A2,B5,C8</td>
</tr>
<tr>
<td>A2,B5,C9</td>
</tr>
<tr>
<td>A3,B6,C10</td>
</tr>
</tbody>
</table>
You can simply put more parameters this way.
$("table tbody tr td:contains('A1'):contains('B1'):contains('C1')").css( "text-decoration", "underline" );

Change and Update parameter value when Onchange combobox triggered

I have a problem to change url parameter when event onchange triggered in combobox.
Here is the preview :
My default url like this :
http://reserv_book.php?id=1 the number id is according to row (from database).
When i select in Cart combobox i want to add parameter cart=standard or cart=extra according to combobox value.
So URL update like this :
http://reserv_book.php?id=1&cart=standard
When i select in Caddy combobox i want to add parameter caddy=standard or caddy=extra according to combobox value.
So URL update like this :
http://reserv_book.php?id=1&cart=standard&caddy=standard
Here is my function that called when onChange event in combobox triggered.
function changeValue(type, id) {
var valCart = document.getElementById("cart").value;
var valCaddy = document.getElementById("caddy").value;
if (type == "cart") {
//alert("Cart : "+val+" , "+id);
$("a.book").each(function() {
var link = "reserv_book.php?id="+id+"&caddy="+ valCaddy +"&cart=";
if (valCart == "standard") {
$(this).attr("href", link + 'standard');
} else {
$(this).attr("href", link + 'extra');
}
});
} else {
//alert("Caddy : "+val+" , "+id);
$("a.book").each(function() {
var link = "reserv_book.php?id="+id+"&cart="+ valCart +"&caddy=";
if (valCaddy == "standard") {
$(this).attr("href", link + 'standard');
} else {
$(this).attr("href", link + 'extra');
}
});
}
}
And this is html file in combobox :
<table width="100%" class="ry-table-gold" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<th>No.</th>
<th>Date</th>
<th>Time</th>
<th>Player(s)</th>
<th>Price</th>
<th>Caddy</th>
<th>Cart</th>
<th> </th>
</tr>
<tr>
<td>1</td>
<td>Oct 28 2013</td>
<td>14:50</td>
<td>3</td>
<td>IDR 450,000.0</td>
<td>
<select id="caddy" onchange="changeValue('caddy',1)">
<option value="standard">Standard</option>
<option value="extra">Extra</option>
</select>
</td>
<td>
<select id="cart" onchange="changeValue('cart',1)">
<option value="standard">Standard</option>
<option value="extra">Extra</option>
</select>
</td>
<td>
Book Now
</td>
</tr>
<tr>
<td>2</td>
<td>Oct 10 2013</td>
<td>14:00</td>
<td>3</td>
<td>IDR 700,000.0</td>
<td>
<select id="caddy" onchange="changeValue('caddy',2)">
<option value="standard">Standard</option>
<option value="extra">Extra</option>
</select>
</td>
<td>
<select id="cart" onchange="changeValue('cart',2)">
<option value="standard">Standard</option>
<option value="extra">Extra</option>
</select>
</td>
<td>
Book Now
</td>
</tr>
</tbody>
</table>
Another problem is, if the data cart and caddy in first row changed. It affect to another row.
You need to find closest tr and search for links inside the table row. Since you are using inline handlers you need to pass additional argument.
function changeValue(type, id, element) {
var valCart = $("#cart").val(); //use val to get the value of select.
var valCaddy = $("#caddy").val();
if (type == "cart") {
//alert("Cart : "+val+" , "+id);
$(element).closest("tr").find("a.book").each(function() {
var link = "reserv_book.php?id="+id+"&caddy="+ valCaddy +"&cart=";
if (valCart == "standard") {
$(this).attr("href", link + 'standard');
} else {
$(this).attr("href", link + 'extra');
}
});
} else {
...
//same here
}
}
HTML
<select id="cart" onchange="changeValue('cart',1, this)">
<option value="standard">Standard</option>
<option value="extra">Extra</option>
</select>

Categories

Resources