I'm generating a 2-column HTML table from a php array as follows:
<table>
<?php
$i=0
foreach ($fullNameArray as $namePair){
echo
"<tr>
<td id='first ".$i."'>".$namePair[0]."</td>
<td id='last".$i."'>".$namePair[1]."</td>
</tr>";
$i++;
}
?>
</table>
What is the best way to explore this table in Javascript, for example to build an array that would replicate the PHP array, i.e., an array of [first name, last name] pairs.
If you want to go the old-fashioned pure-JavaScript way, you could do some simple DOM traversal.
If you add an id to the table, your life will be much easier, especially if you have (or may later add) other tables in the page.
<table id="nameTable">
...
</table>
Now you can access the table in JavaScript and store a reference to it in a variable. You will also want to initialize an empty array/list variable to hold the names later.
var nameTable = document.getElementById("nameTable");
var nameArray = [];
Next, you begin looping through the child elements of the table, each of which will be a tr (table row) element.
for (var i=0; i<nameTable.childNodes.length; i++) {
...
}
Inside that for loop you will build your list of [first name, last name] pairs. You will do this by grabbing the value of each of the two td (table data cell) children of the current row.
var dataCells = nameTable.childNodes[i].childNodes;
var namePair = [dataCells[0].innerHTML, dataCells[1].innerHTML];
That should give you a JSON array something like this (my values added):
[
["Andy", "Jackson"],
["Barry", "Obama"],
["Benny", "Franklin"],
["Georgey", "Washington"],
["Billy", "Clinton"]
]
To review, the full code would look something like this:
var nameTable = document.getElementById("nameTable");
var nameArray = [];
for (var i=0; i<nameTable.childNodes.length; i++) {
var dataCells = nameTable.childNodes[i].childNodes;
var namePair = [dataCells[0].innerHTML, dataCells[1].innerHTML];
}
NOTE: This is fun, but it is likely that the better solution, if you don't mind a hard-coded JSON array in your source code (if you've got the table there anyway it really doesn't matter), is probably to print a json_encoded array in a <script> tag straight from the PHP, like #JayBhatt suggested. It is likely the faster method, and it puts much less stress on the user's browser.
Encode your array to Json using PHP's json_encode, assign this string to a javascript variable and decode json to array using javascript...
Another way could be assign the json to a hidden input instead a javascript and later get the input value in your javascript Code.
Related
I have this PHP Code which populates a select menu from a MySQL Database...
<select name="input" id="input">
<?php
$sql="SELECT * from table ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
while($result=mysql_fetch_array($rs))
{
echo '<option value="'.$result["db_field"].'">'.$result["db_field"].'</option>';
}
?>
</select>
which works perfectly fine but i need to somehow get it into a javascript function.
I have the javascript code that when you click a button it adds more text boxes and another select menu but it does not populate the data from the database in any new (added on) select menus
You can probably convert the options into JSON using json_encode (I am not a PHP programmer and dont know exact semantics of using it)
In PHP do something like:
echo '<script>var optionsJSON = '.json_encode(mysql_fetch_array($rs)).'</script>'
In javascriptn do something like (I am using jquery):
var select = $('select.classOfThisSelect');
var options = JSON.parse(optionsJSON);
for(var i = 0; i < options.length; i++)
$('option').attr({value: options[i]}).append(options[i]).appendTo(select);
optionsJSON will be the JSON string which will be globally available
You can freely use it in your Javascript function
Note: You may need to surround the json_encode with quotes
Start by converting the string of values into an array, so you have something like:
var values = ['value0','value1','value2'];
Then you can convert them to options and add them to a select element like:
function addOptions(select, values) {
for (var i=0, iLen=values.length; i<iLen; i++) {
select.appendChild(new Option(values[i],values[i]));
}
}
And call it like:
addOptions(document.getElementById('input'), values);
after the select is added to the page.
Incidentally, you don't need to add both an id and name to form controls. You must have a name for them to be submitted, the ID is unnecessary. If you get a reference to the form you can access controls as named properties of the form, so you might reference the select using:
document.forms[0]['input'];
or
document.forms[0].input;
and so on. Note that "input" isn't a good choice of control name.
The plan:
Basically I have a set of clothing items stored in a table each containing "item_name" "item_id" and "item_shortcode" I want to have a link per clothing item, when the user clicks the link the item needs to be added to an array (the selected array)
I'm trying to create a javascript object based off the data I've gathered from the mySQL database, then pass that data to a function when a div is clicked to my method.
this is an example:
<?php
while($row = mysql_fetch_array($results)){
?>
<script>
var item = new Object();
item.itemName = <?php echo json_encode($row['item_name']); ?>;
</script>
<?php
echo "<div id=\"".$row['item_name']."\" class=\"choice\" onclick=\"SetSelectedChoice(item);\">";
//echo $row['item_name'];
echo "</div>";
}
}
?>
EDIT: this is just an example I'll be populating my object with lots of data, not just item_name
problem is the last object seems to be assigned to every div in while loop.
Anyone point out where I am going wrong?
Well, i honestly don't know if i really got you, but if i see it right, then you simply overwrite the item-object in every run of the while-loop.
After the last loop (after this comes the output) the variable "item" is set to the last result of the loop, so clicking on any div will return "item" - the last item of the loop.
As a solution, try to save the rows name in the div as a parameter, like
echo "<div id=\"".$row['item_name']."\" class=\"choice\" onclick=\"SetSelectedChoice(\'".$row['item_name']."\');\">";
You're redefining item on every iteration. Why not do something like this:
As per edit, you can create an item array and populate it in the loop:
<script type="text/javascript">
var objects = new Array();
</script>
<?php while($row = mysql_fetch_array($results)): ?>
<script type="text/javascript">
var item = new Object();
item.itemName = '<?php echo json_encode($row['item_name']); ?>';
objects.push(item);
</script>
<div id="<?php echo $row['item_id']; ?>" class="choice">
<?php echo $row['item_name']; ?>
</div>
<?php endwhile; ?>
then in js OUTSIDE of your loop:
$('.choice').on('click', function(){
SetSelectedChoice($(this).html());
});
function SetSelectedChoice(name)
{
for(var i = 0; i < objects.length; i ++)
{
if(objects[i].itemName == name)
{
//do something
}
}
}
NOTE: I wouldn't really recommend this kind of weird loop for comparing names. I just don't know what else you are doing with passing the name to this function. I would pass the item id or the index value and directly access an item in the array instead of a loop. Make sense?
Basically, stop using onclick. The whole world is leaning more on listeners. Secondly, no need to create an object at all. You don't seem to be using it and even if you did, you didn't put single quotes around the name like you should for strings. Thirdly, please break out of php to write html. It's just cleaner and easier. Morely, assign the item's id to the id parameter. It gets really ugly to have names and spaces in the ids of elements. And you don't really seem to need one since you don't use it in your example. None the less, I put it in there in case you wanted to access it like $(this).attr('id') in the on click listener.
But if I missed the point, perhaps you can clarify and I may update to better fit your needs
i want to create array of same id or name using getElementById..
i have a "add button", when the user press this button, its generate a dropdown list(dynamic) which the value is get from mysql..
and its looks like this when the user press 3 times..
i want to create an array of this id, and store it to mysql..
this is my JS code :
var menu_paket_array = document.getElementById('menu_paket').value;
alert(menu_paket_array);
the problem is, when i try to create this array(menu_paket_array), the value in this array is just the first id (Test 1) only..
how can i fix this?
thanks...
Using the same id for more than one element is wrong. Id is to uniquely identify certain element. Using it for more elements defeats its -purpose. If you need that for i.e. CSS styling, then use class instead, which is designed just for such scenarios.
An ID must be unique on a page. You can only use it on one element.
Instead, use a CSS class or element type to iterate (here's a fiddle demonstrating this code):
function alertValues() {
var select, selects = document.getElementsByTagName('select');
var out = "";
for (var i = 0; i < selects.length; i++) {
select = selects[i];
if (select.className && select.className.match(/CLASSNAME_TO_INCLUDE/)) {
out += select.options[select.selectedIndex].value;
}
}
alert(out);
}
A better solution, of course, would be to utilize a dom library like jQuery or mootools, with which you could do something like this:
jQuery(function($) {
vals = [];
$('select.CLASSNAME').each(function() { vals.push($(this).val()); });
alert(vals.join(','));
});
document.getElementsByClassName(names);
Where names is the classname u generate for each one.
Instead of assigning each element with id='menu_paket' (for the reasons #WebnetMobile.com explained) assign class='menu_paket'.
Instead of var menu_paket_array=document.getElementById('menu_paket').value;, do
var temp_array = document.getElementsByClassName('menu_paket');
var menu_paket_array = [];
for(i in temp_array){
menu_paket_array[] = temp_array[i].value;
}
I have an array being passed from php which looks like:
$resultsArr[123]['A']='q';
$resultsArr[123]['B']='d';
$resultsArr[113]['C']='s';
$resultsArr[113]['A']='ss';
$resultsArr[113]['B']='sd';
$resultsArr[111]['C']='sds';
$resultsArr[111]['A']='vv';
$resultsArr[111]['B']='vv';
i need to access certain values frmo this array using jquery.
i am trying to access it like
keyVal = 123; //dynamically generated
var pri = '~$results['keyVal']['B']`'
but i am getting a blank value in variable 'pri'
How can this be solved?
Could you not convert it to a JSON Array and then use it directly in Javascript, rather than picking out individual elements of the array?
<script>
var myArray = <?php echo json_encode($resultsArr); ?>;
</script>
Then use jQuery each to read the array.
This would give you greater flexibility in the long term of what was available to javascript for reading and manipulation.
EDIT
You can read a specific element like so, this will alert "vv":
<script>
var myVar = myArray[111].A;
alert(myVar);
</script>
In php use :
$ResultsArr = json_encode($resultsArr);
$this->jsonResultsArr = $ResultsArr; //its seems u r using smarty.
In javascript
jsonResultsArr = "~$jsonResultsArr`";
requireValue = jsonResultsArr[111].A;
Here's my little problem:
I've this code http://jsfiddle.net/marcelo066/d7ehQ/light/ which I changed from BrianGlaz's original http://jsfiddle.net/B7bgN/10/ .It clones some part from a form. My question is: how can I get this cloned values using php to store it in a mysql database? Just for enlightenment, the code from my fiddle is a part from a bigger form, which is working. So i add this clone part, and I don't know how to get the cloned values from $_POST. Any ideas?
Name your form fields as array elements:
<select name="dormitorios_name[0]"... >
And for the clones make it respectively
<select name="dormitorios_name[1]"... >
...
<select name="dormitorios_name[2]"... >
Thus in you php code you can check for
$i = 0;
do {
// save values
$i++;
} while (isset( $_POST['dormitorios_name'][$i])
Use arrays on elements attributes names.
Alter the names of the elements so that instead of name="myname" and name="myname2", name="mayname3" you have name="myname[0]" and name="myname[1]", name="myname[2]".
So that in the $_POST array you will have $_POST['myname'] as an array will al original and cloned values and not $_POST['myname'],$_POST['myname2'],$_POST['myname3'].
Depending on the way you want to hanlde that you could also have original elements with names like name="form[0][myname]" and the others like name="form[1][myname]", etc. At the end the original elements values are on $_POST['form'][0] and the others in $_POST['form'][1], $_POST['form'][2], etc.
I've made a fiddle here http://jsfiddle.net/regilero/6kd2L/1/
http://jsfiddle.net/regilero/6kd2L/1/
Where basically, appart from altering the way names are handled in the HTML part I 've altered
$(elem).attr('id', $(elem).attr('id') + newNum).attr('name', $(elem).attr('name')+ newNum);
To:
var $elem = $(elem);
$elem.attr('id', $elem.attr('id') + newNum);
var ename = $elem.attr('name');
if (ename) {
$elem.attr('name',ename.replace('form[0]','form['+newNum+']'));
}