Create text-input on button click in form - javascript

I want to create another input field, everytime the button "+" inside the form is clicked. I searched for a solution but i can't find anything. The input field should be created inside the form over the "+" button.
Here is my current code:
<div class="row">
<div class="col-md-12">
<form method="post" id="create-form" action="create.php" enctype="multipart/form-data">
<?php
/* getting sample questions */
/* checks result and creates variables from result */
if ($sampleamount > 0) { // amount
$samplequery->bind_result($questionid_sample, $question_sample);
while ($samplequery->fetch()) { // while page can use this variables
/* echo text-box, value from db */
$required = $questionid_sample === 1 ? "required" : ""; // one question is always required
echo "<input class='question-box' type='text' name='" . $questionid_sample . "' placeholder='Write your question in here.' maxlength='255' size='70' value='" . $question_sample . "'" . $required . "> <br>";
}
} else {
/* no result (db=sample_question) */
header('Location: ../index.php');
}
$samplequery->close();
closeDB($conn);
/* adds more input for user */
for ($i = ($sampleamount + 1); $i <= ($additionalquestions + $sampleamount); $i++) {
echo "<input class='question-box' type='text' name='" . $i . "' placeholder='Write your question in here.' maxlength='255' size='70'> <br>";
}
?>
<br>
<input class="createsurvey2" type="button" id="addqbtn" name="addqbtn" value="+" >
<br>
<input class="createsurvey2" type="submit" name="btnSubmit" value="Create Survey!" >
</form>
</div>
</div>
</div>
<script>
function addquestion() {
var counter = 2;
var addqbtn = document.getElementById('addqbtn');
var form = document.getElementById('create-form');
var addInput = function() {
counter++;
var input = document.createElement("input");
input.id = 'additionalquestion-' + counter;
input.type = 'text';
input.class = 'question-box';
input.name = 'name';
input.placeholder = 'Write your question in here.';
form.appendChild(input);
};
addqbtn.addEventListener('click', function(){
addInput();
}.bind(this));
};
</script>

<html>
<body>
<button onclick="createNewFiled()" id="incrementBtn" type="button">Click here</button>
<form id="form" action="">
</form>
</body>
</html>
<script type="text/javascript">
var counter = 0;
var incrementBtn = document.getElementById('incrementBtn');
var form = document.getElementById('form');
var createNewFiled = function() {
counter++;
var input = document.createElement("input");
var br = document.createElement("br"); // If you need new line after each input field
input.id = 'input-' + counter;
input.classList.add("inputClass");
input.type = 'text';
input.name = 'name'+counter;
input.placeholder = 'Input field ' + counter;
form.appendChild(input);
form.appendChild(br); // If you need new line after each input field
};
</script>

Related

onclick() event is not working in javascript and span tag

I have written the below code to display textarea in the form but it is not working in javaascript. the real requirement is when i click on reply in span tag a text area with a button should appear but it is not happening. Is it happening because the script part is below the span tag or something else is the reason for it just asking.
echo "<center>";
echo "<span class=c20 id=like1>Like</span>";
echo "<span class=c21 id=reply1 onclick='myFunction()'>Reply</span>";
echo "<span class=c22 id=display1>Display</span>";
echo "</center>";
echo "<br><br>";
echo "<span id=reply3></span>";
echo "<br><br>";
'$row01["Email"]'; '$row01["Name"]'; '$row01["Message"]'; '$row01["Picture"]'; '$row01["Status"]'; '$replybymail'; '$replybyname'; '$row01["Password"]';
<script type="text/javascript">
document.getElementById("reply1").addEventListener("click", myFunction);
function myFunction() {
reply();
}
function reply() {
var x = document.getElementById("reply3").value;
var email1 = document.getElementById("i1").value;
var pass1 = document.getElementById("i8").value;
var name1 = document.getElementById("i2").value;
var pict1 = document.getElementById("i4").value;
var status1 = document.getElementById("i5").value;
var message1 = document.getElementById("i3").value;
var replybymail1 = document.getElementById("i6").value;
var replybyname1 = document.getElementById("i7").value;
var email;
var picture;
var name;
var status;
var password;
var mess;
var replybymail;
var replybyname;
var url= 'profileto.php?email='+ email1+'&picture='+ pict1+'&name='+ name1+'&status=' + status1+'&password='+ pass1+'&mess=' + message1+'&replybymail='+ replybymail1 +'&replybyname='+ replybyname1+' ';
var forms = "<form id='replyform' method='POST' class='form1' onsubmit = 'myFunction2()'>
<center><textarea cols='40' rows='50' class = 'c61' name='reply' style= 'height: 27px'></textarea></center><br>
<center><input type='submit' value ='Reply' class='c60'></center></form><br><br>";
document.getElementById("reply3").innerHTML = forms;
document.getElementById("replyform").action = url;
if(x.style.display === "none" )
{
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function myFunction2()
{
alert("Your post is published");
}
</script>
The problem is that you are getting the element to set OnClickListener
JS is not able to find the element!
You are not using inverted commas when set attribute value.
Change this line:
echo "<span class=c21 id=reply1 onclick='myFunction()'>Reply</span>";
To:
echo "<span class=\"c21\" id=\"reply1\" onclick='myFunction()'>Reply</span>";
\ is used to escape " OR '.
Always add \ before " OR '. Like this \".
Not like this "\.

JS - How to add three inputs, get the text from them and show the text in another subpage

I have a problem with adding three input text fields after I put one button.
I'd like to have three new input fields after i push the button "Add author" - these inputs would be: 1. name 2. surname 3. initial. Everyone new input needs to have a different id in order to take the text from the inputs and show it in the new subpage which has to show up right after I push the button "Make the order".
<!DOCTYPE HTML>
<html lang='en'>
<head>
<meta charset='utf-8'>
<link rel='stylesheet' href='css/style.css'>
<script type="text/javascript">
window.onload = Load;
function Load()
{
document.getElementById('add_input').onclick = AddElement;
}
function AddElement()
{
var element = document.createElement('input');
var element2 = document.createElement('input');
var element3 = document.createElement('input');
element.setAttribute('type', 'text');
element.setAttribute('type', 'text');
element.setAttribute('type', 'text');
var number = 0;
var amount = document.forms['add_file'].elements.length;
for (var i = 0; i < ilosc; i++ )
{
if (document.forms['add_file'].elements[i].type == 'text')
{
number += 1;
}
}
element.setAttribute('name', 'file-'+(liczba+1));
element.setAttribute('nazwisko', 'file-'+(liczba+1));
element.style.display = "block";
element.style.margin= "2px";
document.forms['add_file'].appendChild(element);
}
</script>
<!--making order -->
<script>
function getText(){
var publisher = document.getElementById("publisher");
var year = document.getElementById("year");
var div = document.getElementById("readyorder")
div.innerHTML = "("+surname.value+" "+year.value+","+" "+"s."+" "+page.value+")";
}
</script>
</head>
<body>
<div class='container'>
<!-- header -->
<header>
<img src="images/header.jpg" alt=""/>
</header>
<input type="text" name="file-1" />
<input type="text" name="surname-1" />
<input type="submit" value="Add author" id="add_input" />
<form name="add_file" enctype="multipart/form-data" method="post">
</form>
Author's Surname<br>
<input type="text" id="surname"><br>
Page number<br>
<input type="text" id="page"><br>
Year<br>
<input type="text" id="year"><br/>
<input type="submit" value="Make the order" onclick="getText()" /> <br/><br/>
<div id="readyorder"></div><br/>
</body>
</html>
Store your id globaly and increase on each addition.
While Creating your node set their id value using setAttribute
element1.setAttribute('id', 'surname' + number);
Also Create a button while adding textbox's which let you know current order.
var button = document.createElement('input');
Add onclick attribute to call javascript function
button.setAttribute('onclick', 'getText(' + number + ')');
window.onload = Load;
var number = 0;
function Load()
{
document.getElementById('add_input').onclick = AddElement;
}
function AddElement()
{
var element1 = document.createElement('input');
var element2 = document.createElement('input');
var element3 = document.createElement('input');
var label1 = document.createElement('label');
var label2 = document.createElement('label');
var label3 = document.createElement('label');
var button = document.createElement('input');
label1.innerHTML = "</br>Author's Surname " + number + "</br>";
element1.setAttribute('type', 'text');
element1.setAttribute('id', 'surname' + number);
element1.setAttribute('placeholder', 'Surname...');
label1.appendChild(element1);
label2.innerHTML = '</br>Page number ' + number + '</br>';
element2.setAttribute('type', 'text');
element2.setAttribute('id', 'page' + number);
element2.setAttribute('placeholder', 'Page...');
label2.appendChild(element2);
label3.innerHTML = '</br>Year ' + number + '</br>';
element3.setAttribute('type', 'text');
element3.setAttribute('id', 'year' + number);
element3.setAttribute('placeholder', 'Year...');
label3.appendChild(element3);
button.setAttribute('onclick', 'getText(' + number + ')');
button.setAttribute('type', 'button');
button.setAttribute('value', 'Button ' + number);
document.forms['add_file'].appendChild(label1);
document.forms['add_file'].appendChild(label2);
document.forms['add_file'].appendChild(label3);
document.forms['add_file'].appendChild(button);
number++;
}
function getText(id)
{
var surname = document.getElementById("surname" + id);
var page = document.getElementById("page" + id);
var year = document.getElementById("year" + id);
var div = document.getElementById("readyorder")
div.innerHTML = "("+surname.value+" "+year.value+","+" "+"s."+" "+page.value+")";
}
<input type="text" name="file-1" />
<input type="text" name="surname-1" />
<input type="submit" value="Add author" id="add_input" />
<form name="add_file" enctype="multipart/form-data" method="post">
</form>
<hr>
<div id="readyorder"></div><br/>

PHP $_POST can't read values set by jQuery val()

I created a little script which allows users to shadow some input values from other inputs. The JavaScript part is working fine, but now when I'm trying to send the form, it doesn't send it, saying that the field the value is copied to is empty. What's the problem here? Thanks!
$(document).ready(function()
{
$(":text").blur(function()
{
var input = $(this);
var id = input.attr("id");
var fieldname = "#".concat(id);
for (i = 0; i < fields.length; i++)
{
if (fields[i][4] == id)
{
var boxname = "#copy_".concat(fields[i][0]);
if ($(boxname).prop("checked"))
{
var fieldname2 = "#".concat(fields[i][0]);
$(fieldname2).val($(fieldname).val());
}
}
}
});
$(":checkbox").change(function()
{
var input = $(this);
var id = input.attr("id");
id = id.substring(id.indexOf("_") + 1, id.length);
var fieldname = "#".concat(id);
var checked = input.prop("checked");
$(fieldname).prop("disabled", checked);
var field = FindField(0, fields[FindField(0, id)][4]);
if (checked)
{
var fieldname2 = "#".concat(fields[field][0]);
$(fieldname).val($(fieldname2).val());
}
});
});
function FindField(index, value)
{
for (i = 0; i < fields.length; i++)
{
if (fields[i][index] == value) return i;
}
return -1;
}
The form (without some irrelevant stuff):
<form method="post" action="sendform.php">
<table>
<?php
foreach ($fields as $field)
{
if ($field[0] == "divider") echo('<tr><td colspan="2"><hr /></td></tr>');
else
{
switch ($field[2])
{
case FIELD_TEXT:
{
echo('<tr><td><label for="' . $field[0] . '">' . $field[1] . ': </label></td><td>');
if ($field[4] != "")
{
foreach ($fields as $field2)
{
if ($field2[0] == $field[4])
{
echo('<input type="checkbox" id="copy_' . $field[0] . '" title="Kopeeri väljalt "' . $field2[1] . '"" />');
}
}
}
echo('<input type="text" id="' . $field[0] . '" name="' . $field[0] . '" placeholder="' . $field[1] . '" /></td></tr>');
break;
}
}
}
}
?>
<tr><td colspan="2"><hr /></td></tr>
<tr>
<td colspan="2" style="text-align: center;">
<input type="submit" value="Saada avaldus" name="saadaavaldus" />
</td>
</tr>
</table>
</form>
A sample of the fields array:
var fields = <?php echo json_encode($fields); ?>
$fields = array
(
// ID/name label/placeholder type regex field copied from
array( "saatjanimi", "Teie täisnimi", FIELD_TEXT, "^[-,.'\s\pL]*\pL[-,.'\s\pL]\s+[-,.'\s\pL]*\pL[-,.'\s\pL]*$", ""),
array( "meiliaadress", "Teie meiliaadress", FIELD_TEXT, "^([\pL-.\d]+)#([\pL-.\d]+)((\.(\pL){2,63})+)$", ""),
array( "isanimi", "Lapse isa täisnimi", FIELD_TEXT, "^[-,.'\s\pL]*\pL[-,.'\s\pL]\s+[-,.'\s\pL]*\pL[-,.'\s\pL]*$", "saatjanimi")
);

How to handle javascript made inputs

I have a problem, i searched for the solution all over the internet, but i couldn't find it out :S
The problem is:
I'm creating file inputs on button click, but i can't handle these javascript made inputs because they aren't in my $_FILES array after i click on submit..
My code is:
HTML:
<form name = "galleryupload_form" method = "post" action = "#" enctype="multipart/form-data">
<ul id = "formul">
</ul>
<input type="button" value="Még egy kép feltöltése" onClick="addInput('formul');">
<input name = "galleryupload_submit" type = "submit" value = "Küldés"/>
</form>
javascript:
var counter = 0;
var limit = 5;
function addInput(ulName) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
var newli = document.createElement('div');
newli.innerHTML = "<label for = ''>Fájl " + (counter + 1) + "</label><input type='file' name='files[]'>";
document.getElementById(ulName).appendChild(newli);
counter++;
}
}
If you now the solution, please let me know. Thank you.
Referring to the question before editing:
File inputs appear in $_FILES not $_POST.
After editing, I cannot reproduce the problem.
check this code .
<?php
if(isset($_POST['galleryupload_submit'])){
print_r($_FILES);
}
?>
<form name = "galleryupload_form" method = "post" action = "" enctype="multipart/form-data">
<ul id = "formul">
</ul>
<input type="button" value="My textbox goes" onClick="addInput('formul');">
<input name ="galleryupload_submit" type ="submit" value ="Click Add"/>
</form>
<script>
var counter = 0;
var limit = 5;
function addInput(ulName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}else {
var newli = document.createElement('div');
newli.innerHTML = "<label for = ''>New TexBOx " + (counter + 1) +"</label><input type='file' name='files[]'>";
document.getElementById(ulName).appendChild(newli);
counter++;
}
}
</script>

Multiple input fields using JS

Got the following JS code:
<script language="javascript">
fields = 0;
pNR = 0;
err = 0;
function addInput() {
if (fields != 40) {
document.getElementById('text').innerHTML += "<input type='text' name='first" + pNR + "' value='' /><input type='text' name='second" + pNR + "' value='' /><br />";
fields += 1;
pNR += 1;
} else {
if (err == 0) {
document.getElementById('text').innerHTML += "<br />Adaugati maxim 40 ingrediente.";
err = 1;
}
document.form.add.disabled = true;
}
}
</script>
and the following HTML:
<input name="name" style="color:#ffffff;" class="name required" type="button" onclick="addInput()" value="Add" />
<div id="text">
</div>
By default, there are no fields. When I press the Add button (fields are added two by two with different names), fill in the fields and click again the Add button, the filled fields are emptied. What did I do wrong?
You aren't simply adding new inputs.
You are:
converting the existing ones to HTML (the value attribute is unchanged, it will still have the default value, not the current value)
adding the HTML for the new inputs to it
generating new DOM elements from that HTML.
Don't use innerHTML. Use createElement, appendChild and friends.
This:
document.getElementById('text').innerHTML += "<input type='text' name='first" + pNR + "' value='' /><input type='text' name='second" + pNR + "' value='' /><br />";
Becomes this:
var firstInput = document.createElement("input");
var secondInput = document.createElement("input");
firstInput.type = secondInput.type = "text";
firstInput.name = "first" + pNR;
secondInput.name = "second" + pNR;
var text = document.getElementById("text");
text.appendChild(firstInput);
text.appendChild(secondInput);
text.appendChild(document.createElement("br"));
And, for the else case:
var text = document.getElementById("text");
text.appendChild(document.createElement("br"))
text.appendChild(document.createTextNode("Adaugati maxim 40 ingrediente."));
Working example: http://jsbin.com/OqIWeMum/2/edit

Categories