Find the row index when dropdownlist value changed - javascript

I have an HTML Table with dropdownlist on every row. I want everytime I change the value of the dropdownlist, the background of that row be changed to indicate that there is something changed on the dropdownlist.
Here is the code:
<table id="table1">
<tr>
<td>Value</td>
<td>
<Select onchange="myFunction(this)">
<option value="1">1</option>
<option value='2">2</option></select>
</td>
</tr>
</table>
<script type="text/javascript">
function myFunction(a) {
var cells = document.getElementById("table1").rows[a].cells;
for (var i = 0, len = cells.length; i < len; ++i) {
cells[i].style.backgroundColor = "yellow";
}
}
</script>
It's still not working, how do I fix it? Thanks!

If you're using jquery then change your function to be:
<script type="text/javascript">
function myFunction(a)
{
$(a).parent().parent().css("background-color", "yellow");
}
</script>
If you were going to just use plain javascript then it would be:
<script type="text/javascript">
function myFunction(a)
{
a.parentNode.parentNode.style.backgroundColor = "yellow";
}
</script>

<select onchange="this.parentNode.parentNode.style.backgroundColor='yellow';"></select>

Change your function to this:
function myFunction(a)
{
a.parentNode.parentNode.style.backgroundColor = "yellow";
}
Then make sure you fix a little typo you have on the select (single quote instead of double quotes):
<table id="table1">
<tr>
<td>Value</td>
<td><select onchange="myFunction(this);">
<option value="1">1</option>
<option value="2">2</option>
</select>
</td>
</tr>
</table>
http://jsfiddle.net/hescano/GkvA9/

Related

JQuery set select from string

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>

Change one select based on the value of another with Javascript

I need one <select> dropdown to change based on another. Here is what I have so far, which is not working.
HTML
<html>
<head>
...
</head>
<body>
<form>
<table>
<tr>
<td>Dropdown Menu 1</td>
<td>Dropdown Menu 2</td>
</tr>
<tr>
<td>
<select id="ddl1" onchange="changeDropdown(this,document.getElementById('ddl2'))">
<option value=""><!---------></option>
<option value="Colors">Colors</option>
<option value="Shapes">Shapes</option>
<option value="Sounds">Sounds</option>
</select>
</td>
<td>
<select id="ddl2">
</select>
</td>
</tr>
</table>
</form>
</body>
</html>
Javascript
<script>
function changeDropdown(ddl1,ddl2) {
var colors = new Array('Black', 'Brown', 'Blue');
var shapes = new Array('Triangle', 'Square', 'Circle');
var sounds = new Array('Loud', 'Soft');
switch (ddl1.value) {
case 'Colors':
for (i = 0; i < colors.length; i++) {
createOptions(ddl2, colors[i], colors[i]);
}
break;
default:
ddl2.options.length = 0;
break;
}
}
function createOptions(ddl,text,value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.option.add(opt);
}
</script>
This needs to be in Javascript. I know that people usually advice jQuery for stuff like this, but this needs to be Javascript.
What am I doing wrong?
Thanks in advance!
-Anthony
Instead of:
opt.option.add(opt);
Do:
ddl.appendChild(opt);
This works:
function createOptions(ddl,text,value) {
var opt = document.createElement('option');
opt.setAttribute("value", value);
opt.innerHTML=text;
ddl.appendChild(opt);
}
opt.option.add(opt);
Seems like you're adding the option to itself.

Appear div on select change with php

I am kinda stuck and I can't tell why.
I am trying to make a form and within this form I put a 'select' tag. Every options has a single number, 0 to 5. If you choose less than 2, a div appears, else, nothing appears. Here's my code :
<script>
$(document).ready(function(){
$("#depuis").change(function(){
if ($('#depuis') < 2)
$('#moins2').show();
});
});
</script>
And this is my body :
<form action="test.php" method="post">
<table class="formDiv" id="info_perso">
<tr>
<td><label for="depuis">Depuis combien d'annees:</label></td>
<td><select id="depuis" name="depuis">
<option value=''></option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
</td>
</tr>
</table>
</form>
<table class="formDiv" id="moins2">
<tr>
<td>Veuillez entrer votre ancienne adresse.</td>
</tr>
<tr>
<td><label for="adresse2">Adresse :</label></td>
<td><input type="text" id="adresse2" name="adresse2"></td>
<td><label for="app2">App :</label></td>
<td><input type="text" id="app2" name="app2"></td>
</tr>
<tr>
<td><label for="codepostal2">Code Postal :</label></td>
<td><input type="text" id="codepostal2" name="codepostal2"></td>
<td><label for="ville">Ville :</label></td>
<td><input type="text" id="ville" name="ville"></td>
</tr>
<tr>
<td><label for="telephone2">Telephone :</label></td>
<td><input type="text" id="telephone2" name="telephone2"></td>
</tr>
</table>
There's a problem in my function, how can I fix it?
try something like this
$(function(){
$("#depuis").change(function(){
if (this.value < 2){
$('#moins2').show();
}else{
$('#moins2').hide();
}
});
})
Write:
check();
$("#depuis").change(function () {
check();
});
function check() {
if (parseInt($("#depuis").val()) < 2) {
$('#moins2').show();
} else {
$('#moins2').hide();
}
}
DEMO here.
if ($('#depuis') < 2)
$('#moins2').show();
you are not comparing with integers... first get the indexed size and then compare
or use else case to check what is going wrong here...
Try this:
<script>
$(document).ready(function(){
$("#depuis").change(function(){
if ($('#depuis').val() < 2)
$('#moins2').show();
else
$('#moins2').hide();
});
});
</script>
Demo
Getting select box value use .val()
<script>
$(document).ready(function(){
$("#depuis").on('change',function(){
if (parseInt($("#depuis").val()) < 2)
$('#moins2').show();
else
$('#moins2').hide();
});
$("#depuis").trigger('change')
});
</script>
DEMO
add a onchage event on your select box like this
<select id="depuis" name="depuis" onchange="javascript:show_div(this.value);">
and use js function
function show_div(str)
{
if(str<2)
{
document.getElementById('moins2').style.display="block";
}
else
{
document.getElementById('moins2').style.display="none";
}
}
you can also use jquery function as follows without attibute onchange on select box
$(function(){
$("#depuis").change(function(){
if (this.value < 2){
$('#moins2').show();
}else{
$('#moins2').hide();
}
});
})
See JS Fiddle

Trying to output from Javascript file to HTML page?

I am trying to output from a Javascript file to the HTML page, and I am coming across some difficulty. Basically the user would select the options from the drop down menus and input from the text boxes, hit calculate and the program would calculate the necessary values.
After the calculation is complete there are three variables that I would like to output back to the page. Disregard the actual calculations, they are irrelevant. I am using jQuery and Javascript, I guess I can return a single variable but how do I return all of the variables I need.
Here is the HTML page I have and the javascript file.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="framework.js"></script>
<script type="text/javascript">
function ShowCalculation() {
Main($("#orangeSel").val(), $("#appleSel").val(), $("#soccerTxt").val(), $("#basketballTxt").val(), $("#banSel").val());
}
</script>
</head>
<body>
<div>
<div>
<br />
<table border="0">
<tr>
<td>
Number of Bananas
</td>
<td>
<select id="banSel">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
<td>
Number of Oranges:
</td>
<td><select id="orangeSel">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
<td>
Apples
</td>
<td>
<select id="appleSel">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3 </option>
<option value="4">4</option>
</select>
</td>
</tr>
<tr>
<td>
Soccer Score:
</td>
<td>
<input type="text" id="soccerTxt" value="2" size="3" />
</td>
<td>
Basketball Score:
</td>
<td>
<input type="text" id="basketballTxt" value="30" size="3" />
</td>
</tr>
</table>
<br />
<br />
<center><input type="submit" value="Calculate" onclick="ShowCalculation(); return false;" /></center>
</div>
</div>
<div>
<b><h1>Output</h1></b>
<table border="0">
<tr>
<td>
Manipulated Oranges:
</td>
</tr>
<tr>
<td>
Manipulated Apples:
</td>
</tr>
<tr>
<td>Manipulated Soccer:</td>
</tr>
</table>
</div>
</body>
</html>
And here is the Javascript file
function Main(orange, apple, soccer, basketball, banana) {
var a = parseInt(orange);
var b = parseInt(apple);
var c = parseInt(soccer);
var d = 0;
var e = parseInt(basketball);
var f = parseInt(banana);
for (var i = 0; i < a; i++) {
d += c;
}
for (var j = 0; j < 10; i++) {
c += 30;
}
var outputOne = c;
var outputTwo = d;
var outputThree = 5;
}
To return several values from a JavaScript function you can create a new "anonymous" object, something like this in the Main() function:
function Main(orange, apple, soccer, basketball, banana) {
var a = parseInt(orange);
var b = parseInt(apple);
var c = parseInt(soccer);
var d = 0;
var e = parseInt(basketball);
var f = parseInt(banana);
for (var i = 0; i < a; i++) {
d += c;
}
for (var j = 0; j < 10; i++) {
c += 30;
}
var outputOne = c;
var outputTwo = d;
var outputThree = 5;
return {output1:outputOne, output2:outputTwo, output3:outputThree};
}
Then you have to modify the markup to add ids to the fields where you want to output the variables:
<td>
Manipulated Oranges: <span id="manOranges"></span>
</td>
Then you will have to change the JavaScript function ShowCalculation to look like this:
function ShowCalculation() {
var results = Main($("#orangeSel").val(), $("#appleSel").val(), $("#soccerTxt").val(), $("#basketballTxt").val(), $("#banSel").val());
$("#manOranges").html(results.output1);
}
...
Hope this helps
Edit: Added the complete Main function to show how the entire function has to look.
You could return the results as an object. Something along these lines:
return {
outputOne: c,
outputTwo: d,
outputThree: 5
};
This is know as JavaScript Object Literal Notation. You can read more about it in this article.
EDIT:
Using jQuery there are several ways you can then add the results to your page using. jQuery.append or jQuery.html are two such ways.
I posted an example using your code on jsFiddle. Also, there is a bug in this line:
for (var j = 0; j < 10; i++)
i++ should be j++.
In your code you are using the id selector to get the value of some elements
$("#orangeSel").val()
In the same way, you need to set the value once you do the computation
$("#answer-area").html('the answer)
I believe if your answer-area is an input, you can use val('the answer') in place of html.
f you want to return the value to another javascript function you could use an map object:
var output=[ val1, val2, val3];
and then loop trough em with a foreach
for (i in output){
do something
}
if you want to display these values in your html i would advice you to set the values from your javascript directly by giving the cell you want the values at an ID and putting a value like this
document.getElementById('answer1').innerHTML = val1;

Adding rows dynamically with jQuery

I'm building a form where I need multiple optional inputs, what I have is basically this:
Every time a user presses the plus button a new row of form inputs should be added to the form, how can I do this in jQuery? Also, is it possible to automatically add a new row when all rows (or just the last row, if it's easier / faster) are filled? That way the user wouldn't need to press the plus button.
I'm sorry for asking maybe such a basic question but I'm still very green with jQuery, I could do this with PHP but I'm sure Javascript / jQuery plays a more appropriate role here.
#alex:
<!DOCTYPE html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<script type="text/javascript">
$form = $('#personas');
$rows = $form.find('.person');
$('a#add').click(function() {
$rows.find(':first').clone().insertAfter($rows.find(':last'));
$justInserted = $rows.find(':last');
$justInserted.hide();
$justInserted.find('input').val(''); // it may copy values from first one
$justInserted.slideDown(500);
});
</script>
</head>
<body>
<form id="personas" name="personas" method="post" action="">
<table width="300" border="1" cellspacing="0" cellpadding="2">
<tr>
<td>Name</td>
<td>More?</td>
</tr>
<tr class="person">
<td><input type="text" name="name[]" id="name[]" /></td>
<td>+</td>
</tr>
</table>
</form>
</body>
</html>
This will get you close, the add button has been removed out of the table so you might want to consider this...
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function() {
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
return false;
});
});
</script>
HTML markup looks like this
<a id="add">+</a></td>
<table id="mytable" width="300" border="1" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td>Name</td>
</tr>
<tr class="person">
<td><input type="text" name="name" id="name" /></td>
</tr>
</tbody>
</table>
EDIT To empty a value of a textbox after insert..
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
$('#mytable tbody>tr:last #name').val('');
return false;
EDIT2 Couldn't help myself, to reset all dropdown lists in the inserted TR you can do this
$("#mytable tbody>tr:last").each(function() {this.reset();});
I will leave the rest to you!
As an addition to answers above: you probably might need to change ids in names/ids of input elements (pls note, you should not have digits in fields name):
<input name="someStuff.entry[2].fieldOne" id="someStuff_fdf_fieldOne_2" ..>
I have done this having some global variable by default set to 0:
var globalNewIndex = 0;
and in the add function after you've cloned and resetted the values in the new row:
var newIndex = globalNewIndex+1;
var changeIds = function(i, val) {
return val.replace(globalNewIndex,newIndex);
}
$('#mytable tbody>tr:last input').attr('name', changeIds ).attr('id', changeIds );
globalNewIndex++;
I have Tried something like this and its works fine;
this is the html part :
<table class="dd" width="100%" id="data">
<tr>
<td>Year</td>
<td>:</td>
<td><select name="year1" id="year1" >
<option value="2012">2012</option>
<option value="2011">2011</option>
</select></td>
<td>Month</td>
<td>:</td>
<td width="17%"><select name="month1" id="month1">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select></td>
<td width="7%">Week</td>
<td width="3%">:</td>
<td width="17%"><select name="week1" id="week1" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select></td>
<td width="8%"> </td>
<td colspan="2"> </td>
</tr>
<tr>
<td>Actual</td>
<td>:</td>
<td width="17%"><input name="actual1" id="actual1" type="text" /></td>
<td width="7%">Max</td>
<td width="3%">:</td>
<td><input name="max1" id="max1" type="text" /></td>
<td>Target</td>
<td>:</td>
<td><input name="target1" id="target1" type="text" /></td>
</tr>
this is Javascript part;
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type='text/javascript'>
//<![CDATA[
$(document).ready(function() {
var currentItem = 1;
$('#addnew').click(function(){
currentItem++;
$('#items').val(currentItem);
var strToAdd = '<tr><td>Year</td><td>:</td><td><select name="year'+currentItem+'" id="year'+currentItem+'" ><option value="2012">2012</option><option value="2011">2011</option></select></td><td>Month</td><td>:</td><td width="17%"><select name="month'+currentItem+'" id="month'+currentItem+'"><option value="1">January</option><option value="2">February</option><option value="3">March</option><option value="4">April</option><option value="5">May</option><option value="6">June</option><option value="7">July</option><option value="8">August</option><option value="9">September</option><option value="10">October</option><option value="11">November</option><option value="12">December</option></select></td><td width="7%">Week</td><td width="3%">:</td><td width="17%"><select name="week'+currentItem+'" id="week'+currentItem+'" ><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option></select></td><td width="8%"></td><td colspan="2"></td></tr><tr><td>Actual</td><td>:</td><td width="17%"><input name="actual'+currentItem+'" id="actual'+currentItem+'" type="text" /></td><td width="7%">Max</td> <td width="3%">:</td><td><input name="max'+currentItem+'" id ="max'+currentItem+'"type="text" /></td><td>Target</td><td>:</td><td><input name="target'+currentItem+'" id="target'+currentItem+'" type="text" /></td></tr>';
$('#data').append(strToAdd);
});
});
//]]>
</script>
Finaly PHP submit part:
for( $i = 1; $i <= $count; $i++ )
{
$year = $_POST['year'.$i];
$month = $_POST['month'.$i];
$week = $_POST['week'.$i];
$actual = $_POST['actual'.$i];
$max = $_POST['max'.$i];
$target = $_POST['target'.$i];
$extreme = $_POST['extreme'.$i];
$que = "insert INTO table_name(id,year,month,week,actual,max,target) VALUES ('".$_POST['type']."','".$year."','".$month."','".$week."','".$actual."','".$max."','".$target."')";
mysql_query($que);
}
you can find more details via Dynamic table row inserter
Untested.
Modify to suit:
$form = $('#my-form');
$rows = $form.find('.person-input-row');
$('button#add-new').click(function() {
$rows.find(':first').clone().insertAfter($rows.find(':last'));
$justInserted = $rows.find(':last');
$justInserted.hide();
$justInserted.find('input').val(''); // it may copy values from first one
$justInserted.slideDown(500);
});
This is better than copying innerHTML because you will lose all attached events etc.
Building on the other answers, I simplified things a bit. By cloning the last element, we get the "add new" button for free (you have to change the ID to a class because of the cloning) and also reduce DOM operations. I had to use filter() instead of find() to get only the last element.
$('.js-addNew').on('click', function(e) {
e.preventDefault();
var $rows = $('.person'),
$last = $rows.filter(':last'),
$newRow = $last.clone().insertAfter($last);
$last.find($('.js-addNew')).remove(); // remove old button
$newRow.hide().find('input').val('');
$newRow.slideDown(500);
});

Categories

Resources