Is there any way to find the text content of a td and then make that text the first line or option in a select drop down?
<table class="options">
<tbody>
<tr>
<td><b>Colour:</b></td>
<td>
<select>
<option selected="" value="">Select:</option>
<option value="1">Black</option>
<option value="2">White</option>
</select>
</td>
</tr>
</tbody>
</table>
The first td content (Colour:) needs to go in place of the first option (Select:), basically. I don't have full control over the select list myself so I'm having to try doing this dynamically. Trying to save on space. Ideally I'd like to remove the td as well after moving the content.
Just get the caption from the previous cell and put it to the first option. Check it out here: https://jsfiddle.net/w07vg0ef/
Try this:
// do for all selects on the page
$('select').each(function (index, element) {
// store the select
var select = $(element)
// get the caption from the previous cell
var caption = select.parent().prev('td').text()
// put the caption to the first option
select.find('option').first().html(caption)
})
$('select').prepend('<option selected=selected>'+$('select').closest('tr').find('td:nth-child(1)').text()+'</option>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="options">
<tbody>
<tr>
<td><b>Colour:</b>
</td>
<td>
<select>
<option selected="" value="">Select:</option>
<option value="1">Black</option>
<option value="2">White</option>
</select>
</td>
</tr>
</tbody>
</table>
try this
If you're looking to do it only by JavaScript then take a look at this:
Add option as the first value but as a new value:
var getColor = document.getElementsByTagName("td")[0];
var selectedColor = getColor.getElementsByTagName("b")[0].innerHTML;
var select = document.getElementsByTagName("select")[0];
var option = document.createElement("option");
option.text = selectedColor;
select.add(option, select[0]);
<table class="options">
<tbody>
<tr>
<td><b>Color:</b></td>
<td>
<select>
<option selected="" value="">Select:</option>
<option value="1">Black</option>
<option value="2">White</option>
</select>
</td>
</tr>
</tbody>
</table>
Add option as a replace value of the current first value:
var getColor = document.getElementsByTagName("td")[0];
var selectedColor = getColor.getElementsByTagName("b")[0].innerHTML;
var select = document.getElementsByTagName("select")[0];
var option = select.options[0];
option.innerHTML = selectedColor;
<table class="options">
<tbody>
<tr>
<td><b>Color:</b></td>
<td>
<select>
<option selected="" value="">Select:</option>
<option value="1">Black</option>
<option value="2">White</option>
</select>
</td>
</tr>
</tbody>
</table>
Here's a quick pure javascript solution. If possible, I would add a class to the TD so you could target it better or something like that.
var firstTD = document.getElementsByClassName('options')[0].getElementsByTagName('td')[0];
var text = firstTD.innerHTML;
var selectBox = document.getElementsByTagName('select')[0];
var option = document.createElement('option');
option.setAttribute('value', '');
option.innerHTML = text;
selectBoxFirstChild = document.getElementsByTagName('select')[0].children[0];
selectBox.insertBefore(option, selectBoxFirstChild);
Related
i want clone previous row's selected option value to the new raw while cloning new row.
$("#btnAdd").on("click", function() {
var $tableBody = $('#tbl').find("tbody"),
$trLast = $tableBody.find("tr:last"),
$trNew = $trLast.clone();
$trLast.after($trNew);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='tbl'>
<tbody>
<tr>
<td>
<p>Cell3</p>
</td>
<td>
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</select>
</td>
</tr>
</tbody>
</table>
<input type="button" id="btnAdd" value="Add New Row"></button>
I'm unable to copy the last row selected drop down list value, any solution or cloning is not the way to do it?
You need to set the select elements value as .clone() intentionally doesn't copy dynamic state of textarea and select
Note: For performance reasons, the dynamic state of certain form elements (e.g., user data typed into textarea and user selections made to a select) is not copied to the cloned elements. When cloning input elements, the dynamic state of the element (e.g., user data typed into text inputs and user selections made to a checkbox) is retained in the cloned elements.
Use
$trNew.find('select').val($trLast.find('select').val());
$("#btnAdd").on("click", function() {
var $tableBody = $('#tbl').find("tbody"),
$trLast = $tableBody.find("tr:last"),
$trNew = $trLast.clone();
//Set updated value
$trNew.find('select').val($trLast.find('select').val())
$trLast.after($trNew);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='tbl'>
<tbody>
<tr>
<td>
<p>Cell3</p>
</td>
<td>
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</select>
</td>
</tr>
</tbody>
</table>
<input type="button" id="btnAdd" value="Add New Row"></button>
If case tr has multiple select, Value's can be fetched based on index of the element.
$trNew.find('select').val(function(index, value) {
return $trLast.find('select').eq(index).val();
});
$("#btnAdd").on("click", function() {
var $tableBody = $('#tbl').find("tbody"),
$trLast = $tableBody.find("tr:last"),
$trNew = $trLast.clone();
$trNew.find('select').val(function(index, value) {
return $trLast.find('select').eq(index).val();
});
$trLast.after($trNew);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='tbl'>
<tbody>
<tr>
<td>
<p>Cell3</p>
</td>
<td>
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</select>
</td>
<td>
<select>
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
</td>
</tr>
</tbody>
</table>
<input type="button" id="btnAdd" value="Add New Row"></button>
You can modify $trNew elements before appending it.
In your case:
$('select', $trNew).val($('select', $trLast).val());
My solution was
$trNew.find('.bootstrap-select').next().remove();
Currently I have this setting.
My page loads with 2 drop-downs aligned adjacent and an ADD button.
The ADD button adds a drop-down in the next row using the function addRow().
The function is probably the worst implementation though.
a) I want ADD button to add 2 similar drop-downs aligned adjacent as in the page initially, to the next row. (right now the code only adds 1 drop-down in the next row)
b) is there any way I can put my ADD button to be below the drop-downs I have instead of being next to the first row of drop-downs?
Below is the code
<div class="container">
<table>
<tr>
<td>
<select id="soflow">
<!-- This method is nice because it doesn't require extra div tags, but it also doesn't retain the style across all browsers. -->
<option>Select an Option</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
<select id="soflow">
<!-- This method is nice because it doesn't require extra div tags, but it also doesn't retain the style across all browsers. -->
<option>Select an Option</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
<button class = "button" type="button" onClick ="addRow(this)">Add</button></td>
</tr>
</table>
</div>
<script>
function addRow(btn) {
var parentRow = btn.parentNode.parentNode;
var table = parentRow.parentNode;
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
//var element2 = document.createElement("input");
var element2 = document.createElement("select");
element2.setAttribute("id", "soflow")
//element2.type = "select";
var option1 = document.createElement("option");
option1.innerHTML = "Option1";
option1.value = "1";
element2.add(option1, null);
var option2 = document.createElement("option");
option2.innerHTML = "Option2";
option2.value = "2";
element2.add(option2, null);
cell1.appendChild(element2);
}
</script>
Thank you for any help.
Give id to your <tr> to be cloned and to the table. Then use cloneNode() to clone the row and append it to the table.
<div class="container">
<table id="myTable">
<tr id="initialRow" class="select_row">
<td>
<select id="soflow" class="select1">
<!-- This method is nice because it doesn't require extra div tags, but it also doesn't retain the style across all browsers. -->
<option>Select an Option</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
<select id="soflow" class="select2">
<!-- This method is nice because it doesn't require extra div tags, but it also doesn't retain the style across all browsers. -->
<option>Select an Option</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
</td>
</tr>
</table>
<button class = "button" type="button" onClick ="addRow()">Add</button>
<button class = "button" type="button" onClick ="getValues()">Print values</button>
</div>
<script>
const table = document.querySelector('#myTable');
const rowToDuplicate = document.querySelector('#initialRow');
function addRow() {
var duplicate = rowToDuplicate.cloneNode(true);
duplicate.removeAttribute('id'); table.appendChild(duplicate);
}
function getValues() {
const rows = document.querySelectorAll('.select_row');
rows.forEach((row, i) => {
console.log(`row ${i}: select1 `, row.querySelector('.select1').value); console.log(`row ${i}: select2 `,row.querySelector('.select2').value);
})
}
</script>
You have two IDs which have the same name. Change the ID property to have different names for both select elements like <select id="soflow1"> && <select id="soflow2"> and refer to each element as soflow1 or soflow2 in your Javascript. Your JavaScript is referencing two ID elements and causing two dropdowns to open with one call.
IDs should be unique to only one element.
To use the same style across those dropdown elements add a class property which is the same to both select elements like <select id="soflow1" class="myDropdownClass"> && <select id="soflow2" class="myDropdownClass"> and create CSS for .myDropdownClass { //some style }
To put the button underneath the select elements you could do this in your table...
<table>
<tr>
<td><select id="soflow1" class="myDropdownClass" ... /></td>
<td><select id="soflow2" class="myDropdownClass" ... /></td>
</tr>
<tr>
<td colspan="2"><button>text</button></td>
</tr>
</table>
I like to add the event listener to the table since the click will bubble up the dom tree. Then check to see that it was an element with the class "add" that called the event. If it is then clone the row node of the table and append it to the table body. I also placed the button in the table footer so it always stays at the bottom. Hope this helps.
This method also allows you to change the structure of the table without having to rewrite the javascript to correctly climb the dom tree. Added a remove row button just for S&G.
In similar fashion to get the values without having ids on every select element you could use the elements index from a list of solflow elements as a unique identifier and the value.
Since you are creating dynamic elements by cloning the row, either the event listeners for the solflow need to be added to the new select elements or the table can handle the change event in which case you add the change handler once and the solflow change bubbles up no matter when the element was added. In similar fashion a submit button can be created with the table click handler grabbing all the values from the solflow elements in the table and indexing them to the number of solflow elements as either a key value store or as an array of solflow values matching the order in which the elements appear.
<table>
<tbody>
<tr>
<td>
<select class="solflow">
<option>Select an Option</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
<select class="solflow">
<option>Select an Option</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<button class="button add" type="button">Add</button>
<button class="button remove" type="button">Remove</button>
</td>
</tr>
</tfoot>
</table>
<script>
function tableClickHandler(e) {
if (e.target.classList.contains('add')) {
let tbody = this.querySelector('tbody');
let row = tbody.querySelector('tr');
tbody.appendChild( row.cloneNode(true) );
}
if (e.target.classList.contains('remove')) {
var tbody = this.querySelector('tbody');
var row = tbody.querySelectorAll('tr');
if (row.length > 1) {
tbody.removeChild(row[row.length-1]);
}
}
}
function tableChangeHandler(e) {
if (e.target.classList.contains('solflow')) {
let solflows = this.querySelectorAll('.solflow');
let solflow = e.target;
let index = -1;
solflows.forEach(function(el, ind){
if (el === solflow) { index = ind }
});
console.log(index, solflow.value);
}
}
document.querySelector('table').addEventListener('click', tableClickHandler);
document.querySelector('table').addEventListener('change', tableChangeHandler);
</script>
You can use a for loop to loop twice and create two selects. You should move the button outside of the table if you want it to always be under the selects (both added and initial ones) while adding new rows to the table for the selects.
Also, you can not have more than one element with one id. You initially have 2 elements with the id "soflow" and are going to add more when the Add button is clicked.
To count how many selects have been added, you just need a global variable that increase by one each time the for loop inside the function is run.
<div class="container">
<table id="selectTable">
<tr>
<td>
<select id="soflow">
<!-- This method is nice because it doesn't require extra div tags, but it also doesn't retain the style across all browsers. -->
<option>Select an Option</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
<select id="soflow2">
<!-- This method is nice because it doesn't require extra div tags, but it also doesn't retain the style across all browsers. -->
<option>Select an Option</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
<br/>
</td>
</tr>
</table>
<button class = "button" type="button" onClick ="addRow(this)">Add</button>
</div>
<script>
var addedSelects = 0;//total number of dropdowns added
function addRow(btn) {
var table = document.getElementById('selectTable');
var soflow = document.getElementById("soflow2");
var rowCount = table.rows.length;
var row = document.createElement('tr');
table.appendChild(row);
//var element2 = document.createElement("input");
var td = document.createElement('td');
row.appendChild(td);
for(let i = 0; i < 2; i++){
var element2 = document.createElement("select");
//element2.setAttribute("id", "soflow"+(i+1))
//element2.type = "select";
var option1 = document.createElement("option");
option1.innerHTML = "Option1";
option1.value = "1";
element2.add(option1, null);
var option2 = document.createElement("option");
option2.innerHTML = "Option2";
option2.value = "2";
element2.add(option2, null);
td.appendChild(element2);
addedSelects++;
}
}
</script>
This should do the trick
function addRow() {
//Select the table
var table = document.getElementsByTagName('table')[0];
//Append a row
table.innerHTML = table.innerHTML + '<tr>\
<td>\
<select>\
<option>Select an Option</option>\
<option>Option 1</option>\
<option>Option 2</option>\
</select>\
<select>\
<option>Select an Option</option>\
<option>Option 1</option>\
<option>Option 2</option>\
</select>\
</td>\
</tr>';
}
<div class="container">
<table>
<tr>
<td>
<select>
<!-- This method is nice because it doesn't require extra div tags, but it also doesn't retain the style across all browsers. -->
<option>Select an Option</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
<select>
<!-- This method is nice because it doesn't require extra div tags, but it also doesn't retain the style across all browsers. -->
<option>Select an Option</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
</td>
</tr>
</table>
<button class = "button" type="button" onClick ="addRow()">Add</button>
</div>
The ADD button always stays at the bottom because I moved it out of the table. I removed the id on the select tags, duplicate ids will give you errors, try using document.getElementsByTagName('select')[x] selector and use 0 (where x) to get the first drop down, 1 to get the second... I also just used text instead of creating the elements via JS because their much easier to read, create, and modify in my opinion. If you have any questions just ask.
In a table, how to loop through all dropdowns text & id in a table's col, and save them in array. So that I can disable previously selected options
Once an option is selected, I do not want it to be available again. How to check the selected text of previously selected options in the table set that option to disabled on all other dropdowns in the page.
(this question is different from other SO questions since its disabling after checking both selected text & selected value inside a table and needs to target the dropdown in the specified column)
var allSelectedValuesArray = array();
allSelectedValuesArray.push($("#tblVersions .Model option:selected").text());
var rows = $("body tr",$("#tblVersions")).map(function() {
return [$("td:eq(0) input:checkbox:checked",this).map(function() {
return this.innerHTML;
}).get()];
}).get();
<table id="tblversions">
<tbody id="body">
<tr class="rowcss">
<td>
<select class="Manufacturer">
<option value="1">Toyota </option>
<option value="2">Honda</option>
<option value="3">BMW</option>
</select>
</td>
<td>
<select class="Model">
<!-- If user selects Honda my Ajax populates Honda Models/Cars like below-->
<option value="1">Accord</option>
<option value="2">Toyota 2</option>
<option value="3">Honda 3</option>
</select>
</td>
</tr>
<tr class="rowcss">
<td>
<select class="Manufacturer">
<option value="1">Toyota </option>
<option value="2">Honda</option>
<option value="3">BMW</option>
</select>
</td>
<td>
<select class="Model">
<!-- If user selects BMW my Ajax populates BMW models Cars like below-->
<option value="1">X5 Suv</option>
<option value="2">318 series Cheap</option>
<option value="3">540i too expensive!</option>
</select>
</td>
</tr>
</tbody>
</table>
I didn't understand the second part of your question, but if you want to get text and values for all dropdowns you could do something like this.
// Called when any of the dropdowns change
( "#tblversions" ).change(function() {
var allSelectedValuesArray = [];
// Search for all selects in the #tblversions
$("#tblversions select option:selected").each(function() {
// for each one, push it into the array
allSelectedValuesArray.push({text:$(this).text(), value:this.value});
});
});
This creates an array of objects in the format {text:"sometext",value:"somevalue"} for each of the dropdowns in the table.
I'm quite new to web-development, and have a problem which I can't solve. I have a table which has 3 items: car, color and motor type. Table example is here:
<table>
<tr>
<th>Car</th>
<th>Color</th>
<th>Motor type</th>
</tr>
<tr>
<td>Mercedes</td>
<td>Blue</td>
<td>Petrol</td>
</tr>
<tr>
<td>Mercedes</td>
<td>Red</td>
<td>Diesel</td>
</tr>
<tr>
<td>VW</td>
<td>Blue</td>
<td>Hybrid</td>
</tr>
<tr>
<td>VW</td>
<td>Yellow</td>
<td>Diesel</td>
</tr>
<tr>
<td>Alfa Romeo</td>
<td>Red</td>
<td>Diesel</td>
</tr>
<tr>
<td>Alfa Romeo</td>
<td>Green</td>
<td>Petrol</td>
</tr>
</table>
I want to add 3 dropdowns with checkboxes to filter selected items, one for car, one for color and one for motor type. Items in dropdown should be filled dynamically, based on the items in the table.
For example:
First dropdown will be consisted of 3 checkboxes: Mercedes, VW and Alfa Romeo
Second will have Blue, Red, Yellow and Green
and third one will have Petrol, Diesel and Hybrid
Also, when I select Mercedes, for example, Yellow and Green color should be hidden in second dropdown, and Hybrid should be hidden in third dropdown, since there aren't any Yellow/Green/Hybrid Mercedes.
Can someone please help with writing the appropriate JavaScript/jQuery file?
Thank you a lot.
i am write in php, you can modify this
this is only idea for you
//fetch from database
<input type="checkbox" value="Mercedes" onclick="car_fun(this.value)"> Mercedes
<input type="checkbox" value="VW" onclick="car_fun(this.value)"> VW
<input type="checkbox" value="Alfa Romeo" onclick="car_fun(this.value)"> Alfa Romeo
<select id="color">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Orange">Orange</option>
<option value="Blue">Blue</option>
</select>
<select id="type">
<option value="Petrol">Petrol</option>
<option value="Diesel">Diesel</option>
<option value="Hybrid">Hybrid</option>
</select>
<script>
function car_fun(car)
{
$.ajax({
url:// your url,
data:"$car_name="+car,
type:"post",
dataType:"json",
success:function(result)
{
$("#color").html(result.color);
$("#type").html(result.type);
}
});
}
</script>
fetch the value from database using the passed car value
First, set onchange to the checkboxs to track with is selected.
Then, in the onchange event, use the index of the items you want to hide items of dropdownlist:
document.getElementById('your dropdownlist id').options[index].style.display = 'none';
this is a example.
function changeItemsOfDropDown() {
var drop = document.getElementById("optionDrop");
for (var i = 0; i < drop.options.length; i++) {
if (drop.options[i].value == "Green" || drop.options[i].value == "Blue") {
drop.options[i].style.display = "none";
}
}
}
function fillItemsToDropDown() {
var drop = document.getElementById("optionDrop");
for(var i = 0; i < 5; i++) {
var option = document.createElement('option');
option.text = option.value = "test" + i;
drop.add(option);
}
}
<input type="checkbox" onchange="changeItemsOfDropDown()" >Click to hide items of Green and Blue</input>
<button type="checkbox" onchange="fillItemsToDropDown()" >Fill new options to dropdownlist</button>
<br>
<select id="optionDrop">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Orange">Orange</option>
<option value="Blue">Blue</option>
</select>
I have got a table with a select option in it. After the select changes, the td's innerHTML should change to the selected value so the select disappears.
<table>
<tr>
<td>
<select onchange="update(param1, param2)">
<option value="Value 1">Value 1</option>
<option value="Value 1">Value 2</option>
</select>
</td>
</tr>
</table>
So, when I select Value 2, the table should look like this:
<table>
<tr>
<td>
Value 2
</td>
</tr>
</table>
How do I do this. I've tried things like parentNode, parent()..
It has to be javascript or jQuery.
function update(id, row) {
var val = document.activeElement.value;
var id = id;
var row = row;
if (val != '') {
$.post('../inc/helikopter_beheer.php', {val: val, id: id, row: row}, function(data) {});
$.post('../inc/gereedstelling_get_info.php', {id: id, rij: row}, function(data) {
var result = data.split(",");
// this.parents('id').innerHTML = result;
$(this).closest("td").html(result[0]);
alert(result[0]);
});
};
}
This is what I got. It's getting some data out of my database, turns it into result and i have to get result in my td instead of the select.
JQuery function that accomplishes it (once you've given your select element an id of mySelect):
$('#mySelect').on('change', function () {
var val = $(this).val();
$(this).parent().html(val);
});
JS Fiddle Demo
<table>
<tr>
<td>
<select id="wdm_select">
<option value="Value 1">Value 1</option>
<option value="Value 2">Value 2</option>
<option value="Value 3">Value 3</option>
</select>
</td>
</tr>
</table>
<script>
$(document).ready(function() {
$("#wdm_select").on("change",function() {
var selected_val = $(this).val();
$(this).parent().html( selected_val );
})
})
</script>
here is demo
$(document).on('change','#foo',function(){
$(this).parent('td').html($(this).val());
$(this).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<select id="foo">
<option value="">--Select--</option>
<option value="Value 1">Value 1</option>
<option value="Value 2">Value 2</option>
</select>
</td>
</tr>
</table>