I have a form html which can add the form dynamically. I have problem with radio button, it can only select one option (even when the radio button is in different tag). I search the solution, one solution is to change the name of the radio button. Is there any other way to do it? Because my other input all use same name and when submit the form all input can be collected in an array.
If there's no other way, how can I change the name of the radio button for the cloned element?
Here's my code:
app.get('/form', function (req, res) {
var html='';
html += `<head>
<style>
.formset {
border-style: solid;
border-width: 1px;
}
</style>
<script>
var id=1
function myFunction() {
id++
var elmnt = document.getElementById("div1")
var cln = elmnt.cloneNode(true)
cln.id = "div"+id
document.getElementById("divParent").appendChild(cln);
}
</script>
</head>`;
html +="<body>";
html += "<p>Click the button to make a BUTTON element with text.</p>";
html += '<button onclick="myFunction()">Add form</button>';
html += "<form action='/thank' method='post' name='form1'>";
html += "<div id='divParent'>";
html += "<div id='div1' name='formset' class='formset'>";
html += "<p>Name: <input type= 'text' name='name'></p>";
html += "<p>Sex: Male <input type='radio' name='gender' value='male'>"
html += " Female <input type='radio' name='gender' value='female'></p>"
html += "<p>Email: <input type='text' name='email'></p>";
html += "<p>Address:<input type='text' name='address'></p>";
html += "<p>Mobile number:<input type='text' name='mobilno'></p>";
html += "</div>";
html += "</div>";
html += "<input id='input1' type='submit' value='submit'>";
html += "<INPUT type='reset' value='reset'>";
html += "</form>";
html += "</body>";
res.send(html);
});
And the code to handle the form:
app.post('/thank', urlencodedParser, function (req, res){
var reply='';
reply += "<br>Array length is : " + req.body.name.length;
reply += "<br>Your name is : " + req.body.name;
reply += "<br>Sex is : " + req.body.gender;
reply += "<br>Your E-mail id is : " + req.body.email;
reply += "<br>Your address is : " + req.body.address;
reply += "<br>Your mobile number is : " + req.body.mobilno;
res.send(reply);
});
I think you need change name of the radio input, add class to radio to make it can be found by getElementsByClassName.
html += "<p>Sex: Male <input type='radio' class='gender' name='gender' value='male'>"
html += " Female <input type='radio' class='gender' name='gender' value='female'></p>"
//change the name, add id to the end
function changeName(element, id) {
var x = element.getElementsByClassName("gender");
var i;
for (i = 0; i < x.length; i++) {
x[i].name += id;
}
}
function myFunction() {
id++
var elmnt = document.getElementById("div1")
var cln = elmnt.cloneNode(true)
cln.id = "div"+id
//change radio id
changeName(cln, id);
document.getElementById("divParent").appendChild(cln);
}
Related
I'm building kind of a form.
Trying to insert a button into a new div created dynamically with javascript. Apparently, the code isn't working because the new div created is a local variable inside the function that created it.
Without the additional button, the code is working fine.
The idea is that the additional button add extra inputs of the original type of input of the Form.
Any advice of how could I accomplish this?
HTML:
<div id="dynamicInputs">
</div>
Título de la pregunta: <input name="qName" type="text"><br>
Tipo: <select name="inputSelect">
<option value="text">Respuesta corta</option>
<option value="radio">Selección múltiple</option>
<option value="checkbox">Checkboxes</option>
<option value="textarea">Desarrollo</option>
</select><br>
<input type="button" class="btn btn-default btn-sm" value="Agregar pregunta" onclick="addAllInputs('dynamicInputs', document.myForm.qName.value, document.myForm.inputSelect.value)">
Javascript:
//agegar pregunta en formulario
var counterDynInput = 0;
function addAllInputs(divName, qName, inputType){
var newDiv = document.createElement('div');
var newDivName = "";
newDivName = "divInputs_" + (counterDynInput + 1);
newDiv.setAttribute("id", newDivName);
newDiv.innerHTML =
(counterDynInput + 1)
+ ". "
+ inputLabel(qName)
+ "<br>"
+ inputFields(inputType)
+ "<hr>";
addButtonToDiv(newDivName);
counterDynInput++;
document.getElementById(divName).appendChild(newDiv);
}
function inputLabel(qName){
var putStr = "";
putStr = "<input type='text' name='qLabel' value='" + qName + "' placeholder='Título de la pregunta...'>";
return putStr;
}
function inputFields(inputType){
var putStr = "";
putStr = "<input type='" + inputType + "' name='myInputs[]'><br>";
return putStr;
}
function addButtonToDiv(newDivName){
var btn = document.createElement('BUTTON');
var div = document.getElementById(newDivName);
div.appendChild(btn);
}
Basically I'm trying to populate an array with some values in text boxes. I thought I could do it by incrementing though ids, but it isn't working.
Here it is:
var sections = 0;
var mod = [];
var identifier = 0;
function addSection(){
sections++;
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
function removeSection(){
if (sections > 0){
sections--;
identifier -= 3;
document.getElementById("input").innerHTML = "";
for(i=0; i<sections; i++){
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
}
}
function calculate(){
populateArray();
}
function populateArray(){
var i,j;
for(i=0;i<sections * 3;i++){
var pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
i++;
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
i++
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
}
document.getElementById("debug").innerHTML = mod.toString();
}
<!doctype html>
<html>
<head>
<title>To Pass v1.0</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>TO PASS</h1>
<button onclick="addSection()">Add Section</button>
<button onclick="removeSection()">Remove Section</button>
<div id='input'></div>
<button onclick="calculate()">Calculate</button>
<div id='output'></div>
<div id='debug'></div>
</body>
<script type="text/javascript" src="js/main.js"></script>
</html>
Is it possible doing it my method, or will it inevitably not work for whatever reason? Doing some searches it seems jquery might be the way to go, but I'm not sure how to get started with that.
jQuery certainly simplifies things, but it can't do anything that JavaScript can't do, and many amazing websites were built long before jQuery came into existence.
In populateArray(), remove innerHTML here:
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
Should be:
mod[i] = parseInt(document.getElementById(pop).value);
You can simplify the function like this:
function populateArray() {
var i;
for(i = 0 ; i < sections * 3 ; i++) {
mod[i] = parseInt(document.getElementById(i).value);
}
document.getElementById('debug').innerHTML = mod.toString();
}
In addSection(), this wipes out the values of existing input elements:
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
Instead, you should create new input elements and append them.
Here's a rewrite of the function:
var input= document.getElementById('input');
function addSection(){
var inp, i;
sections++;
for(var i = 0 ; i < 3 ; i++) {
inp= document.createElement('input');
inp.type= 'text';
inp.id= identifier++;
input.appendChild(inp);
}
input.appendChild(document.createElement('br'));
} //addSection
In removeSection(), values of all input elements are wiped out.
Instead of rewriting that function, I've done a complete rewrite or your program, without any global variables and without assigning IDs to the input elements.
If you have any questions, I'll update my answer with explanations.
Snippet
function addSection() {
var input= document.getElementById('input'),
sect= document.querySelector('section');
input.appendChild(sect.cloneNode(true));
}
function removeSection() {
var input= document.getElementById('input'),
sects= document.querySelectorAll('section');
if(sects.length > 1) {
input.removeChild(sects[sects.length-1]);
}
}
function calculate() {
var inp= document.querySelectorAll('section input'),
debug= document.getElementById('debug'),
mod= [],
i,
val;
for(i = 3 ; i < inp.length ; i++) {
val= parseInt(inp[i].value);
mod.push(val || 0);
}
debug.innerHTML = mod.toString();
}
section:first-of-type {
display: none;
}
<button onclick="addSection()">Add Section</button>
<button onclick="removeSection()">Remove Section</button>
<div id='input'>
<section>
<input type="text">
<input type="text">
<input type="text">
</section>
</div>
<button onclick="calculate()">Calculate</button>
<div id='output'></div>
<div id='debug'></div>
This version of your script stores the actual elements in an array of sections. That way you can loop through them as you would an array, and alter the contents that way.
Here's a pen of the code: looping through added elements
var sections = [];
var output = document.getElementById('input');
function addSection(){
var section = document.createElement('div');
for (var i = 0; i < 3; i++) {
el = document.createElement('input');
el.type = 'text';
section.appendChild(el);
}
sections.push(section);
output.appendChild(section);
}
function removeSection(){
if (sections.length > 0){
output.removeChild(sections.pop())
}
}
function calculate(){
populateArray();
}
function populateArray(){
for (var i = 0; i < sections.length; i++) {
for (var j = 0; j < sections[i].children.length; j++ ) {
sections[i].children[j].value = (i+1) * (j+2);
}
}
}
If your problem is the NaN, this is because you select an input field and then first try to read its innerHtml before reading its value. Read values of inputs directly.
var sections = 0;
var mod = [];
var identifier = 0;
function addSection(){
sections++;
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
function removeSection(){
if (sections > 0){
sections--;
identifier -= 3;
document.getElementById("input").innerHTML = "";
for(i=0; i<sections; i++){
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
}
}
function calculate(){
populateArray();
}
function populateArray(){
var i,j;
for(i=0;i<sections * 3;i++){
var pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).value);
i++;
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).value);
i++
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).value);
}
document.getElementById("debug").innerHTML = mod.toString();
}
<!doctype html>
<html>
<head>
<title>To Pass v1.0</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>TO PASS</h1>
<button onclick="addSection()">Add Section</button>
<button onclick="removeSection()">Remove Section</button>
<div id='input'></div>
<button onclick="calculate()">Calculate</button>
<div id='output'></div>
<div id='debug'></div>
</body>
<script type="text/javascript" src="js/main.js"></script>
</html>
So what I am trying to achieve is to increment the points".$id." in the javascript code below starting from 0 like points+n and it would be a dynamic value according to rows in a table. Same for the value 'button".$id."' and all this is because of styled radiobutton labels that are looped etc.
So all I want to do is get rid of all the hardcoded different var txt1 to txt+n, button0 to button+n and points0 to points+n in the JavaScript function.
The real problem here for me is the line: var buttons1 = document.forms[0].button0; how to replace the 0 in button0 to the 'i' in a for loop. Someting like button + i won't work.
Oh and what I'm trying to do is get the values from the radiobuttons to a textarea with one buttongroup and textarea per tablerow.
The code below works for the first 7 rows in my table...
echo "
<td>
<div class='radio'>
<input id='".$temp1."' type='radio' name='button".$id."' onclick='myFunction()' value='4'>
<label for='".$temp1."'></label>
<input id='".$temp2."' type='radio' name='button".$id."' onclick='myFunction()' value='3'>
<label for='".$temp2."'></label>
<input id='".$temp3."' type='radio' name='button".$id."' onclick='myFunction()' value='2'>
<label for='".$temp3."'></label>
<input id='".$temp4."' type='radio' name='button".$id."' onclick='myFunction()' value='1'>
<label for='".$temp4."'></label>
</div>";
echo"<textarea id='points".$id."' name='points".$id."' cols='1' rows='1' ;> </textarea>
</td>
</tr>";
The Javascript function:
function myFunction() {
var txt1 ='';
var txt2 ='';
var txt3 ='';
var txt4 ='';
var txt5 ='';
var txt6 ='';
var txt7 ='';
var buttons1 = document.forms[0].button0;
var buttons2 = document.forms[0].button1;
var buttons3 = document.forms[0].button2;
var buttons4 = document.forms[0].button3;
var buttons5 = document.forms[0].button4;
var buttons6 = document.forms[0].button5;
var buttons7 = document.forms[0].button6;
var buttons8 = document.forms[0].button7;
for (var i = 0; i < 4; i++) {
if (buttons1[i].checked) {
txt1 = txt1 + buttons1[i].value + " ";
}
if (buttons2[i].checked) {
txt2 = txt2 + buttons2[i].value + " ";
}
if (buttons3[i].checked) {
txt3 = txt3 + buttons3[i].value + " ";
}
if (buttons4[i].checked) {
txt4 = txt4 + buttons4[i].value + " ";
}
if (buttons5[i].checked) {
txt5 = txt5 + buttons5[i].value + " ";
}
if (buttons6[i].checked) {
txt6 = txt6 + buttons6[i].value + " ";
}
if (buttons7[i].checked) {
txt7 = txt7 + buttons7[i].value + " ";
}
}
document.getElementById("points0").value = txt1;
console.log(txt1);
document.getElementById("points1").value = txt2;
console.log(txt2);
document.getElementById("points2").value = txt3;
console.log(txt3);
document.getElementById("points3").value = txt4;
console.log(txt4);
document.getElementById("points4").value = txt5;
console.log(txt5);
document.getElementById("points5").value = txt6;
console.log(txt6);
document.getElementById("points6").value = txt7;
console.log(txt7);
}
i think what you need is use the "eval" function in javascript
try the following
var buttons1;
var buttons2;
var buttons3;
var buttons4;
var buttons5;
var buttons6;
var buttons7;
var buttons8;
var j;
for(var i=0;i<8;i++){
j=i+1;
eval("buttons" +j+ " = document.forms[0].button" +i+ ";");
}
If i understood correctly,
Try something like this:
change your onclick as following:
<input id='".$temp4."' type='radio' name='button".$id."' onclick='myFunction(this)' value='1'>
and change function :
function myFunction(button){
var name= button.name;
var id= name.split('button')[1];;
document.getElementById("points"+id).value = buttons.value +" ";
}
I try to make web app for creating radio button questions (like survey). The problem is defining the array of radio button options in order to call it on php page and display it in the desirable order.
In my example below, I only got one radio button of each question, and I want to display all radio buttons input on the index.html page.
This should work like this: User opens index.html, there he add the first question (button Add Question) and the proposal of answers (for example 3, which he will get by pressing the Add option button and inserting text of it). The same he should do and for the question number 2, etc...
After that, by clicking PROCEED, it should lead him to the process.php page where the survey will display radio buttons questions. But there is a mistake, please see it on the link or in the code below:
LINK FOR TESTING
index.html
<script src="script.js"></script>
<form action="http://www.balkanex.info/atest/radio/process.php" method="post">
Here is the page with which you can add your new radio button questions for survey.
<input type="button" value="ADD NEW QUESTION" onclick="addradio();">
<div id="mydiv"></div>
<br/>
<input type="submit" name="submit" value="PROCEED"><br/>
</form>
script.js
n=1;
var m = 1;
var moreradio = '<br/><input type="button" onclick="addmoreradio()" value="Add option">';
function addradio() {
m = 1;
var textarea = document.createElement("textarea");
textarea.name = "question[" + n + "]";
textarea.rows = 1;
textarea.cols = 60;
var div = document.createElement("div");
div.innerHTML = n + '. Question: ' + '<br />' + 'Que: ' + textarea.outerHTML + moreradio + '<br/><div id="opid' + n + '"' + '></div><br /><br/>';
document.getElementById("mydiv").appendChild(div);
n++;
r = n-1;
}
function addmoreradio() {
var radio = '<input type="text" name="tag' + r + m + '"><br/>';
document.getElementById("opid"+r).innerHTML += radio;
m++
}
process.php
<?php
$question = $_POST['question'];
$length = count($_POST['question']);
$r=1;
for($j=1; $j<$length+1; $j++) {
if($_POST['question'][$j] != "") {
$radioarray = $_POST['tag'];
$area = '<input type="radio" name="'.$r.'" value="'.$r.'">'.$radioarray$j$r.'<br/>';
$bla .= $j.') '.$question[$j].'<br/>'.$area.'<br/><br/>';
$r++;
}}
$content = $bla;
echo $content;
?>
You can did a mistake on form side while naming elements. Also you did mistake on backend while iterating. You can use following;
JS:
<script>
var m = 0;
function addradio() {
var textarea = document.createElement("textarea");
textarea.name = "question[]";
textarea.rows = 1;
textarea.cols = 60;
var div = document.createElement("div");
div.innerHTML = m + '. Question: ' + '<br />' + 'Que: ' + textarea.outerHTML + '<br/><input type="button" onclick="addmoreradio(' + m + ')" value="Add option">' + '<br/><div id="opid' + m + '"' + '></div><br /><br/>';
document.getElementById("mydiv").appendChild(div);
m++;
}
function addmoreradio(question_id) {
var radio = '<input type="text" name="tag' + question_id + '[]"><br/>';
document.getElementById("opid" + question_id).innerHTML += radio;
}
</script>
HTML:
<script src="script.js"></script>
<form action="http://www.balkanex.info/atest/radio/process.php" method="post">
Here is the page with which you can add your new radio button questions for survey.
<input type="button" value="ADD NEW QUESTION" onclick="addradio();">
<div id="mydiv"></div>
<br/>
<input type="submit" name="submit" value="PROCEED"><br/>
</form>
PHP:
<?php
$question = $_POST['question'];
$content = '';
foreach ($question as $k => $v) {
$area = '';
$options = $_POST["tag" . $k];
foreach ($options as $key => $val) {
$area .= '<input type="radio" name="tag[]" value="'. $key .'">' . $val . '<br/>';
}
$content .= $k + 1 . ') ' . $question[$k].'<br/>'.$area.'<br/><br/>';
}
echo $content;
?>
I'm creating file(images) upload form.
I want to add input elements by clicking on button.
This is my input:
<input type="file" name="file"/>
I've alerady write some code:
<script language="javascript">
fields = 0;
function addInput() {
if (fields < 10) {
document.getElementById('text').innerHTML += "<input type="file" name="file"/><br />";
fields += 1;
} else {
document.getElementById('text').innerHTML += "<br />Only 10 upload fields allowed.";
document.form.add.disabled=true;
}
}
</script>
But it's ugly and not works...
I have prototype library and want to use it to add inputs.
So i need a button to add given inputs and on more button near every input to remove it - like when you attaching files to your mail.
[See it in action]
HTML
<div id="text"></div>
<div id="warning"></div>
Javascript
fields = 0;
function addInput() {
if (fields < 10) {
var id = "file" + fields;
document.getElementById('text').innerHTML +=
"<div><input type='file' name='"+id+"' />" +
" <a href='#' onclick='removeInput(this.parentNode)' />remove</div>";
fields += 1;
} else {
document.getElementById('warning').innerHTML =
"Only 10 upload fields allowed.";
document.form.add.disabled = true;
}
}
function removeInput( el ) {
if (fields > 0) {
document.getElementById('warning').innerHTML = "";
var parent = document.getElementById('text');
parent.removeChild(el);
fields -= 1;
}
}
I think problem with use of "
document.getElementById('text').innerHTML += "<input type="file" name="file"/><br />";
should be
document.getElementById('text').innerHTML += "<input type='file' name='file'/><br />";
To remove field
document.getElementById('text').innerHTML += "<div id='div_"+fields+"'><input type='file' name='file'/><br /><a onclick='removeDiv(/""+fields+"/")' href='javascript:void(0)'>Remove</a></div>";
and add javasript function
function removeDiv(val)
{
var d = document.getElementById('text');
var olddiv = document.getElementById("div_"+id);
d.removeChild(olddiv);
fields-=1; //this should be done to decrement count
}