JQuery to dynamically update totals - javascript

Each time a new div is created via a button click, I want to dynamically keep an order so when one div is created it becomes 1 of 1, then 1 of 2 when a further div is created and when a div is deleted it reverts back to 1 of 1 etc.
I've tried using each to update all specific tags, but they do not update themselves each time a new div is added. This is the code:
iadd = 0;
itotal = 0;
$('#add').click(function() {
iadd++;
$('<div class="input-group col-sm-offset-4 col-sm-3" name="music" id="music' + iadd + '"><label for="phone" class="control-label"><b>Track ' + iadd + ' of ' + itotal + '</b></label><input type="text" class="form-control" name="music1" placeholder="Email" value="" id="music1" data-name="musicAdd" /><br><input type="text" class="form-control" name="email2" placeholder="Description" value="" id="music2" data-name="emailDesc"/></div>').appendTo('#musics');
$('.control-label').each(function() {
itotal = iadd;
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="add">Add</button>
<div class="form-group" id="musics"></div>
How could it be possible to enable this? This is the JSFiddle

I would go like this:
$(function () {
$('#add').on('click', function () {
// The total is the number of divs within the main container + 1.
// + 1 because we're calculating it before actually appending the new one.
var total = $('#musics div').length + 1;
// The current index is exactly the total (you could save a variable here).
var index = total;
// Create the new div and append it to the main container.
var newDiv = $('<div class="input-group col-sm-offset-4 col-sm-3" name="music" id="music' + index + '"><label for="phone" class="control-label"><b>Track ' + index + ' of ' + total + '</b></label><input type="text" class="form-control" name="music1" placeholder="Email" value="" id="music1" data-name="musicAdd" /><br><input type="text" class="form-control" name="email2" placeholder="Description" value="" id="music2" data-name="emailDesc"/></div>').appendTo('#musics');
// Loop through the new div siblings (filtering the type just to make sure),
// and update their labels with the index/total.
newDiv.siblings('div').each(function (ix, el) {
$('label', el).html('<b>Track ' + (ix + 1) + ' of ' + total + '</b>');
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add">Add</button>
<div class="form-group" id="musics"></div>
Demo (jsFiddle)
...
If you want to go a bit further (with some prototype):
// The explanation for the code below is basically the same you can
// find in the code above, with the exception of using prototype
// to create a format method, where you replace items within a string.
String.prototype.format = function () {
var value = this.toString();
for (var i = 0, len = arguments.length; i < len; i++) {
value = value.replace(new RegExp('\{[' + i + ']\}', 'g'), arguments[i]);
}
return value;
}
String.format = function () {
if (arguments.length == 0) return '';
var value = arguments[0].toString();
for (var i = 1, len = arguments.length; i < len; i++) {
value = value.replace(new RegExp('\{[' + (i - 1) + ']\}', 'g'), arguments[i]);
}
return value;
}
$(function () {
$('#add').on('click', function () {
var total = $('#musics div').length + 1;
var index = total;
var labelHtml = '<b>Track {0} of {1}</b>';
var newDiv = $('<div class="input-group col-sm-offset-4 col-sm-3" name="music" id="music{0}"><label for="phone" class="control-label">' + labelHtml.format(index, total) + '</label><input type="text" class="form-control" name="music1" placeholder="Email" value="" id="music1" data-name="musicAdd" /><br><input type="text" class="form-control" name="email2" placeholder="Description" value="" id="music2" data-name="emailDesc"/></div>'.format(index)).appendTo('#musics');
newDiv.siblings('div').each(function (ix, el) {
$('label', el).html(labelHtml.format((ix + 1), total));
});
});
});
Demo
...
UPDATE
As per your comment, I believe you're planning to have a delete button to be able to remove tracks and then update the indexes/total.
You can do it like this:
$(function () {
// A single function to update the tracks indexes/total.
function sortTracks() {
// Not like the first piece of code in the beginning of the answer,
// here we don't add 1 to the length, because the elements will be
// already in place.
var $tracks = $('#musics .input-group');
var total = $tracks.length;
$tracks.each(function (ix, el) {
$('label', el).html('<b>Track ' + (ix + 1) + ' of ' + total + '</b>');
});
}
$('#add').on('click', function () {
var index = $('#musics div').length + 1;
$('<div class="input-group col-sm-offset-4 col-sm-3" name="music" id="music' + index + '"><label for="phone" class="control-label"></label><input type="text" class="form-control" name="music1" placeholder="Email" value="" id="music1" data-name="musicAdd" /><br><input type="text" class="form-control" name="email2" placeholder="Description" value="" id="music2" data-name="emailDesc"/><button class="delete">Delete</button></div>').appendTo('#musics');
sortTracks();
});
$('#musics').on('click', '.delete', function () {
// Remove this element's immediate parent with class = input-group.
$(this).closest('.input-group').remove();
sortTracks();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add">Add</button>
<div class="form-group" id="musics"></div>
Demo (jsFiddle)
Note: If you check your HTML string used to create the tracks, you'll notice that your inputs have hard-coded ids, so you'll have multiple elements sharing the same id, which is wrong. IDs should be always unique.

Related

Button generated inside javascript code to onclick insert value in input type text in form

I have a very nice SEO-keyword suggestion tool working with CKeditor, it displays the most used word in the text while writing. The problem is that I want to make these generated keywords clickable one by one. So when you click on a keyword, it auto-fills an input-type text.
Here is the HTML code:
<!-- Textarea -->
<div class="form-group">
<label class="col-md-2 control-label" for="editor1">Insert your text here </label>
<div class="col-md-10">
<textarea class="form-control" id="editor1" name="editor1"><p>text example with ahöäåra</p></textarea>
</div>
</div>
<!-- KW density result -->
<div class="form-group">
<label class="col-md-2 control-label" for="editor1">Suggested SEO keywords</label>
<div class="col-md-10">
<div id="KWdensity" ></div>
</div>
</div>
Here is the javascript code:
<script type="text/javascript">
$(document).ready(function() {
CKEDITOR.replace('editor1');
$(initKW);
CKEDITOR.instances.editor1.on('contentDom', function() {
CKEDITOR.instances.editor1.document.on('keyup', function(event) {
$(initKW);
});
});
function KeyDensityShow(srctext, MaxKeyOut, keylenMin) {
var Output;
var words = srctext.toLowerCase().split(/[^\p{L}\p{M}\p{N}]+/u)
var positions = new Array()
var word_counts = new Array()
try {
for (var i = 0; i < words.length; i++) {
var word = words[i]
if (!word || word.length < keylenMin) {
continue
}
if (!positions.hasOwnProperty(word)) {
positions[word] = word_counts.length;
word_counts.push([word, 1]);
} else {
word_counts[positions[word]][1]++;
}}
word_counts.sort(function(a, b) {
return b[1] - a[1]
})
return word_counts.slice(0, MaxKeyOut)
} catch (err) {
return "";
}}
function removeStopWords(input) {
var stopwords = ['test', ];
var filtered = input.split(/\b/).filter(function(v) {
return stopwords.indexOf(v) == -1;
});
stopwords.forEach(function(item) {
var reg = new RegExp('\\W' + item + '\\W', 'gmi');
input = input.replace(reg, " ");
});
return input.toString();
}
function initKW() {
$('#KWdensity').html('');
var TextGrab = CKEDITOR.instances['editor1'].getData();
TextGrab = $(TextGrab).text();
TextGrab = removeStopWords(TextGrab);
TextGrab = TextGrab.replace(/\r?\n|\r/gm, " ").trim();
TextGrab = TextGrab.replace(/\s\s+/g, " ").trim();
if (TextGrab != "") {
var keyCSV = KeyDensityShow(TextGrab, 11, 3);
var KeysArr = keyCSV.toString().split(',');
var item, items = '';
for (var i = 0; i < KeysArr.length; i++) {
item = '';
item = item + '<b>' + KeysArr[i] + "</b></button> ";
i++;
item = '<button class="btn btn-default btn-xs" type="button" onclick="document.getElementById(thebox).value="head of gwyneth paltrow";"><span class="badge">' + KeysArr[i] + "</span> " + item;
items = items + item;
}
$('#KWdensity').html(items);
}}});
</script>
And here is some extra HTML for the input that needs to be auto-filled.
The keywords box:
<input type="text" id="thebox" value="" style="width:80%;height:30px;background:#000;color:#fff;"/>
<br><input type="button" value="this one is working" onclick="document.getElementById('thebox').value='test button is working';">
So if you write something, it will generate keywords buttons. When you click on one of these buttons, the keyword must be entered in the input text like this
keyword,
Here is a Fiddle DEMO.
Any idea how to fix that? I added a document.getElementById('thebox'). but it does not return anything
Your code in
item = '<button class="btn btn-default btn-xs" type="button" onclick="document.getElementById(thebox).value="head of gwyneth paltrow";"><span class="badge">' + KeysArr[i] + "</span> " + item;
Will add to the DOM (in other words, to the HTML of the page), the following bit:
<button
class="btn btn-default btn-xs"
type="button"
onclick="document.getElementById(thebox).value="head of gwyneth paltrow";"
>
Now, the resulting onclick above has some problems. First, notice that the quotes it uses in the string after .value= are actually closing the onclick declaration because they are not escaped. I mean, instead of
onclick="document.getElementById(thebox).value="head of gwyneth paltrow";"
^--- problem here ^--- and here
It should've been
onclick="document.getElementById(thebox).value=\"head of gwyneth paltrow\";"
^--- fixed here ^--- and here
Secondly, the argument to .getElementById(thebox) is thebox. Notice here that the way it is now, thebox is actually a variable, not a string. So instead of the above, what you want is:
onclick="document.getElementById(\"thebox\").value=\"head of gwyneth paltrow\";"
^--- ^--- fixed here
These fixes should be enough to make the clicks on the words set the "head of gwyneth paltrow" value in the textbox.
I believe, though, you want to actually set the key when the button is clicked. To do that, instead of having "head of gwyneth paltrow" after the .value, you should have the text of the key. All in all, here's how that line could be:
item = '<button class="btn btn-default btn-xs" type="button" onclick="document.getElementById(\'thebox\').value=\'' + key + '\';"><span class="badge">' + KeysArr[i] + "</span> " + item;
^-- ^-- ^^^^^^^^^^^^^^--- changed here (notice in the demo below I declare the key variable before using it here)
Updated fiddle here. Running demo below as well.
$(document).ready(function() {
CKEDITOR.replace('editor1');
$(initKW);
CKEDITOR.instances.editor1.on('contentDom', function() {
CKEDITOR.instances.editor1.document.on('keyup', function(event) {
$(initKW);
});
});
function KeyDensityShow(srctext, MaxKeyOut, keylenMin) {
var Output;
var words = srctext.toLowerCase().split(/[^\p{L}\p{M}\p{N}]+/u)
var positions = new Array()
var word_counts = new Array()
try {
for (var i = 0; i < words.length; i++) {
var word = words[i]
if (!word || word.length < keylenMin) {
continue
}
if (!positions.hasOwnProperty(word)) {
positions[word] = word_counts.length;
word_counts.push([word, 1]);
} else {
word_counts[positions[word]][1]++;
}
}
word_counts.sort(function(a, b) {
return b[1] - a[1]
})
return word_counts.slice(0, MaxKeyOut)
} catch (err) {
return "";
}
}
function removeStopWords(input) {
var stopwords = ['test', ];
var filtered = input.split(/\b/).filter(function(v) {
return stopwords.indexOf(v) == -1;
});
stopwords.forEach(function(item) {
var reg = new RegExp('\\W' + item + '\\W', 'gmi');
input = input.replace(reg, " ");
});
return input.toString();
}
function initKW() {
$('#KWdensity').html('');
var TextGrab = CKEDITOR.instances['editor1'].getData();
TextGrab = $(TextGrab).text();
TextGrab = removeStopWords(TextGrab);
TextGrab = TextGrab.replace(/\r?\n|\r/gm, " ").trim();
TextGrab = TextGrab.replace(/\s\s+/g, " ").trim();
if (TextGrab != "") {
var keyCSV = KeyDensityShow(TextGrab, 11, 3);
var KeysArr = keyCSV.toString().split(',');
var item, items = '';
var previousKeys = [];
for (var i = 0; i < KeysArr.length; i++) {
item = '';
var key = KeysArr[i];
previousKeys.push(key);
item = item + '<b>' + key + "</b></button> ";
i++;
item = '<button class="btn btn-default btn-xs" type="button" onclick="document.getElementById(\'thebox\').value=\'' + previousKeys.join(', ') + '\';"><span class="badge">' + KeysArr[i] + "</span> " + item;
items = items + item;
}
$('#KWdensity').html(items);
}
}
});
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="//cdn.ckeditor.com/4.6.1/standard/ckeditor.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-2 control-label" for="editor1">Insert your text here </label>
<div class="col-md-10">
<textarea class="form-control" id="editor1" name="editor1"><p>text example with ahöäåra</p></textarea>
</div>
</div>
<!-- KW density result -->
<div class="form-group">
<label class="col-md-2 control-label" for="editor1">Suggested SEO keywords</label>
<div class="col-md-10">
<div id="KWdensity" ></div>
</div>
</div>
The keywords box: <input type="text" id="thebox" value="" style="width:80%;height:30px;background:#000;color:#fff;"/>
<br><input type="button" value="this one is working" onclick="document.getElementById('thebox').value='test button is working';">

How to get data from dynamic elements that added to the html page?

In below I write form part of my html page.
<form method="post" enctype="multipart/form-data">
<div>
<label>Brand Name:</label>
<input type="text" asp-for="#Model.Name">
</div>
<div id="divCategory">
</div>
<button type="button" id="btnAddCategory">Add Category</button>
<button>Create new Brand</button>
</form>
and I have two js and jquery function that add a select to divCategory. Whith this select I can add some categories.
function countMyCategories() {
if (typeof countMyCategories.counter == 'undefined') {
countMyCategories.counter = -1;
}
return ++countMyCategories.counter;
}
$(document).ready(function () {
$('#btnAddCategory').on('click', function () {
var catId = countMyCategories();
$('#divCategory').append(
'<select id="selectCategory' + catId + '" asp
for="##Model.CatBrands[' + catId + '].CatId" class="mt-3 form-control
form-control-sm">' +
'<option>---Select---</option>' +
'</select>'
);
$.ajax('/API/GetCats')
.done(function (categories) {
for (var i = 0; i < categories.length; i++) {
$('#selectCategory' + catId).append(
'<option value="' + categories[i].id + '">' +
categories[i].name + '</option>'
)
}
});
});
});
When I click the "Add Category" button one select tag added to the div by id="divCategory", but problem is that when I click "Create New Brand" button, I don't get data from these selects in server, actually CatBrands is null but I got name. I get something like that:
{name = "LG", catBrands = null}
CatBrands is null because you can't dynamically add data from the server in this manner. When the page renders, you need everything you want rendered by asp in the html.
<form method="post" enctype="multipart/form-data">
<div>
<label>Brand Name:</label>
<input type="text" asp-for="#Model.Name">
</div>
<div id="divCategory">
<select id="selectCategory asp-code-goes-here>
<option>---Select---</option>
</select>
</div>
<button type="button" id="btnAddCategory">Add Category</button>
<button>Create new Brand</button>
</form>
I've made a terible mistake. I should change my function like this
$(document).ready(function () {
$('#btnAddCategory').on('click', function () {
var catId = countMyCategories();
$('#divCategory').append(
'<select id="selectCategory' + catId + '"
name = "CatBrands[' + catId + '].CatId" class="mt-3 form-control
form-control-sm">' +
'<option>---Select---</option>' +
'</select>'
);
$.ajax('/API/GetCats')
.done(function (categories) {
for (var i = 0; i < categories.length; i++) {
$('#selectCategory' + catId).append(
'<option value="' + categories[i].id + '">' +
categories[i].name + '</option>'
)
}
});
});
});

How to create program to Calculate Resistors in Series using javascript?

i'm newbie in here. i want to create program to calculate resistors in series using HTML & javascript.
I have tried to make it with code below. there are 2 functions.
first, to create input fields automatically based on how many resistors you wants to input.
image 1.( i have created this function ).
and the second function is sum the total values of the input fields that have been created.
image 2. ( i'm not yet create this function )
how to create this ? could you complate the second function ? or any have other alternative ?
JAVASCRIPT :
< script >
function display() {
var y = document.getElementById("form1").angka1.value;
var x;
for (x = 1; x <= y; x++) {
var a = document.getElementById("container");
var newInput = document.createElement('div');
newInput.innerHTML = 'R ' + x + ': <input type="text" id="r_' + x + '" name="r_' + x + '"/>';
a.appendChild(newInput);
}
}
function count() {
//this function not yet created
}
</script>
HTML:
<form id="form1" name="form1" onsubmit="return false">
<label for="number">Input Qty of Resistors </label>
<input type="number" name="angka1">
<input type="submit" value="Display Input" onclick="display()">
<div id="container"></div>
<input type="submit" value="Count" onclick="count()">
</form>
Here is the working demo of what you want to achieve. Click Here
Note that here in demo I have use JQuery so please include jquery file.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="number">Input Qty of Resistors </label>
<input type="number" id="angka1" />
<input type="button" value="Display Input" onclick="display()" />
<div id="container"></div>
<input type="button" value="Count" onclick="count()" />
<label id="totalCount"></label>
function display() {
document.getElementById("container").innerHTML = "";
var y = document.getElementById("angka1").value;
var x;
for (x = 1; x <= y; x++) {
var a = document.getElementById("container");
var newInput = document.createElement('div');
newInput.innerHTML = 'R ' + x + ': <input type="number" id="r_' + x + '" name="r_' + x + '" />';
a.appendChild(newInput);
}
}
function count() {
console.log("Count function is called.");
var total = 0;
$("#container input").each(function () {
total += Number($(this).val().trim());
console.log(total);
});
document.getElementById("totalCount").innerHTML = total;
}
Hope that will work for you.

How to rename all id in a cloned form (javascript)?

I have a form (commonStuff) cloned this way (and an html page, designed in jquery mobile, where the form appears multiple times, cloned):
var commonClone = commonStuff.cloneNode(true);
and this function
function renameNodes(node) {
var i;
if (node.length) {
for (i = 0; i < node.length; i += 1) {
renameNodes(node[i]);
}
} else {
// rename any form-related elements
if (typeof node.form !== 'undefined') {
node.id = currentPrefix + '_' + node.id;
node.name = currentPrefix + '_' + node.name;
// This assumes that form elements do not have child form elements!
} else if (node.children) {
renameNodes(node.children);
}
}
}
which add a prefix 'form1_', 'form_2' (the currentPrefix) to id and names of any element in the form and is applied to commonClone (and so recursively to his sons).
renameNodes(commonClone);
It work perfectly in case of text inputs like
<div data-role="fieldcontain" class="ui-field-contain ui-body ui-br">
<label for="foo" class="ui-input-text">Age:</label>
<input type="text" name="age" id="age" value="" class="ui-input-text ui-body-c ui-corner-all ui-shadow-inset">
</div>
But it fails on radio buttons like
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Address:</legend>
<input type="radio" name="radio-address" id="radio-address_female" value="1" checked="checked" />
<label for="radio-address_female">Address 1</label>
<input type="radio" name="radio-address" id="radio-address_male" value="2" />
<label for="radio-address_male">Address 2</label>
</fieldset>
</div>
applying the renaming to the outer divs like 'fieldcontain' and 'controlgroup'. It works if i remove those two divs but the graphical effect is unacceptable...
As far as now, i got the problem is in the last 'else if' block for it doesn't care of siblings, but I don't really know how to fix this. Any idea?
EDIT: This code comes from this answer How to create a tabbed html form with a common div
As you use jQuery mobile, jQuery will be available.
I hope this code will point you in the right direction:
var i = 0;
$("form").each(function() {
$(this).find("input, select").each(function() {
$(this).attr("id", "form" + i + "_" + $(this).attr("id"));
$(this).attr("name", "form" + i + "_" + $(this).attr("name"));
});
$(this).find("label").each(function() {
$(this).attr("for", "form" + i + "_" + $(this).attr("for"));
});
i++;
});
EDIT:
I understand your current approach fails with labels. Consider to wrap your input elements inside the label tag. In that case, you won't need the for-attribute. This is in accordance with the docs: http://api.jquerymobile.com/checkboxradio/
Consider this:
HTML
<form>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Address:</legend>
<label><input type="radio" name="radio-address" id="radio-address_female" value="1" checked="checked" />Address 1</label>
<label><input type="radio" name="radio-address" id="radio-address_male" value="2" />Address 2</label>
</fieldset>
</div>
<div data-role="fieldcontain" class="ui-field-contain ui-body ui-br">
<label><input type="text" name="age" id="age" value="" class="ui-input-text ui-body-c ui-corner-all ui-shadow-inset">Age:</label>
</div>
</form>
jQuery
var i = 0, currentPrefix = "form";
$("form").each(function() {
$(this).find("input, select").each(function() {
$(this).attr("id", currentPrefix + i + "_" + $(this).attr("id"));
$(this).attr("name", currentPrefix + i + "_" + $(this).attr("name"));
});
i++;
});
Workin fiddle: https://jsfiddle.net/EliteSystemer/8sx6rnwo/
Truly, this is far from elegant, but a solution, anyway. In any node, this searches manually for input and labels, changing id, names and 'for' attribute in case of labels.
function renameNodes(node) {
var i;
if (node.length) {
for (i = 0; i < node.length; i += 1) {
renameNodes(node[i]);
}
} else {
// rename any form-related elements
if (typeof node.form !== 'undefined') {
node.id = currentPrefix + '_' + node.id;
node.name = currentPrefix + '_' + node.name;
var inputs = node.getElementsByTagName('input');
for (i = 0; i < inputs.length; ++i) {
inputs[i].id = currentPrefix + '_' + inputs[i].id;
inputs[i].name = currentPrefix + '_' + inputs[i].name;
}
var labels = node.getElementsByTagName('label');
for (i = 0; i < labels.length; ++i) {
labels[i].setAttribute('for', currentPrefix + '_' + labels[i].getAttribute("for"));
}
} else if (node.children) {
renameNodes(node.children);
}
}
}

how to assign variable value after window onload

How to show the textboxes.....see. The max value I will assign after onload so following code did not work........
max value is equal to the user selected files count.
I cant assign before onload the page..
<form action="" method="post" onsubmit="store(this); return false">
<p>
<input type="button" name="prev" onclick="goto(this.form, -1)" value="Previous" />
<input type="button" name="next" onclick="goto(this.form, +1)" value="Next" />
</p>
<divs>
<noscript>Please enable JavaScript to see this form correctly</noscript>
</divs>
<div id="filename"></div>
<p>
<input type="submit" name="submit" value="Store in database" />
</p>
</form>
<!-------------user selected file's name in array------------------>
var filelist=new Array();
function insert(filess)
{
filelist[filelist.length]=filess;
var sahan=(filelist.valueOf());
}
max=filelist.length;
window.onload = function() {
var form = document.forms[0];
var container = form.getElementsByTagName('divs')[0];
container.innerHTML = '';
for (var i = 0; i < max; i++)
container.innerHTML += '<fieldset style="width: 250px; height: 80px;"><legend>Files of ' +(i + 1) + ' / ' + max + '</legend><input type="text" name="name' + i + '" /><br /><br /><input type="text" name="topic' + i + '" /></fieldset>';
goto(form, 0);
}
There are too many issues to mention.
you need to get the maximum before you use it, so call insert and from there issue the call to build the list
you need to either pass the maximum around OR make it global in scope
you are using two different ajax methods
you are not using jQuery everywhere and so on.
Here is a working demo when maximum is set before onload.
http://jsfiddle.net/mplungjan/rnJWX/
var maximum=0, current = 0;
$(document).ready(function(){
maximum=10;
var container = $("#sankar");
container.hide();
container.empty();
for (var i = 0; i < maximum; i++) {
container.append('<fieldset style="width: 250px; height: 80px;"><legend>Files of ' +(i + 1) + ' / ' + maximum + '</legend><input type="text" name="name' + i + '" /><br /><br /><input type="text" name="topic' + i + '" /></fieldset>');
}
goto(form, 0);
container.show();
})
function goto(form, pos) {
current += pos;
$('#my_div').html("Hiding all "+maximum+" sets and showing set #"+current+"..."); // sankar[curent];
form.prev.disabled = current <= 0;
form.next.disabled = current >= maximum - 1;
// you can do jQuery here too
var fields = form.getElementsByTagName('fieldset');
for (var i = 0; i < fields.length; i++) fields[i].style.display = 'none';
fields[current].style.display = 'block';
form['name' + current].focus();
}
Well, since you've given your "container" element an ID, you should use document.getElementById('divs') instead of form.getElementsByTagName('divs')[0].
In your current code, container would be undefined.

Categories