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
Related
Here is the setting. I have two drop-downs adjacent to each other on my initial page. The values in the 2nd drop down depend on the value from the 1st drop down. This works fine.
I have an Add button which duplicates the row of drop-downs i.e. adds 2 adjacent drop-downs below the previous ones.
The addition of drop-downs work fine. However if I have a value selected in my initial drop-down and there is a respective value loaded in 2nd drop-down(dependent on the value from first), that same value is duplicated in the newly added drop-down.
Moreover, the newly added drop-downs are not responsive i.e. a change in left drop-down doesnt change the value in the right drop-down. (The responsiveness is only in the initially added drop-downs)
Maybe I havent used the best javascript practices, forgive me for I am very new at this.
Any feedback is welcomed. Thank you.
Here is the code:
<div class="container">
<table id="myTable">
<tr id="initialRow" class="select_row">
<td>
<select id= "select1" class = "select1">
<option>Select an option</option>
<option>yes</option>
<option>no</option>
</select>
<select id = 'select2' class = "select2">
</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>
<script>
(function() {
//setup an object fully of arrays
//alternativly it could be something like
//{"yes":[{value:sweet, text:Sweet}.....]}
//so you could set the label of the option tag something different than the name
var bOptions = {
"yes": ["sweet", "wohoo", "yay"],
"no": ["you suck!", "common son"]
};
var A = document.getElementById('select1');
var B = document.getElementById('select2');
//on change is a good event for this because you are guarenteed the value is different
A.onchange = function() {
//clear out B
B.length = 0;
//get the selected value from A
var _val = this.options[this.selectedIndex].value;
//loop through bOption at the selected value
for (var i in bOptions[_val]) {
//create option tag
var op = document.createElement('option');
//set its value
op.value = bOptions[_val][i];
//set the display label
op.text = bOptions[_val][i];
//append it to B
B.appendChild(op);
}
};
//fire this to update B on load
A.onchange();
})();
</script>
Few things:
The code in the script tag runs once. That means that you init your selects once. Those selects you add dynamically are not initialized and do not react on the onchange event.
Your clone was not sufficient. You need to clone the clean row and then keep cloning that.
You depend too much on the ids. Once you start dealing with the new dynamic rows those ids are a pain.
I did a quick fix that should get you going. Let me know if this helps.
<div class="container">
<table id="myTable">
<tr id="initialRow" class="select_row">
<td>
<select class="select1">
<option>Select an option</option>
<option>yes</option>
<option>no</option>
</select>
<select class="select2"></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.getElementById('myTable');
const initialRow = document.getElementById('initialRow');
const rowToDuplicate = initialRow.cloneNode(true);
function addRow() {
let duplicate = rowToDuplicate.cloneNode(true);
let select1 = duplicate.lastElementChild.firstElementChild
let select2 = duplicate.lastElementChild.lastElementChild
select1.setAttribute('id', 'select1-' + table.children.length)
select2.setAttribute('id', 'select2-' + table.children.length)
table.appendChild(duplicate);
initSelects(select1, select2);
}
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);
})
}
function initSelects(a, b) {
var bOptions = {
"yes": ["sweet", "wohoo", "yay"],
"no": ["you suck!", "common son"]
};
a.onchange = function () {
//clear out B
b.length = 0;
//get the selected value from A
var _val = this.options[this.selectedIndex].value;
//loop through bOption at the selected value
for (var i in bOptions[_val]) {
//create option tag
var op = document.createElement('option');
//set its value
op.value = bOptions[_val][i];
//set the display label
op.text = bOptions[_val][i];
//append it to B
b.appendChild(op);
}
}
}
initSelects(
initialRow.lastElementChild.firstElementChild,
initialRow.lastElementChild.lastElementChild
);
</script>
I have some code that I want to insert or replace with a desired set of code if it is blank. Any direction in Javascript or jQuery?
If html code equals this:
<td id="Display1234"></td>
change to:
<td id="Display1234">
<select name="ShippingSpeedChoice" onchange="RecalcShipping(this);" style="">
<option value="101" selected="">Free</option>
</select>
</td>
Try using the following for a pure JavaScript solution:
var td = document.getElementById('Display1234');
if (td.innerHTML.trim() == ""){
// Creating the select element
var select = document.createElement('select');
select.setAttribute('name', 'ShippingSpeedChoice');
select.setAttribute('onchange', 'RecalcShipping(this);');
select.setAttribute('style', '');
// Creating the option element
var option = document.createElement('option');
option.innerText = "Free";
option.setAttribute('value', '101');
option.setAttribute('selected', '');
// Appending elements to td element
select.appendChild(option);
td.appendChild(select);
}
<table>
<td id="Display1234"></td>
</table>
You would need to start by getting all the elements on the page (as I'm assuming you don't know which ones are empty).
// need to use Array.prototype.slice because getElementsByTagName
// returns an HTMLCollection and not an Array
var allElementsArray = Array.prototype.slice.call(document.body.getElementsByTagName('*'));
var emptyElements = allElementsArray.filter(function(element) {
return !element.innerHTML; // returns true for all empty elements
});
I don't know what data to insert but you can then loop through the emptyElements array;
emptyElements.forEach(function(element) {
element.innerHTML = 'some content or HTML';
});
$('#Display1234').html('your html');
// if the div is empty
if($("#Display1234").html()===""){
// create a a <select> element
var $sel = $('<select name="ShippingSpeedChoice" onchange="RecalcShipping(this);" style="">');
// add an option to the select element
$sel.append('<option value="101" selected="">Free</option>');
// add the select element to the div.
$sel.appendTo("#Display1234");
}
window.addEventListener("DOMContentLoaded", function(){
var theCell = document.getElementById("Display1234");
if(theCell.textContent.trim() === ""){
theCell.innerHTML = '<select name="ShippingSpeedChoice" onchange="RecalcShipping(this);" style=""> <option value="101" selected="">Free</option></select>'
}
});
<table>
<tr>
<td id="Display1234"></td>
<td id="other1">something</td>
<td id="other2">something else</td>
</tr>
</table>
My html table have many rows.One checkbox and one combo box have contained per each row. When I select combo box and get one value then disable checkbox for relative row according to check combo box value.Here is my javascript method
function check(cbo) {
var chx = document.getElementsByTagName('input');
for ( var i = 0; i < chx.length; i++) {
if (chx[i].type == 'checkbox') {
chx[i].disabled = (cbo.value == 'D') ? true : false;
}
}
}
My requirement is when I select combo box and disable enable checkbox for each row.Please share me something.
Generate a dynamic id (number) and append id with your select and checkbox, as following:
<table width="100%" border="1">
<tr>
<td>Row - 1</td>
<td>
<select id="select1"
onchange="checkTheCheckbox('select1', 'check1');">
<option value="false" selected="true">Default</option>
<option value="true">Check</option>
<option value="false">Uncheck</option>
</select>
</td>
<td>
<input type="checkbox" name="check1" id="check1" />
</td>
</tr>
<tr>
<td>Row - 2</td>
<td>
<select id="select2"
onchange="checkTheCheckbox('select2', 'check2');">
<option value="true" selected="true">Default</option>
<option value="true">Check</option>
<option value="false">Uncheck</option>
</select>
</td>
<td>
<input type="checkbox" name="check2" id="check2" checked />
</td>
</tr>
</table>
Add following javascript method:
function checkTheCheckbox(selectId, checkId){
var ddl = document.getElementById(selectId);
for(var i= 0; i < ddl.length; i++){
if(ddl[i].selected){
var status = ddl[i].value === 'true' ? true : false;
document.getElementById(checkId).checked = status;
}
}
}
Working example: http://jsfiddle.net/gRAb6/
Using an object's parentNode, you can find a shared parent of both the checkbox and the combo box (probably the tr table-row element), and then select within that row for the element you want. Something like:
function check(cbo) {
var parent = cbo.parentNode;
var chx = parent.getElementByTagName('input');
...
}
it may make things a lot simpler for you to use some classes to make selection easier as well. For instance, giving all the checkboxes that you want to be able to be disabled the class of "checkbox_will_disable", say, will allow you to use the document.getElementsByClassName function, which means you don't need the if chx[i].type == "checkbox" any more.
the end function could become something like:
function check(cbo) {
var parent = cbo.parentNode;
var chx = parent.getElementByClassName('checkbox_will_disable');
for (var i=0; i < chx.length; i++) {
chx[i].disabled = (cbo.value == 'D') ? true : false;
}
}
if the parentNode of the cbo isn't far enough up the chain (say it's a td rather than the tr or something) you can keep on using it until you're far enough up:
var parent = cbo.parentNode.parentNode;
say. There are also more elegant ways to do these kinds of things, using jQuery, for instance. And if it becomes complex enough, you may find it easier switching to a javascript framework such as knockoutjs.
Good luck!
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.
I want to use the value of a HTML dropdown box and create that number of input boxes underneath. I'm hoping I can achieve this on the fly. Also if the value changes it should add or remove appropriately.
What programming language would I need to do this in? I'm using PHP for the overall website.
Here is an example that uses jQuery to achieve your goals:
Assume you have following html:
<div>
<select id="input_count">
<option value="1">1 input</option>
<option value="2">2 inputs</option>
<option value="3">3 inputs</option>
</select>
<div>
<div id="inputs"> </div>
And this is the js code for your task:
$('#input_count').change(function() {
var selectObj = $(this);
var selectedOption = selectObj.find(":selected");
var selectedValue = selectedOption.val();
var targetDiv = $("#inputs");
targetDiv.html("");
for(var i = 0; i < selectedValue; i++) {
targetDiv.append($("<input />"));
}
});
You can simplify this code as follows:
$('#input_count').change(function() {
var selectedValue = $(this).val();
var targetDiv = $("#inputs").html("");
for(var i = 0; i < selectedValue; i++) {
targetDiv.append($("<input />"));
}
});
Here is a working fiddle example: http://jsfiddle.net/melih/VnRBm/
You can read more about jQuery: http://jquery.com/
I would go for jQuery.
To start with look at change(), empty() and append()
http://api.jquery.com/change/
http://api.jquery.com/empty/
http://api.jquery.com/append/
Doing it in javascript is quite easy. Assuming you've got a number and an html element where to insert. You can obtain the parent html element by using document.getElementById or other similar methods. The method assumes the only children of the parentElement is going to be these input boxes. Here's some sample code:
function addInput = function( number, parentElement ) {
// clear all previous children
parentElement.innerHtml = "";
for (var i = 0; i < number; i++) {
var inputEl = document.createElement('input');
inputEl['type'] = 'text';
// set other styles here
parentElement.appendChild(inputEl);
}
}
for the select change event, look here: javascript select input event
you would most likely use javascript(which is what jquery is), here is an example to show you how it can be done to get you on your way
<select name="s" onchange="addTxtInputs(this)" onkeyup="addTxtInputs(this)">
<option value="0">Add</option>
<option value="1">1</option>
<option value="3">3</option>
<option value="7">7</option>
</select>
<div id="inputPlaceHolder"></div>
javascript to dynamically create a selected number of inputs on the fly, based on Mutahhir answer
<script>
function addTxtInputs(o){
var n = o.value; // holds the value from the selected option (dropdown)
var p = document.getElementById("inputPlaceHolder"); // this is to get the placeholder element
p.innerHTML = ""; // clears the contents of the place holder each time the select option is chosen.
// loop to create the number of inputs based apon `n`(selected value)
for (var i=0; i < n; i++) {
var odiv = document.createElement("div"); //create a div so each input can have there own line
var inpt = document.createElement("input");
inpt['type'] = "text"; // the input type is text
inpt['id'] = "someInputId_" + i; // set a id for optional reference
inpt['name'] = "someInputName_" + i; // an unique name for each of the inputs
odiv.appendChild(inpt); // append the each input to a div
p.appendChild(odiv); // append the div and inputs to the placeholder (inputPlaceHolder)
}
}
</script>