I created a dropdown list with javascript and I populate it getting data from a MySQL database.
The problem that I have is that I can't place the dropdown list in the innerHTML code.
This is what I wrote to create the dropdown list with JS:
var mySpan = document.getElementById('myDiv');
var myLine = document.getElementById('testcat');
myLine.value++;
// Create select
var selection = document.createElement('select');
selection.setAttribute('name',"category[]");
mySpan.appendChild(selection);
// Create Option
createSelectOption(selection);
// Create the container
var ni = document.getElementById('myDiv');
ni.setAttribute('style', 'width:790px;');
...........
...........
Then I create other things and to create the HTML code, I use:
newdiv.innerHTML = '<div class="table">.........</div>';
ni.appendChild(newdiv);
This is the part of HTML:
// test dropdown list
<input name="testcat" id="testcat" type="hidden" value="0" />
<div id="myDiv"></div>
I tested my dropdown list as you can see in the code above, and it works if I declare <input name="testcat" id="testcat" type="hidden" value="0" /> in the HTML (I mean in the <body></body>), but if I use the same code in the innerHTML, FireBug tells me: "myLine is null; myLine.value++;".
Any help?
You can't assign an element with an ID using innerHTML as text - the ID won't register on the DOM. You need to first create the element, assign it the ID and then put that element in the DOM.
You might find this easier using jQuery:
var input = document.createElement("input");
input.id="testcat";
input.innerHTML = "testcat" ;
$('somediv').appendChild(input);
this is what I did in my old code:
var selectcat = document.createElement("select");
selectcat.name = "category[]";
selectcat.options[0] = new Option("","");
selectcat.options[1] = new Option("cat1","cat1");
selectcat.options[2] = new Option("cat2","cat2");
..........
..........
selectcat.options[12] = new Option("cat1","cat12");
And the used:
newdiv.innerHTML = '<div class="table"><ul><li><select name="category[]"><option value=""></option><option value="cat1">cat1</option><option value="cat2">cat2</option></select></li></ul></div>';
But now I have to get the values from a MySQL database.
So I created this function:
function createSelectOption(element)
{
var objSelect = ele;
var Item = new Option("", "");
objSelect.options[objSelect.length] = Item;
<?
while($categ = mysql_fetch_array($resultf_categ))
{
?>
var Item = new Option("<?=$categ["cat_name"];?>", "<?=$categ["cat_name"];?>");
objSelect.options[objSelect.length] = Item;
<?
}
?>
}
But still don't understand how can I use directly in my innerHTML.
Sorry for the stupid questions, but I am really stucked here.
Related
i have a form where two fields are dynamically generated through java script when a button is clicked.when the button is clicked each time,the two text field will generate again and again.now i have got the count of text field generated in a hidden field in JavaScript.How can i get the value of hiddenfield in controller and insert the values of text fields in database,by appending comma in data when the text box value is entered each time.please help me.
my javascript is
<script>
var countbox=0;
var textbox1=0;
var textbox2=0;
function getField()
{
var newtextbox1="name1"+countbox;
var newtextbox2="name2"+countbox;
document.getElementById('renderDiv').innerHTML+='<br/><input type="text" id="'+newtextbox1+'" name="'+newtextbox1+'" /><br/><input type="text" id="'+newtextbox2+'" name="'+newtextbox2+'" />';
document.getElementById('renderDiv').innerHTML+='<br/><input type="hidden" id="hiddentextField" name="hiddentextField" value="'+countbox+'" />';
countbox +=1;
}
</script>
my html code is
<input type="button" id="button1" onclick=getField();/>
<div id="renderDiv">
</div>
inside this div the two textfield is generated along with the hidden field
i am not getting the value of textfield in controller while submitting and i am not getting the count of textfield.i tried like $hiddenfield=$this->input->post('hiddentextField');
you will have to post the variable inorder to pass this to the server
<script>
var countbox=0;
var textbox1=0;
var textbox2=0;
function getField()
{
var newtextbox1="name1"+countbox;
var newtextbox2="name2"+countbox;
document.getElementById('renderDiv').innerHTML+='<br/><input type="text" id="'+newtextbox1+'" name="'+newtextbox1+'" /><br/><input type="text" id="'+newtextbox2+'" name="'+newtextbox2+'" />';
document.getElementById('renderDiv').innerHTML+='<br/><input type="hidden" id="hiddentextField" name="hiddentextField" value="'+countbox+'" />';
countbox +=1;
window.location.href = "index.php?name=" + countbox-1;
//change index.php to your page name
}
</script>
then in the same page
<?php
$hiddenfield=$_GET["name"];
?>
I had the same problem before, what I did is I insert those text box inside a table, lets say, tableSample
then I use jQuery find
var _content = '';
var _findcontent = $("#tableSample");
_findcontent.find("tr").each(function(){
$(this).find("td").each(function(){
$(this).find("input").each(function(){
_content += $(this).val+'~'+$(this).attr("id")+'|';
});
});
});
Then use ajax to pass it to your PHP
$.post("<?php echo site_url('controller_name/method_name'); ?>",
{
content : _content
}
,function( _data){
jAlert("alert",_data,"alert");
});
In your PHP, you can use explode to get the desired values,
$content_from_page = $this->input->post("content");
$explode_string = array();
$explode_string = explode("|",$content_from_page );
$explode_arr = array()
for($x=0;$x<count($explode_string)-1;$x++)
{
$explode_arr[] = explode("~",$explode_string[$x];
}
then print_r($explode_arr); to check
*Note: The only problem with this approach is that, if the character that is inserted into the textbox is ~ or |, coz that is the delimiter used.
i have this code:
This is the addOptions function
<script>
var values = <?php
$sql="SELECT * FROM billing_sagenominalcodes order by code ASC";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$nominalcodes = array();
while($result=mysql_fetch_assoc($rs))
{
$nominalcodes[] = $result['code'];
}
echo json_encode($nominalcodes);
?>;
var names = <?php
$sql="SELECT * FROM billing_sagenominalcodes order by code ASC";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$nominalcodesname = array();
while($result=mysql_fetch_assoc($rs))
{
$nominalcodesname[] = $result['code'] . ' - ' . $result['name'];
}
echo json_encode($nominalcodesname);
?>;
function addOptions(select, values)
{
for (var i=0, iLen=values.length; i<iLen; i++)
{
select.appendChild(new Option(names[i],values[i]));
}
}
</script>
then the add row function
<script language="javascript" type="text/javascript">
var i=1;
function addRow()
{
var tbl = document.getElementById('table1');
var lastRow = tbl.rows.length;
var iteration = lastRow - 1;
var row = tbl.insertRow(lastRow);
var sagenominalcodeCell = row.insertCell(3);
var elSageNominalCode = document.createElement('select');
elSageNominalCode.type = 'select';
elSageNominalCode.name = 'sagenominalcode' + i;
elSageNominalCode.id = 'sagenominalcode' + i;
sagenominalcodeCell.appendChild(elSageNominalCode);
i++;
}
</script>
and then the HTML
<select name="sagenominalcode" id="sagenominalcode">
<script>addOptions(document.getElementById('sagenominalcode'), values);</script>
</select>
<input type="button" value="Add" onclick="addRow();" />
it adds the new rows ok but its no populating the select menu with the addOptions function.
is there any way to make it run that function once the new row/select menu has been dynamically created and then the same for all the others created when the addRow function is called?
So, reading your code a little bit more, I see you have
new Option(names[i],values[i])
My question to you is what does new Option return? I don't see code for it anywhere in your question.
Take a look at the spec for appendChild :
https://developer.mozilla.org/en-US/docs/DOM/Node.appendChild
It needs an element passed in. What you want to do is make a new element using the createElement() function like so:
var option = document.createElement("option");
And then edit the inner html to be what ever you need like this:
option.innerHTML = "your option content here";
Then pass the element in to the append child function:
appendChild(option);
Use jQuery here instead of straight js. My bet is that your listener for click is only bound to the items that are present on the page when it is created. If you set up a listener through jQuery, then it will fire even on components that are dynamically added.
Also from a code structuring stand point, be very careful about writing js with php. Although it sounds fun (like doing drugs in highschool) it is dangerous, frustrating and leads to untestable code (like doing drugs in highschool does).
Hello i want to create dynamic drop-downs using javascript, but its not working..
My PHP code:
<input type="button" onclick="javascript:addRow();" value="Add Row" name="addRow"/>
My JS code:
// This function is used to create dynamic form element
function addRow() {
var opt = document.createElement("option");
element = document.createElement("select");
element.setAttribute('id', 'focus');
element.options.add(opt);
}
PS: It is not giving any js console error.
you dont add the element to the body so it doesn't show up
// This function is used to create dynamic form element
function addRow() {
var opt = document.createElement("option");
element = document.createElement("select");
element.setAttribute('id', 'focus');
element.options.add(opt);
document.body.appendChild(element);
}
I create an HTML select element dynamically after a user choice is made from another select element. However the PHP script for inspecting the form does not recognise the new element and is indicating it null:
Here is snippets:
some.js:
if(document.getElementById(firstselect).value=='somvalue'){
document.getElementById(gamsDiv).removeChild(gamsElem);
gamsElem = document.createElement("select");
gamsElem.id = "FacilityGamsId";
gamsElem.name = "FacilityGamsId";
gamsElem.setAttribute("onChange", "updateHidden(this);makeUpdateRequest(arguments[0],this)");
opt = document.createElement("option");
opt.text="Select one ";
opt.value=0;
gamsElem.options.add(opt);
.....some other stuff
.....
document.getElementById(gamsDiv).appendChild(gamsElem);
}
the php script:
if($_POST){
var_dump($_POST['FacilityGamsId'];
}
result: null
Is there any reason why the server post action does not recognise ANY of my dynamic HTML elements from js script. If I examine/inspect the newly created elements, the name and id are exactly same.
Any Help is high appreciated ;) . Thanks
It's not added to the form stored in the DOM of the browser.
This guy was trying to do the same: dynamic element created not POSTed
A solution would be to build the dynamic form server-side -- if it really needs to be client-side, I think you need to manipulate the form (stored in document.forms) in addition to the DOM.
Here:
gamsElem.options.add(opt);
add is a method of the select element interface, not options (which is an HTMLElement Collection and doesn't have an add method). So:
gamsElem.add(opt);
should fix the issue.
Note that gamsElem.add(opt); does not work in Mozilla firefox 6 so I reverted to my old code of gamsElem.options.add(opt).
And:
gamsElem.setAttribute("onChange",
"updateHidden(this);makeUpdateRequest(arguments[0],this)");
would be better as:
gamsElem.onchange = function() {
updateHidden(this);
makeUpdateRequest(arguments[0], this);
};
though I have no idea what arguments[0] should reference.
Here is how this would be done normally (though the button would call a function rather than have a slab of inline code, I've done it that way for convenience only):
<form action="">
<div id="div0">
<select id="sel0" name="sel0">
<option>option 0
</select>
<input type="submit">
</div>
</form>
<button onclick="
var div = document.getElementById('div0');
var sel = document.getElementById('sel0');
div.removeChild(sel);
sel = document.createElement('select');
sel.id = 'sel1';
sel.name = 'sel1';
sel.onchange = function(){alert(this.value);};
sel.options[0] = new Option('Select one', '0');
sel.options[1] = new Option('Select two', '1');
div.appendChild(sel);
">Replace select</button>
A second option is needed to get the onchange listener to fire.
If you want to replace one element with another, create the new element then just replace the old one:
<button onclick="
var oldSel = document.getElementById('sel0');
var sel = document.createElement('select');
sel.id = 'sel1';
sel.name = 'sel1';
sel.onchange = function(){alert(this.value);};
sel.options[0] = new Option('Select one', '0');
sel.options[1] = new Option('Select two', '1');
oldSel.parentNode.replaceChild(sel, oldSel);
">Replace select</button>
Or you can just replace the options (set the select's options.length to zero and just add the new ones).
You have to add a new element into your FORM tag
Run this code after the DOM is ready, preferably $.ready() in jquery.
and also put the quotes aroun div name ("gamsDiv")
I have a javascript code helping me to dynamically create row after row in a table and to delete a row from that table.
each row has four cells. cell 1 for instance contains a text zone.
to differentiate cell1 from row 1 with cell1 from row 2, I rename my cell 1 like that cell1.name= cell1.name + '_' + row.rowIndex.
I create a submit button so that I could read data entered by a user in the rows of the table and I try to print $_GET. but there is nothing inside. How could I access to my DOM objects in PHP?
I am grateful for your help.
my HTML + PHP code
<body >
<?php
if (isset($_GET['Enter'])){
print_r($_GET);
}
?>
<h1> Create an Item </h1>
<form method="GET" action="func.html">
<table align="center" border = "2" cellspacing ="0" cellpadding="3" id="table">
<tr><td><b>Functionality Name:</b></td> <td><b>Description:</b></td> <td><b>Status:</b></td> <td><input type="button" Name= "Ajouter" Value="Ajouter" onclick="go()"></td></tr>
</table>
<input type="submit" name="submit" value="Enter">
</form>
</body>
and my Javascript code:
<script>
function getXhr(){
var xhr = null;
if(window.XMLHttpRequest) // Firefox and others
xhr = new XMLHttpRequest();
else if(window.ActiveXObject){ // Internet Explorer
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
else { // XMLHttpRequest not supported by your browser
alert(" Your browser does not support XMLHTTPRequest objects...");
xhr = false;
}
return xhr
}
/**
* method called when the user clicks on the button
*/
function go(){
var xhr = getXhr()
// We defined what we gonna do with the response
xhr.onreadystatechange = function(){
// We do somthing once the server's response is OK
if(xhr.readyState == 4 && xhr.status == 200){
var body = document.getElementsByTagName("body")[0];
// Retrieve <table> ID and create a <tbody> element
var tbl = document.getElementById("table");
var tblBody = document.createElement("tbody");
var row = document.createElement("tr");
var cell_1 = document.createElement("td");
var cell_2 = document.createElement("td");
var cell_3 = document.createElement("td");
var cell_4 = document.createElement("td");
// Create the first cell which is a text zone
var cell1=document.createElement("input");
cell1.type="text";
cell1.name="fname";
cell1.size="20";
cell1.maxlength="50";
cell_1.appendChild(cell1);
// Create the second cell which is a text area
var cell2=document.createElement("textarea");
cell2.name="fdescription";
cell2.rows="2";
cell2.cols="30";
cell_2.appendChild(cell2);
// Create the second cell which is a combo box
var cell3 = document.createElement("div");
cell3.id="rs";
cell3.innerHTML=xhr.responseText;
cell_3.appendChild(cell3);
// Create the fourth cell which is a button
var cell4=document.createElement("input");
cell4.type="button";
cell4.value="Delete"
cell4.onclick=delRow;
cell_4.appendChild(cell4);
// add cells to the row
row.appendChild(cell_1);
row.appendChild(cell_2);
row.appendChild(cell_3);
row.appendChild(cell_4);
// add the row to the end of the table body
tblBody.appendChild(row);
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// Rename cells with the row index
var ind=row.rowIndex;
var liste_fname = row.getElementsByTagName("input");
for(i=0; i < liste_fname.length; i++)
{
if(liste_fname[i].name == "fname")
{
liste_fname[i].name = liste_fname[i].name + "_" + ind; //give fname_1, fname_2, fname_3, ...
}
}
var fd = row.getElementsByTagName("textarea");
fd[0].name = fd[0].name + "_" + ind;
var cd = row.getElementsByTagName("div");
cd[0].id = cd[0].id + "_" + ind;
var selectname = row.getElementsByTagName("select");
selectname[0].name = selectname[0].name + "_" + ind;
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 1;
tbl.setAttribute("border", "1");
}
}
xhr.open("GET","fstatus.php",true);
xhr.send(null);
}
function delRow(){
var i= this.parentNode.parentNode.rowIndex;
document.getElementById('table').deleteRow(i);
}
</script>
Best regards,
Billy
Because PHP is server side and Javascript is Client side you can't directly access elements on the page.
In order to access elements you need to post back to the server via a FORM or some AJAX.
You might look into jQuery to help you do this since it makes it easier to call your PHP programs and manipulate the DOM.
I'm going to second the use of jQuery. It'll be tidier and keep you neatly in a single paradigm during this particular task.
One way to do this with PHP would be to dump your DOM object into JSON and then use PHP's JSON support. Depending on your purposes, you can roll your own class to process the JSON data or just grab it from the array you get from json_decode(). Another way would be to dump the object into its representative HTML and pass that to your PHP script rather than the DOM object. You can then reparse it using The Simple HTML DOM Parser, an easy-to-use, freely available DOM parser for PHP.
Of course, you should note that you're adding two processing steps here. If you can do the processing you need to do without switching languages, you're saving time and a bit of sanity.
Well... for starters you want to see if $_GET['submit'] is set not $_GET['Enter'] because $_GET['submit'] should have the value of 'Enter'.
Also, each of your textarea's need to have a different name from the rest, so they don't overwrite each other ( Or they need to have a name that ends in [] (square brackets) and then php will turn them into an array).
And once the html is submitted... the DOM doesn't exist anymore so PHP can't really access it except through ajaxy kinf of stuff.
your cell name should not named like that ... it should be like this
<input type='text' name='username[]' value=''/>
<input type='text' name='username[]' value=''/>
<input type='text' name='username[]' value=''/>
.....
<input type='submit' name='submit' value='submit'/>
so you can access from php as array of username
$_GET[username][0] for example will display the first username etc ...
btw, try to use prototype or jquery (javascript framwork) it will simplify your life a lot.
to post data using jquery using ajax:
var url = 'your.server.com/post/fstatus.php';
var data = $('#myform_id').serialize();
$.post(url, data , function(result){
//... if the data was alright or submited ...
alert(result);
},"json");
isn't it easier ? :)
to append a simply type:
var newfield="<div id='rs'><textarea name='mytextarea'></div>"; $('#your_target_id').append(newfield);
in your php type
<?php print_r($_GET); ?>
and you will see what i mean :)
I cannot stress enough - use jQuery. Your life will be an order of magnitude simpler.