I have a table row which looks like
the HTML looks like
When the user changes the value of the Name field I pass the "select" to nameDropChanged function. After obtaining a reference to select I want to change the value of Number of Coupons select box. How can I obtain a reference to it using Jquery? Also there will be many such exact rows in the table.
Update : Here is the dummy HTML code and jsfiddle link
<table id="competitors_table" width="100%" style="border-bottom: #000000 solid 1px;">
<tbody>
<tr>
<td>Name:<select name="CompetitorIDs_Setting_[]" onchange="nameDropDownChanged(this);">
<option value="0">N/A</option><optgroup label="Similar Stores"></optgroup>
<optgroup label="Other Stores">
<option value="1">flipkart</option>
<option value="2">bigshoebazaar</option>
<option value="160">presto</option>
<option value="3">fabindia</option>
<option value="4">fashnvia</option>
</td>
<td>
<select name="Position_Setting_[]" onchange="dropDownChanged(this);">
<option value="1000">Top</option>
<option value="1001">Middle</option>
<option value="1002">Bottom</option>
<option value="">Enter Position</option>
</select>
<input type="text" name="PositionNumber_Setting_[]" size="3" style="display: none;">
</td>
<td>Number of Coupons:<select id="numberOfCoupons_Setting_[]"></select></td>
</tr>
</tbody>
</table>
Javascript code
function nameDropDownChanged(select)
{
var selectedIndex = select.selectedIndex;
var WebsiteName = select.options[selectedIndex].innerHTML;
var couponCount = <?php if(!empty($couponCount)){ echo json_encode($couponCount); }?>;
if(Object.keys(couponCount).length > 0)
{
var numberOfCoupons = couponCount[WebsiteName];
var numberOfCouponsDropDown = document.getElementById('numberOfCouponsSelect');
$("#numberOfCouponsSelect").empty();
if(numberOfCoupons > 0)
{
for(var i=1; i <= numberOfCoupons; i++)
{
var option = document.createElement('option');
option.value = i;
option.innerHTML = i;
numberOfCouponsDropDown.appendChild(option);
}
}
else
{
var option = document.createElement('option');
option.value=1;
option.innerHTML = "No Active Coupons";
numberOfCouponsDropDown.appendChild(option);
}
}
}
inside the nameDropChanged function ..
// considering 'parameter' is the variable to be passed as a parameter to nameDropChanged function
$numberSelect = $(parameter).parent().nextAll(':last').children('select');
// $numberSelect is now containing a reference to the numberOfCoupons_Setting_[ select]
You can do something like this
$('#Selector_ID1, #Selector_ID2, #Selector_ID3, ...').change(function() {
var parent = $(this).parents("tr");
var elm = $("td:last-child", parent).children("select");
//Do your operation with last Select Element here.
});
This helps in two ways
You need not to know exact parents and children, but just reverse
track for parent which is TR in first case and then last SELECT in
the parent.
In a single go you can handle multiple rows. You can
also use class selector here.
Related
I have a table in which first row is a label and drodown for selecting number of spaces.
based on the number selected that much number of rows and inside each row another table with input fields will come. everithing is ok in first time.but when i reselect the number from dropdown the number of rows append to the previous one. i want to replace the previous inner tables. how to do this.
this is my html code
<table border="1" style="border-style:dotted" width="100%" id="table_booking">
<tr>
<td>
<label > Number Of Spaces</label>
</td>
<td>
<select id="dropdown" class="" name="spaces" onchange="addForm(this.value)">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
</tr>
<table border="1" style="background-color:gray" width="100%" id="table_form">
</table>
</table>
this is the script
<script type="text/javascript">
function addForm(space)
{ var val=space;
document.getElementById('dropdown').value =val;
var doc=document.getElementById('table_booking');
for(var i=0;i<val;i++)
doc.innerHTML += '<tr><td><table width="100%" id="table_form"><tr><td><form><label>Name </label><input type="text"></form></td></tr></table></td></tr>';
}
</script>
Before appending, just flush the existing innerHTML like
doc.innerHTML = '';
Then append it,
for(var i=0;i<val;i++)
doc.innerHTML += '<tr><td><table width="100%" id="table_form"><tr><td><form><label>Name </label><input type="text"></form></td></tr></table></td></tr>';
Updates: Looking through your comments in other answers, I have devised the following approach,
function addForm(space) {
var val = space;
var doc = document.getElementById('table_booking').getElementsByTagName('tbody')[0];
// Remove nodes whenever we append new nodes to the tbody (RESET)
if (doc.getElementsByTagName('tr').length > 1) {
var len = doc.getElementsByTagName('tr').length;
for (i = (len - 1); i >= 1; i--) {
doc.getElementsByTagName('tr')[i].remove();
}
}
// Based on the value selected, new rows will be appended to the tbody
for (var i = 1; i <= val; i++) {
t = doc;
r = t.insertRow(i);
c = r.insertCell(0);
c.innerHTML = "<form><label>Name </label><input type='text'></form>";
doc.appendChild(r);
}
}
JSFiddle
Hello I have multiple select boxes which will be added dynamically.
I have 4 options under the selection boxes, each color coded. It works fine with one select box. If i have multiple select boxes then the color coding is not working. Please help!
Heres the fiddle
https://jsfiddle.net/p49g8p9h/
THE HTML
<tr>
<td class="tg-7khl">MAV_01</td>
<td class="tg-7khl">Maveric Poster</td>
<td class="tg-7khl">Maveric</td>
<td class="tg-7khl">PRE,VIN,MUK</td>
<td class="tg-7khl">14 Aug 2015</td>
<td class="tg-7khl">
<select id="stat" class="redText" style="padding: 3px; display:block;">
<option class="redText">Yet to start</option>
<option class="orangeText">In Progress</option>
<option class="blueText">Waiting</option>
<option class="greenText">To invoice</option>
</select>
</td>
<td class="tg-7khl red">from 12 Aug 2015</td>
</tr>
You have two issues in your code.
1) You have duplicate IDs for select element. IDs must be unique. You can rather use same class name. and target elements by classname instead.
2) You are using object of get elements in click handler. You should rather use current element context this in handler.
Full Snippet:
var selectele = document.getElementsByClassName('stat');
for(var i=0;i<selectele.length;i++)
selectele[i].onchange = function () {
this.className = this.options[this.selectedIndex].className;
}
}
Working Demo
check this working updated fiddle you have duplicating id so this was not working you can do it with class also
var select = document.getElementById('stat');
select.onchange = function () {
select.className = this.options[this.selectedIndex].className;
}
var select1 = document.getElementById('stat1');
select1.onchange = function () {
select1.className = this.options[this.selectedIndex].className;
}
var select2 = document.getElementById('stat2');
select2.onchange = function () {
select2.className = this.options[this.selectedIndex].className;
}
id should be unique for each elements. Use class redText instead id like following.
var select = document.getElementsByClassName('redText');
for (var i = 0; i < select.length; i++) {
select[i].onchange = function () {
this.className = this.options[this.selectedIndex].className;
}
}
DEMO
You are using same id for multiple elements which is the cause to fail getting all element by id.
change all id to class as shown below -
<select class="stat redText" style="padding: 3px; display:block;">
Use this.className so that it will take only current select box for which value changed
var select = document.getElementsByClassName('stat');
for(var i = 0; i < select.length; i++) {
select[i].onchange = function () {
this.className = this.options[this.selectedIndex].className;
}
}
JSFiddle Demo
I have the below code in my Velocity template:
<tr>
<td>
<input name ="questions" id = "quest" type = "text" value = "$!question.question" size="30" style="border: none" readonly/>
</td>
<td>
<select id="rate" name="rating" **onchange="myFunction()**">
#set ($values = [0..2])
#foreach ($value in $values)
#set ($optValue = $value)
#if ($optValue == 0)
<option value="$optValue" selected>$optValue</option>
#else
<option value="$optValue">$optValue</option>
#end
#end
</select>
</td>
</tr>
In my Javascript i am defining the function myFunction().
function myFunction()
{
var count = document.getElementsByName('rating').length;
var total = 0;
for(x=0;x<count;x++)
{
var formRating = document.getElementsByName('rating')[x].value;
var formWeightage = document.getElementsByName('weightage') [x].value;
total=formRating + formWeightage;
console.log(total);
}
return total;
};
The problem i face here is,
Consider the above velocity generates 5 rows and 5 selected boxes.
When i select first select option value as 1, the js function(myFunction) is called and all the remaining values of the select boxes() are also selected and displayed.
I want to get only the value of the select box i select. How to achieve this?
You could get all options with the selectedattribute like this:
function doSomethingWithSelectedOptions(){
var selectedElements = document.querySelectorAll("option[selected]");
// Iteration over all selected elements
for(var i=0; i<selectedElements.length; i++){
console.log("Selected element: "+selectedElements[i].innerHTML);
}
}
My task here is to change the content in the table whenever the select's options change.
The code below is my solution but I don't think that is good at all. What if when the options have more than 3 options... this might lead me to modify lots of in the if else condition. Thus, if you have others solution, please let me know that.
Might I set id="approve_2" as show default with my edited JSFIDDLE?
Demo
HTML:
<table>
<tr>
<td>
<select id="select_vehicle">
<option value="company_vehicle">Company Vehicle</option>
<option value="hiring_vehicle">Hiring Vehicle</option>
<option value="taxi">Taxi</option>
</select>
</td>
</tr>
<tr id="company_vehicle">
<td>Company Vehicle</td>
</tr>
<tr id="hiring_vehicle">
<td>Hiring Vehicle</td>
</tr>
<tr id="taxi">
<td>Taxi</td>
</tr>
</table>
Javascript:
var select_vehicle = $("#select_vehicle");
// Set selected item
var set_selected_item = $(select_vehicle).val("company_vehicle");
// Hide options "Hiring Vehicle" & "Taxi"
var company_vehicle = $("#company_vehicle"); // Get id "Company Vehicle"
var hiring_vehicle = $("#hiring_vehicle"); // Get id "Hiring Vehicle"
hiring_vehicle.hide();
var taxi = $("#taxi"); // Get id "Taxi"
taxi.hide();
$(select_vehicle).on('change', function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
if (valueSelected == "company_vehicle") {
company_vehicle.show();
hiring_vehicle.hide();
taxi.hide();
} else if (valueSelected == "hiring_vehicle") {
company_vehicle.hide();
hiring_vehicle.show();
taxi.hide();
} else {
company_vehicle.hide();
hiring_vehicle.hide();
taxi.show();
}
});
JSFIDDLE: http://jsfiddle.net/huydq91/7us66/3/
You can shorten your code without repetition like this:
$('table tr:gt(0)').hide();
$('#select_vehicle').change(function() {
var val = $(this).val();
$('#'+val).show().siblings('tr').not(':first').hide();
}).change();
Updated Fiddle
Following this question - Extending Clone Table Rows functionality - changing row ID
The code - http://jsfiddle.net/EwQUW/58/
I want to update the attr. Please check the code and I have included comments to see what I am talking about.
EDIT
<table id="table">
<tbody>
<tr>
<td>
<select name="make[]" id="make" onchange="change(this,'model')">
<option value="" selected=“selected”> Please Select </option>
<option value=Ford> Ford</option>
<option value=Nissan> Nissan</option>
<option value=Volvo> Volvo</option>
<option value=BMW> BMW</option>
</select>
</td>
<td>
<select name="model[]" id="model" onchange="change(this,'make')">
<option value="" selected=“selected”> Please Select </option>
<option value=Ford> Fiesta</option>
<option value=Nissan> Mirca</option>
<option value=Volvo> s60</option>
<option value=BMW> M3</option>
</select>
</td>
<td>
<input id="country" name="country[]"/>
</td>
<td>
<input id="city" name="city[]" />
</td>
</tr>
</tbody>
</table>
<button id="add">Add</button>
Javascript
function change(fld,id) {
var opt = fld.selectedIndex;
if (fld[opt].value != ' ') {
var sel = document.getElementById(id);
for (var i = sel.options.length -1; i > -1; i--) {
if (fld[opt].value == sel[i].value) sel[i].selected = true;
}
}
}
When I add a new row, I want the ID, NAME and onchange to be updated with a count or length as you put.
As ID are updated and onchange to id=make to id=make2 so the onchange still works
EDIT AGAIN
Actually names will be an array. So only IDS and Onchange needs updating depending on number of rows
The first means I've come up with is:
function change(fld, id) {
var opt = fld.selectedIndex;
if (fld[opt].value != ' ') {
var sel = document.getElementById(id);
for (var i = sel.options.length - 1; i > -1; i--) {
if (fld[opt].value == sel[i].value) sel[i].selected = true;
}
}
}
$('select').change( // moving away from intrusive in-line JavaScript
function() {
var changeTarget; // used to determine which select to change
if (this.id == 'make') {
changeTarget = 'model';
}
else {
changeTarget = 'make';
}
change(this,changeTarget);
});
$('#add').click(
function() {
$('#table tbody tr:last').clone(true).appendTo($('#table')).find('input,select').each(
function() {
var attr = this.id.replace(/\d/, ''); // gets the text of the id attribute
var length = $('#table tbody tr').length; // finds what number the new attributes should be
if ($(this).is('input')){ // select elements don't need their name to be changed
$(this).attr({
'id': attr + length,
'name': attr + length
});
}
else if ($(this).is('select')){
$(this).attr('id',attr + length);
}
});
});
JS Fiddle demo.
Edited to remove the hard-coded 'make'/'model' choice in the select change() event-handler to the following:
$('select').change(
function() {
var changeTarget = $(this)
.closest('tr')
.find($('select'))
.not($(this))
.attr('id');
change(this,changeTarget);
});
JS Fiddle demo.