Javascript function ASP <body onload="form1.submit();"> is not submitting the form below once the page have loaded.
<script type="text/javascript">
$(function() {
var count = 20;
$.extend($.wordStats.stopWords, {'retrieved': true, '2007': true});
$.wordStats.computeTopWords(count);
var msgsubmit = '<input type="submit" name="button" id="button" value="Submit" />'
var msgform = '<html><body onload="form1.submit();"><form id="form1" name="form1" method="post" action="get_page_2.asp">\n'
var msg = 'Keywords: <textarea name="g_seo_no_keywords" id="g_seo_no_keywords" cols="120" rows="3">';
var msgend = '</textarea>\n';
var msgg_seo_no_title = '<input type="text" name="g_seo_no_title" id="g_seo_no_title" value="title" />'
var msgg_seo_no_title_count = '<input type="text" name="g_seo_no_title_count" id="g_seo_no_title_count" value="0" />'
var msgg_seo_no_keywords_count = '<input type="text" name="g_seo_no_keywords_count" id="g_seo_no_keywords_count" value="0" />'
var msgg_page_no = '<input type="text" name="g_page_no" id="g_page_no" value="<%=(Request.Form("g_page_no"))%>" />'
var msgg_page_site = '<input type="text" name="g_page_site" id="g_page_site" value="<%= Request.Form("g_page_site") %>" />'
var msgg_page_url = '<input type="text" name="g_page_url" id="g_page_url" value="<%= Request.Form("g_page_url") %>" />'
var msgcounttext = 'Word Count: <input type="text" name="g_seo_no_description_count" id="g_seo_no_description_count" value="<%= counttext %>" />\n';
var msgg_seo_no_textcount = 'Word Count: <input type="text" name="g_seo_no_textcount" id="g_seo_no_textcount" value="<%= counttext %>" />\n';
var msgcounttext1 = '<textarea name="g_seo_no_description" id="g_seo_no_description" cols="120" rows="15"><%=completehtml%></textarea>\n'
for(var i = 0, j = $.wordStats.topWords.length; i < j && i <= count; i++) {
msg += $.wordStats.topWords[i].substring(1) + ', ';
}
var msgformend ='</form></body></html>\n'
document.write(msgform)+document.write(msg)+document.write(msgend)+document.write(msgg_page_no)+document.write(msgg_page_site)+document.write(msgg_page_url)+document.write(msgg_seo_no_textcount)+document.write(msgg_seo_no_title)+document.write(msgg_seo_no_title_count)+document.write(msgg_seo_no_keywords_count)+document.write(msgcounttext)+document.write(msgsubmit)+document.write(msgcounttext1)+document.write(msgformend);
$.wordStats.clear();
});
</script>
Hi There I am hoping that someone can help me to find the solution why this form is not getting submitted when the page loads.
How would I go about to submit this page? It is supposed to be an autosubmit
Thanks
Try using document.form1.submit() or document.forms.form1.submit() instead
After this line
$.wordStats.clear();
try
$("#form1").submit();
Related
I have disabled my submit button to avoid submission when textbox are not filled. I have multiple dynamic textbox where the function works correctly. But upon adding another row of textboxes, the submit button is already enabled. How can I still disable the textboxes when the user decides to add another row? I need the submit button to be enabled whenever all the textboxes are filled, after and before adding another row.
<html>
<head>
<script>
function addRow(){
var table = document.getElementById("bod");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = '<input type="text" name="purpose_dy[]" id="purpose" size="20" onkeyup="success()"/>';
row.insertCell(1).innerHTML = '<input type="text" name="wafernum_dy[]" id="wafernum" size="20" onkeyup="success()"/>';
row.insertCell(2).innerHTML = '<input type="text" name="cell_dy[]" id="cell" size="20" onkeyup="success()"/>';
row.insertCell(3).innerHTML = '<input type="text" name="qty_dy[]" id="qty" size="20" onkeyup="success()"/>';
row.insertCell(4).innerHTML = '<input type="text" name="remarks_dy[]" id="remarks" size="20" onkeyup="success()"/>';
row.insertCell(5).innerHTML = '<input type="button" value="Delete" onClick="Javacsript:deleteRow(this)"/>';
}
function success() {
if(document.getElementById("uname").value==="" || document.getElementById("age").value==="" || document.getElementById("purpose").value==="" || document.getElementById("wafernum").value==="" || document.getElementById("cell").value==="" || document.getElementById("qty").value==="" || document.getElementById("remarks").value==="") {
document.getElementById('submit_form').disabled = true;
} else {
document.getElementById('submit_form').disabled = false;
document.getElementById('submit_form').style.backgroundColor="yellow";
}
}
</script>
<style>
</style></head>
<body>
Name: <input type="text" id="uname" />
Age: <input type="text" id="age" />
<input type= "button" id= "add" value="Add" onclick= "Javascript:addRow();" >
<table id= "bod">
<tr>
<th>PURPOSE</th>
<th>WAFERNUM</th>
<th>CELL</th>
<th>QTY</th>
<th>REMARKS</th>
</tr>
</table>
<input type = "submit" name = "submit" id= "submit_form" value = "Submit" onclick="SaveData()" disabled>
</body>
</html>
Alright i fixed your error , you had some issues where you were enbaling the button and disabling , its always better to itrate and check through the loop rather than going and checking if every element is empty , check the bellow answer and the fiddle . let me know if it works . The edited script part is below , replace it with yours it should work .
<script>
function addRow() {
var table = document.getElementById("bod");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = '<input type="text" name="purpose_dy[]" class = "uname" id="purpose" size="20" onkeyup="success()"/>';
row.insertCell(1).innerHTML = '<input type="text" name="wafernum_dy[]" class = "wafernum" id="wafernum" size="20" onkeyup="success()"/>';
row.insertCell(2).innerHTML = '<input type="text" name="cell_dy[]" class = "cell" id="cell" size="20" onkeyup="success()"/>';
row.insertCell(3).innerHTML = '<input type="text" name="qty_dy[]" class = "qty" id="qty" size="20" onkeyup="success()"/>';
row.insertCell(4).innerHTML = '<input type="text" name="remarks_dy[]" class = "remarks" id="remarks" size="20" onkeyup="success()"/>';
row.insertCell(5).innerHTML = '<input type="button" value="Delete" onClick="Javacsript:deleteRow(this)"/>';
}
function success() {
// get all the elements present in form
var unameArray = document.getElementsByClassName("uname");
var ageArray = document.getElementsByClassName("age");
var cellArray = document.getElementsByClassName("cell");
var qtyArray = document.getElementsByClassName("qty");
var wafernumArray = document.getElementsByClassName("wafernum");
var purposeArray = document.getElementsByClassName("purpose");
var remarksArray = document.getElementsByClassName("remarks");
// Check for number of tr
var rowCount = document.getElementById("bod").rows.length;
var bt = document.getElementById('submit_form');
var ele = document.getElementsByTagName('input');
for(var i=0;i<ele.length;i++) {
if (ele[i].type == 'text' && ele[i].value == '') {
bt.disabled = true; // Disable the button.
return false;
}
else {
bt.disabled = false; // Enable the button.
}
}
}
</script>
Modify your conditions a little bit. Now it is working as desired
<html>
<head>
<script>
function addRow() {
var table = document.getElementById("bod");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = '<input type="text" name="purpose_dy[]" class = "uname" id="purpose" size="20" onkeyup="success()"/>';
row.insertCell(1).innerHTML = '<input type="text" name="wafernum_dy[]" class = "wafernum" id="wafernum" size="20" onkeyup="success()"/>';
row.insertCell(2).innerHTML = '<input type="text" name="cell_dy[]" class = "cell" id="cell" size="20" onkeyup="success()"/>';
row.insertCell(3).innerHTML = '<input type="text" name="qty_dy[]" class = "qty" id="qty" size="20" onkeyup="success()"/>';
row.insertCell(4).innerHTML = '<input type="text" name="remarks_dy[]" class = "remarks" id="remarks" size="20" onkeyup="success()"/>';
row.insertCell(5).innerHTML = '<input type="button" value="Delete" onClick="Javacsript:deleteRow(this)"/>';
}
function success() {
// get all the elements present in form
var unameArray = document.getElementsByClassName("uname");
var ageArray = document.getElementsByClassName("age");
var cellArray = document.getElementsByClassName("cell");
var qtyArray = document.getElementsByClassName("qty");
var wafernumArray = document.getElementsByClassName("wafernum");
var purposeArray = document.getElementsByClassName("purpose");
var remarksArray = document.getElementsByClassName("remarks");
// Check for number of tr
var rowCount = document.getElementById("bod").rows.length;
for(var i=0;i<rowCount;i++) {
var uname = unameArray[i];
var age = ageArray[i];
var cell = cellArray[i];
var qty = qtyArray[i];
var wafernum = wafernumArray[i];
var purpose = purposeArray[i];
var remarks = remarksArray[i];
if (uname === "" || age === "" || cell === "" || qty === "" || wafernum === "" || purpose === "" || remarks === "") {
document.getElementById('submit_form').disabled = true;
document.getElementById('submit_form').style.backgroundColor = "initial";
break;
} else {
document.getElementById('submit_form').disabled = false;
document.getElementById('submit_form').style.backgroundColor = "yellow";
}
}
}
</script>
<style>
</style>
</head>
<body>
Name: <input type="text" id="uname" /> Age: <input type="text" id="age" />
<input type="button" id="add" value="Add" onclick="Javascript:addRow();">
<table id="bod">
<tr>
<th>PURPOSE</th>
<th>WAFERNUM</th>
<th>CELL</th>
<th>QTY</th>
<th>REMARKS</th>
</tr>
</table>
<input type="submit" name="submit" id="submit_form" value="Submit" onclick="SaveData()" disabled>
</body>
</html>
html code we can get the value
<input type="text" name="value1[]" id="value1"/>
<input type="mail" name="value2[]" id="value2"/>
<input type="text" name="total[]" id="total" />
i can try with this in jQuery i can get only html value result, after add new row i can't get the value
$(document).ready(function () {
var counter = 0;
$("#addrow").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td>Item1</td>';
cols += '<td><input type="text" class="form-control" name="value1[]" id="value2' + counter + '"></td>';
cols += '<td><input type="text" class="form-control" name="foreign_milion[]" id="foreign_milion_' + counter + '"></td>';
cols += '<td><input type="text" readonly class="form-control" name="total_milion[]" id="total_"' + counter + '"></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("#value2").keyup(function () {
var value1 = $("#value1").val();
var value2 = $("#value2").val();
var totalincome = parseInt(value1) + parseInt(value2);
//alert(totalincome);
$("#total").val(totalincome);
})
});
First of all the id must be unique in the same document, else you'll end up with incorrect HTML code, so you need to replace the ids with common classes instead in your code as a first step.
Then you need to use event delegation to attach the event to your inputs since the must of them are created dynamically with the JS code.
I prefer the use of input event instead of keyup when you track the user inputs, so the event will be something like:
$(document).ready(function() {
var counter = 1;
$("body").on("input", ".calculated_value", function() {
var parent_row = $(this).closest('tr');
var totalincome = 0;
parent_row.find('.calculated_value').each(function() {
totalincome += parseInt($(this).val() || 0);
});
parent_row.find(".total").val(totalincome);
});
$("#addrow").on("click", function() {
var newRow = $("<tr>");
var cols = "";
cols += '<td>Item ' + counter + '</td>';
cols += '<td><input type="text" class="form-control calculated_value" name="value1[]"></td>';
cols += '<td><input type="text" class="form-control calculated_value" name="foreign_milion[]"></td>';
cols += '<td><input type="text" class="form-control total" name="total_milion[]" readonly></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="order-list">
<tr>
<td>Item </td>
<td><input type="text" class="form-control calculated_value" name="value1[]"></td>
<td><input type="text" class="form-control calculated_value" name="foreign_milion[]"></td>
<td><input type="text" class="form-control total" name="total_milion[]" readonly></td>
</tr>
</table>
<button id="addrow">Add row</button>
I have tried this one, may be this is what you are looking into.
please take a look at the snippet.
jQuery(document).ready(function () {
var count = 1;
jQuery('#add').on('click', function(){
var el = `<section id="inpFields">
<input type="text" name="value1[]" id="value`+count+`" placeholder="value `+count+`"/>
<input type="text" name="value2[]" id="value2`+count+`" placeholder="value `+count+`"/>
<input type="text" name="total[]" id="total`+count+`" placeholder="total" />
<button class="totalBtn" data-id="`+count+`">Total</button>
</section>`;
jQuery('#inpFields').append(el);
count++;
});
jQuery('#add').click();
jQuery(document).on('click', '.totalBtn', function(){
var i = this.dataset.id;
var value1 = jQuery('#value'+i).val();
var value2 = jQuery('#value2'+i).val();
var totalincome = parseInt(value1) + parseInt(value2);
//alert(totalincome);
jQuery('#total'+i).val(totalincome);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<button id="add">Add Fields</button>
<section id="inpFields">
</section>
I have a little problem with my template.
I would like to read in a template with jquery and then find all inputs within this object to manipulate them.
Unfortunately, the inputs are not returned.
I already use the function "checkInputs" in another place.
The target is not a template and it works without problems.
Here's my test code:
listOfTemplateInputs = checkInputs("#IncomingInformationsTemplate");
alert("Hidden: " + listOfTemplateInputs.Hidden.length + ", Fields: " + listOfTemplateInputs.Fields.length);
function checkInputs(target) {
var ListOfFields = [];
var ListOfCheckBoxes = [];
var ListOfHidden = [];
$(target + " input[type='text'], textarea, input[type='password']").each(function() {
var input = $(this);
ListOfFields.push(input);
});
$(target + " input[type='checkbox']").each(function() {
var input = $(this);
ListOfCheckBoxes.push(input);
});
$(target + " input[type='hidden']").each(function() {
var input = $(this);
ListOfHidden.push(input);
});
var inputList = {
Fields: ListOfFields,
CheckBoxes: ListOfCheckBoxes,
Hidden: ListOfHidden
};
return inputList;
}
And here is my template:
<script id="IncomingInformationsTemplate" type="text/html">
<tr class="">
<input autocomplete="off" name="IncomingInformations.Index" type="hidden" value="5eda7c21-9b4e-4eb5-b992-6a3ea16a46cd" />
<td>
<div>
<input type="hidden" name="country" value="Norway">
<input type="hidden" name="country2" value="Germany">
<input type="text" name="Name" value="Tom">
<input type="text" name="Name2" value="Lisa">
</div>
</td>
</tr>
</script>
The thing is that script tag does not parse the HTML and create a DOM out of it.
Its contents are just a string.
To be able to select from it, you should parse it (you can do it with jQuery) and select from the created (parsed) object.
Notice in the code below I first create a "mini (virtual) DOM" out of your template's text contents:
var miniDOM = $($(target).text());
And now use all selectors having it as context/root. E.g.
miniDOM.find("input[type='text'], textarea, input[type='password']").each(function() {
This finds the elements as you wanted.
listOfTemplateInputs = checkInputs("#IncomingInformationsTemplate");
alert("Hidden: " + listOfTemplateInputs.Hidden.length + ", Fields: " + listOfTemplateInputs.Fields.length);
function checkInputs(target) {
var miniDOM = $($(target).text());
var ListOfFields = [];
var ListOfCheckBoxes = [];
var ListOfHidden = [];
miniDOM.find("input[type='text'], textarea, input[type='password']").each(function() {
var input = $(this);
ListOfFields.push(input);
});
miniDOM.find("input[type='checkbox']").each(function() {
var input = $(this);
ListOfCheckBoxes.push(input);
});
miniDOM.find("input[type='hidden']").each(function() {
var input = $(this);
ListOfHidden.push(input);
});
var inputList = {
Fields: ListOfFields,
CheckBoxes: ListOfCheckBoxes,
Hidden: ListOfHidden
};
return inputList;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="IncomingInformationsTemplate" type="text/html">
<tr class="">
<input autocomplete="off" name="IncomingInformations.Index" type="hidden" value="5eda7c21-9b4e-4eb5-b992-6a3ea16a46cd" />
<td>
<div>
<input type="hidden" name="country" value="Norway">
<input type="hidden" name="country2" value="Germany">
<input type="text" name="Name" value="Tom">
<input type="text" name="Name2" value="Lisa">
</div>
</td>
</tr>
</script>
Of course, you could, alternatively, turn that script into any renderable element, like div or span, even if hidden, and you could query it with your original code:
listOfTemplateInputs = checkInputs("#IncomingInformationsTemplate");
alert("Hidden: " + listOfTemplateInputs.Hidden.length + ", Fields: " + listOfTemplateInputs.Fields.length);
function checkInputs(target) {
var ListOfFields = [];
var ListOfCheckBoxes = [];
var ListOfHidden = [];
$(target + " input[type='text'], textarea, input[type='password']").each(function() {
var input = $(this);
ListOfFields.push(input);
});
$(target + " input[type='checkbox']").each(function() {
var input = $(this);
ListOfCheckBoxes.push(input);
});
$(target + " input[type='hidden']").each(function() {
var input = $(this);
ListOfHidden.push(input);
});
var inputList = {
Fields: ListOfFields,
CheckBoxes: ListOfCheckBoxes,
Hidden: ListOfHidden
};
return inputList;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="IncomingInformationsTemplate" style="display: none">
<tr class="">
<input autocomplete="off" name="IncomingInformations.Index" type="hidden" value="5eda7c21-9b4e-4eb5-b992-6a3ea16a46cd" />
<td>
<div>
<input type="hidden" name="country" value="Norway">
<input type="hidden" name="country2" value="Germany">
<input type="text" name="Name" value="Tom">
<input type="text" name="Name2" value="Lisa">
</div>
</td>
</tr>
</div>
you should find inputs with this method
$('#IncomingInformationsTemplate').find(':input').each(function(i,e) {
console.log((i+1)+'. '+$(e)[0].outerHTML);
$(e).addClass('manipulate-it'); //manipulate it
});
Got JS Fiddle to work
http://jsfiddle.net/pskjxofo/
Attached I have the following function, the purpose of which is to perform basic calculation. I also added a feature for adding more boxes for calculation. What I am currently stuck on is how to tell Javascript to make dynamic divs, and how to tell it to perform the same calculations for each line every time I click on Calculate. Assistance on this would be greatly appreciated. Thank you all in advance.
<div id="redo">
2 X
<input type="text" id="initial">
= <input type="text" id="solved">
<input type="submit" value="Calculate" onclick="calculait()">
<input type="submit" value="Add Another Box" onclick="addmore()">
</div>
<div id="main"></div>
<script type="text/javascript">
function calculait(){
var first = document.getElementById('initial');
var second = document.getElementById('solved');
second.value = first.value * 2;
}
function addmore(){
var bar = document.getElementById('main');
bar.innerHTML = bar.innerHTML + "<div id='redo'>2 X
<input type='text' id='initial'> = <input type='text' id='solved'>
<input type='submit' value='Calculate' onclick='calculait()'
<input type='submit' value='Add Another Box' onclick='addmore()";
}
</script>
Here is one of the many ways to do it. You could have this HTML structure:
<div id="main">
<div class="operation">
2 X <input type="text" class="initial"/>=
<input type="text" class="solved"/>
</div>
</div>
<input type="submit" value="Calculate" onclick="calculait()"/>
<input type="submit" value="Add Another Box" onclick="addmore()"/>
And this JS:
// Main container for all operations
var main = document.getElementById('main');
// Piece of HTML you'll be duplicating
var op = document.getElementsByClassName('operation')[0].outerHTML;
function calculait() {
// Get every operation div
var operations = document.getElementsByClassName('operation');
// For each of them, calculate
for(var i=0, l=operations.length; i<l; i++){
operations[i].getElementsByClassName('solved')[0].value =
parseFloat(operations[i].getElementsByClassName('initial')[0].value) * 2;
}
}
function addmore() {
main.insertAdjacentHTML('beforeend',op);
}
JS Fiddle Demo
If I understood correctly, I think this code will help.
First of all, change your ids for classes (IDs must be always unique in the page).
<input type="text" class="initial">
<input type="text" class="solved">
And in the JS, you use a for to iterate for this elements.
function calculait() {
var initial = document.getElementsByClassName('initial');
var solved = document.getElementsByClassName('solved');
for (var i = 0; i < initial.length; i++) {
solved[i].value = initial[i].value * 2;
}
}
function addmore() {
var bar = document.getElementById('main');
var html = "<div>2 X ";
html += "<input type='text' class='initial'> = ";
html += "<input type='text' class='solved'>";
html += "</div>";
bar.innerHTML = bar.innerHTML + html;
}
JSFiddle: http://jsfiddle.net/pskjxofo/2/
Give it a try and let me know if it helps!
When you write JavaScript use a debugger, your code didn't parse. You can find one in your browser by hitting F12.
Don't repeat yourself. A clean solution is to put html to duplicate into a template or similar and call a function to copy it.
Use input type=number for numbers.
<html>
<meta charset="utf-8">
<template id="calculate_template">
<form id="" class="calculate_form">
<input value="2" type="number" name="initial_1"> X
<input type="number" name="initial_2"> =
<input type="number" name="solved" disabled="disabled" >
</form>
</template>
<div id="main">
<button onclick="addmore();">Add Another Box</button>
<button onclick="calculate();">Calculate</button>
</div>
<script type="text/javascript">
function calculate(){
/*Calculates all*/
var forms = document.getElementsByClassName('calculate_form'),
i,
length = forms.length;
for(i = 0; i < length; i++){
console.log(forms[i]);
forms[i]['solved'].value = forms[i]['initial_1'].value * forms[i]['initial_2'].value;
}
}
function addmore(){
var main = document.getElementById('main');
main.insertAdjacentHTML("beforeend", document.getElementById('calculate_template').innerHTML);
}
addmore();
</script>
</html>
Demonstration
Here's a way of doing it:
var counter = 0;
function calculait(calculationId) {
var first = document.getElementById('initial' + calculationId);
var second = document.getElementById('solved' + calculationId);
second.value = first.value * 2;
}
function addmore() {
counter++;
var bar = document.getElementById('main');
var newDiv = document.createElement("div");
newDiv.id = "redo" + counter;
newDiv.innerHTML = "2 X <input type='text' id='initial" + counter + "'/> = <input type='text' id='solved" + counter + "'/><input type='submit' value='Calculate' onclick='calculait(" + counter + ")'/><input type='submit' value='Add Another Box' onclick='addmore(" + counter + ")'/>";
bar.appendChild(newDiv);
}
<div id="main"><div id="redo0">2 X <input type="text" id="initial0" /> = <input type="text" id="solved0" /><input type="button" value="Calculate" onclick="calculait(0)" /><input type="button" value="Add Another Box" onclick="addmore(0)" /></div>
</div>
HTML
<p id="operations"></p>
<p>
<input type="submit" value="Calculate" onclick="calc()" />
<input type="submit" value="Add operation" onclick="addOp()" />
</p>
Javascript
var id = 0, multiplier = 2;
var operations = document.getElementById('operations');
function addOp() {
++id;
var p = document.createElement("p");
var right = document.createElement("input");
right.id = 'right_' + id;
right.type = 'text';
var result = document.createElement('input');
result.id = 'result_' + id;
right.type = 'text';
p.innerHTML = multiplier + ' x ';
p.appendChild(right);
p.innerHTML += ' = ';
p.appendChild(result);
operations.appendChild(p);
}
function calc() {
for(var i = 1; i <= id; i++) {
var right = document.getElementById('right_' + i);
var result = document.getElementById('result_' + i);
result.value = multiplier * right.value;
}
}
addOp();
JSFiddle : http://jsfiddle.net/0Lcg0pyz/
I searched a lot for this, but I can only find +1 -1 solutions.
But I want to set the number of inputs with a other input like this:
//Enter the number of inputs (1 is the start-value)
<input type="text" size="3" maxlength="3" id="count" name="count" value="1">
//Display that number of inputs (1 at start)
<input type="text" size="30" maxlength="30" id="input_1" name="input_1">
When the user now writes 5 in the first field, the form should look like this:
//Enter the number of inputs (1 is the start-value)
<input type="text" size="3" maxlength="3" id="count" name="count" value="1">
//Display that number of inputs (1 at start)
<input type="text" size="30" maxlength="30" id="input_1" name="input_1">
<input type="text" size="30" maxlength="30" id="input_2" name="input_2">
<input type="text" size="30" maxlength="30" id="input_3" name="input_3">
<input type="text" size="30" maxlength="30" id="input_4" name="input_4">
<input type="text" size="30" maxlength="30" id="input_5" name="input_5">
How can I make this? MUST I use js?
Here's a simple javascript snippet that doesn't make use of any frameworks:
function addInputs() {
var count = parseInt(document.getElementById("count").value);
for (var i = 2; i <= count; i++) {
document.getElementById('moreinputs').innerHTML += '<input type="text" name="input_' + i + '" id="input_' + i + '" />';
}
}
In this example you have to add a container (div) with id 'moreinputs'. However, when calling this function more than once, it will not work properly (e.g. it can only increase the number of input but not decrease)
Yes, either you use javascript, or you send the form to the server, where a new html page with all the inputs is generated (e.g. with PHP).
Yes you must use js to do it dynamically on the spot You have a jQuery tag so I will show an example in jQuery
This is not the best example but it works and it's a starting point
JS:
$(function(){
$('#master').on('change', function() {
var count = $(this).val();
$('#otherInputs').html('')
for( var i = 0; i < count; i++) {
$('#otherInputs').append(
$('<input>', {type: 'text'})
);
}
});
});
HTML:
<input type="number" id="master" value="1">
<div id="otherInputs"></div>
Demo
In English this is saying...
When you change #master I will empty #master (html('')) loop through and append a new input depending on #master's value
Here's the FIDDLE. Hope it helps. :)
html
<input type="text" size="3" maxlength="3" id="count" name="count" value="1">
<div id="container"></div>
script
$('#count').on('keyup', function () {
var $this = $(this);
var count = $this.val();
$('#container').empty();
for (var x = 1; x <= count; x++) {
var newInput = '<input type="text" size="30" maxlength="30" id="input_' + x + '" name="input_' + x + '">';
$('#container').append(newInput);
}
});
This worked for me
function AddField() {
var count = $("#countetfield").val();
var i = 1;
var id = $("#container .testClass:last").attr('name');
var test = id.split("_");
id_name = test[1];
while (i <= count) {
id_name++;
var a = '<input type="text" class="testClass" size="30" maxlength="30" id="input_' + id_name + '" name="input_' + id_name + '"/>';
$("#container").append(a);
i++;
}
}
<input type="text" id="countetfield" value="1" />
<input type="button" value="Go" onclick="AddField();" />
<div id="container">
<input type="text" class="testClass" size="30" maxlength="30" id="input_1" name="input_1" />
</div>