Dynamically added field in javascript and saving the data to mysql - javascript

Iam having a small issues with my dynamic form in javascript. when i click add supplier button, two form fields are added automatically. i can add how much fields ever i wanted. But when i click add supplier button the previously added form values are going off. What's the mistake iam doing?
<html>
<head>
<script type="text/javascript">
function addTextArea(){
var div = document.getElementById('div_quotes');
div.innerHTML += "<input type='text' name='sup_name[]' />";
div.innerHTML += "<input type='text' name='sup_email[]' />";
div.innerHTML += "\n<br />";
}
</script>
</head>
<body>
<form method="post" action="ajax.php?tender_id=<?php echo $tender_id ?>">
<div id="div_quotes"></div>
<input type="button" value="Add Supplers" onClick="addTextArea();">
<input type="submit" name="submitted">
</form>
</body>
</html>

Use appendChild() instead of innerHTML that will prevent the existing form elements from getting overwritten.
function addTextArea(){
var div = document.getElementById('div_quotes');
var temp = document.createElement('div');
temp.innerHTML ="<input type='text' name='sup_name[]' /><input type='text' name='sup_email[]' /><br />";
div.appendChild(temp );
}

Related

Javascript concat clearing input fields

function js() {
document.getElementById("example").innerHTML = document.getElementById("example").innerHTML+"<input type=\"text\" name=\"name\" />";
}
<div id="example">
<input type="text" name="name[]" />
</div>
<button type="button" onclick="js();">Click</button>
I have a form, which need variable number of input types.
<form action="" method="">
[...]
<div id="mezok">
<div id="input_id">
<input type="text" name="name" />
</div>
</div>
[...]
</form>
I add and remove further inputs (along with their divs!) via an ajax call. Javascript calls a php which generates a new input_id div, and then concatenates to the rest of the div id="mezok". Adding and removing inputs are fine as long as everything is empty. However, when I add a new div when there is something in the input, it clears the rest of the inputs.
document.getElementById("mezok").innerHTML = document.getElementById("mezok").innerHTML+http.responseText;
document.getElementById("mezok").innerHTML += http.responseText;
document.getElementById("mezok").innerHTML.concat(http.responseText);
(The last one is not working at all...)
TL;DR: concat input to input, values of inputs disappear. :'(
Don't use innerHTML. What you are doing is redrawing the entire container contents, deleting existent inputs and creating new inputs each time. My experience says that when you are accessing innerHTML, recheck your code as you are probably doing something weird.
What you have to do is to create inputs individually and append them to the container, without touching the rest of the inputs. Is like appending elements to an array.
This way the code is more self-explanatory, and better, is way more performant:
function js() {
var input = document.createElement("input"); // Create a new input element. Is like "<input>".
input.setAttribute("type", "text"); // Set the 'type' attribute to 'text'. Is like having '<input type="text">'
input.setAttribute("name", "name[]"); // Set the 'name' attribute to 'name[]'. Is like having '<input name="name[]">' but because you already have set the type, now is like having '<input type="text" name="name[]">'
document.getElementById("example").appendChild(input); // Push it to the container
}
<div id="example">
<input type="text" name="name[]" />
</div>
<button type="button" onclick="js();">Click</button>
The code below could be a solution for you. In this way you're not going to overwrite the existing inputs with the associated values while you're adding new inputs.
function js() {
var inputElementToAppend = document.createElement('input');
inputElementToAppend.innerHTML = "<input type=\"text\" name=\"name\" />";
document.getElementById("example").appendChild(inputElementToAppend.firstChild);
}
<div id="example">
<input type="text" name="name[]" />
</div>
<button type="button" onclick="js();">Click</button>
Let me know if this worked for you.
Following working fine for me.
<button onclick="myFunction()">Try it</button>
<p id="demo">ABC</p>
<script>
function myFunction() {
var x = document.getElementById("myP").innerHTML;
document.getElementById("demo").innerHTML += `<input type=\"text\" name=\"name\" />`;
}
<script>
I would recommend to use appendChild and removeChild instead of innerHTML

Function not working when called inside a div

I have a hidden form inside a div that is displayed on button click.
Inside the form I have an input text field, and a button that should call a JavaScript function that adds another input field.
If the container named "blockOfStuff" is a div, as you see it, the function doesn't work. If I change the <div> container tag into a <script> tag, then it is working...
What's wrong?
<script>
function addProceduri(divName){
c = document.getElementById("proceduri").getElementsByTagName("div").length;
var moddiv = document.createElement('div');
moddiv.innerHTML = "<input type='checkbox' value='1' name='check" + c + "'><input type='text' name='procedura" + c + "'>";
document.getElementById(divName).appendChild(moddiv);
}
</script>
<input type="button" value="ADD" onClick="addbox.innerHTML=blockOfStuff.innerHTML;">
<div id="addbox"></div>
<div id="blockOfStuff" name="blockOfStuff" style="display: none;">
<form name="adaugare" enctype="multipart/form-data" action="afisare.php?add=1" method="POST">
<div id="field"> Procedures: <input type="button" value="+" onClick="addProceduri('proceduri');">
<div id="proceduri">
<?php
echo '<div><input type="checkbox" name="check0" value="1"><input type="text" name="procedura0" value=""></div>';
?>
</div>
</div>
</form>
</div> // end of "blockOfStuff" div
When you use a div, and copy the innerHTML elsewhere, you'll have multiple elements with the same id. This is illegal and all sorts of weirdness happens.
Elements within a script tag aren't part of the "regular" document, and you don't have this conflict when they're copied.
i've changed the onclick envent into document.getElementById('blockOfStuff').style.display= 'block' and now it's working.
Thanks

Dont want to Clear text box while clicking add button

i have one requirements for adding text box while clicking button.
When i am clicking add button new text box will be created But previousely entered data in text box will be cleared.I dont want to clear the data in text box while clicking add button.
How i can resolve this problem?
html
<tr id="div"></tr>
<tr>
<td>
<button type="button" class="btn btn-lg btn-info" onclick="generateRow();">Add</button>
</td>
</tr>
JS
function generateRow() {
var d=document.getElementById("div");
d.innerHTML+=" <input class='form-control' type='text' required autofocus name='year'/> ";
}
you can use something like this in javascript
function generateRow() {
var child="<input class='form-control' type='text' required autofocus name='year'/>";
document.getElementById("div").appendChild(child);
}
function generateRow() {
var i=0,j=0;
var d=document.getElementById("div"),input,value;
//var m=document.getElementById("div");
var x=new Array(50);
while (i!=d.childNodes.length/2)
{
if (input = d.children[i]) {// If there's an input...
x[i]=input.value; // ...get the value
}
//d.children[i].value = value;
i++;
}
d.innerHTML += "<input class='form-control' type='text' required autofocus name='year'/> ";
// m.innerHTML += "<td><input type='button' required autofocus name='year' value='Remove'/> </td>";
while(j!=i)
{
d.children[j].value = x[j];
j++;
}
}
use jquery .append() to add div to the existing content
try this using pure javascript
function generateRow() {
var d=document.getElementById("div");
var f = document.createElement("input");
f.name="year";
d.appendChild(f);
}
A slightly different answer using jQuery. Might be useful for future users
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
function generateRow() {
$("#div").append("<input type='text' name='year'/><br/>");
}
</script>
</head>
<body>
<table>
<div id="div">
<!-- Buttons Go Here -->
</div>
<button type="button" onclick="generateRow();">Add</button>
</table>
</body>
</html>
JSFiddle

Pass textarea value to javascript with button onclick

I have a below PHP code to pass TextArea value to call another PHP page using button onclick. When I type some chars in the text area and click on the button, it does not take value to the mspec parameter.
echo "<TEXTAREA name=Tranrules cols=100 rows=5></TEXTAREA>"
echo "<INPUT TYPE=BUTTON VALUE=\"Add Mapping\"
onClick=\"javascript:JSopenReportWindow('sample8.php?mspec=$Tranrules');\" style=\"color:black; width:153px;\">";
Javascript is below
<script language="JavaScript">
function JSopenReportWindow(URL) {
popupWin = window.open(URL, 'Report',
'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=1,resizable=1,width=675,height=600');
popupWin.focus(); // bring window to front
}
</script>
here is a little sample of what you should be doing instead:
<script>
function popup(name){
var text = document.getElementsByName(name)[0].value;
alert(text);
}
</script>
<textarea name="Transrule"></textarea>
<input type="button" value="submit" onClick="javascript:popup('Transrule');" />
When You echo the HTML, it is HTML, so You cant access element's value by adding $ to name, You should use ID instead of Name and access it the right way.
http://jsfiddle.net/bE84a/
echo "<TEXTAREA id=Tranrules cols=100 rows=5></TEXTAREA>"
echo "<INPUT TYPE=BUTTON VALUE=\"Add Mapping\"
onClick=\"javascript:JSopenReportWindow('sample8.php?mspec='+document.getElementById('Tranrules').value);\"
style=\"color:black; width:153px;\">";

jQuery php variable problems

I'm trying to catch the correct variable in this jQuery function but whatever the button I click, the alert always shows the name of the first label that I have. Any ideas? Thank you.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$(".submit").click(function() {
var name = $("#name").val();
alert(name);
});
});
</script>
</head>
<body>
<?php
include("connection.php");
$link=connect();
$result=mysql_query("select * from names",$link);
if (mysql_fetch_array($result) == 0)
{
echo "No names registered. Add one";
}
else
{
while($row=mysql_fetch_array($result))
{
echo "<html>
<label>".$row["name"]."</label>
<input type='button' class='submit' value='Delete'>
<input type='hidden' id='name' value=".$row["name"].">
<br>
</html>";
}
mysql_free_result($result);
mysql_close($link);
}
?>
</body>
</html>
Use DOM navigation to get the value from the adjacent input:
$( document ).ready(function() {
$(".submit").click(function() {
var name = $(this).next().val();
alert(name);
});
});
Also, there should just be one <html> block in the page. Don't put that in the loop.
At first, html ID should be unique.
Try using html5 data attributes and remove your hidden form element:
while($row=mysql_fetch_array($result))
{
echo "<input type='button' class='submit' value='Delete' data-value=".$row["name"].">";
}
And JS part:
<script type="text/javascript">
$( document ).ready(function() {
$(".submit").click(function() {
alert($(this).data('value'));
});
});
You are re-using the same id - name - multiple times:
while($row=mysql_fetch_array($result))
{
echo "<html>
<label>".$row["name"]."</label>
<input type='button' class='submit' value='Delete'>
<input type='hidden' id='name' value=".$row["name"].">
<br>
</html>";
}
You should wrap your fields in individual forms (not html elements) and use the name attribute:
while($row=mysql_fetch_array($result))
{
echo "<form action='' method='post'>
<label>".$row["name"]."</label>
<input type='button' class='submit' value='Delete'>
<input type='hidden' name='name' value=".$row["name"].">
<br>
</form>";
}
This will make your form also work without javascript.
Then, in your javascript you can do:
$(".submit").click(function(e) {
e.preventDefault();
var name = $(this).closest('form').find('input[name="name"]').val();
...
Or if you need to post it using ajax afterwards:
var data = $(this).closest('form').serialize();
(or you catch the submit event of the form instead)
In addition to some of the other answers, you don't really need the hidden input. Could just change the button input to:
<input type='button' class='submit' name='".$row["name"]."' value='Delete'>
Then change your JQuery selector to:
var name = $(this).attr('name');

Categories

Resources