可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have a form which starts out with 2 text inputs. The standard scenario is the user enters a number in one field and his/her name in the other and then the page will be updated (not reloaded). But in some cases the user may want to enter several numbers which are connected to the same name and the way this will be implemented is by the user clicking an "add another" link next to the text box.
When the user clicks the "add another" link, the value from the textbox needs to be inserted into a new (dynamically created) text field and the text field where the user entered the number should be reset to default value. The user can enter 10 numbers this way before an alert is presented informing him/her about more efficient ways to do this operation.
I'm clueless as to how this is done (can it be done) jQuery and it would be great if someone can help out.
Here is the html I'm working with:
<div id="searchFields" class="control-group inlineForm">
<label for="regNr">Regnr</label> <input type="text" id="regNr" class="uprCase" placeholder="Regnr." size="6" maxlength="6">
<span class="addRegNr"><a href="#">add another</a></div>
<label for="poNr">PO.nr</label> <input type="text" id="poNr" placeholder="PO.nr." size="12" maxlength="12">
<input type="button" value="GET INFO" class="last" id="getBaseInf">
</div>
http://jsfiddle.net/RgKV9/
Cheers!
EDIT UPDATE
I've taken a liking to Aske G's example and have made some changes to it. Here is the new code I'm working with, jsfiddle.net/SDpfy Although I managed to do some minor changes to AskeG's code I cant figure out how to add unique ID's and individual delete links for each generated field that ends up in the basket. Also, how can I set the generated fields to readonly and animate them when they show up in the basket?
回答1:
just add a click watcher to the span. Check this fiddle: http://jsfiddle.net/ranjith19/RgKV9/4/
I have done some basic changes. If you need custom names id's you should use a templating library and then append it
<div id="searchFields" class="control-group inlineForm">
<label for="regNr">Regnr</label> <input type="text" id="regNr" class="uprCase" placeholder="Regnr." size="6"
maxlength="6">
<label for="poNr">PO.nr</label> <input type="text" id="poNr" placeholder="PO.nr." size="12" maxlength="12">
<input type="button" value="GET INFO" class="last" id="getBaseInf">
<p></p>
</div>
<span class="addRegNr" style="display:inline"><a href="#">add another</a></span>
<script type="text/javascript">
$(document).ready(function () {
str_to_append = '<label for="regNr">Regnr</label> <input type="text" id="regNr" class="uprCase" placeholder="Regnr." size="6" maxlength="6">\
<label for="poNr">PO.nr</label> <input type="text" id="poNr" placeholder="PO.nr." size="12" maxlength="12">\
<input type="button" value="GET INFO" class="last" id="getBaseInf"><p></p>'
$(".addRegNr").click(function () {
$("#searchFields").append(str_to_append)
})
})
</script>
回答2:
You can do it, using jquery append method.
here I leave a link with some examples:
http://api.jquery.com/append/
回答3:
I guess, you might just be looking for something like this.
回答4:
I would do something like this:
<div id="searchFields" class="control-group inlineForm">
<label for="regNr">Regnr </label><input type="text" id="regNr" class="uprCase" placeholder="Regnr." size="6" maxlength="6"/><br/>
</div>
<span class="addRegNr">add another</span><br/>
<label for="poNr">PO.nr</label> <input type="text" id="poNr" placeholder="PO.nr." size="12" maxlength="12">
<input type="button" value="GET INFO" class="last" id="getBaseInf">
and then some js that looked like this:
var $input = $("#searchFields").children();
$(".addRegNr").on("click", function(){
var $newField = $input.clone();
// change what you need to do with the field here.
$(this).siblings("#searchFields").append($newField);
});
It's also here: http://jsfiddle.net/tatLw/
回答5:
To add any HTML with jQuery you will eventually end up calling .append() (or one of its variations, such as .before, .appendTo, etc.).
These can be passed raw HTML strings, but unless you have an HTML template ready and plain, don't use string concatenation to build your HTML as it is fragile and insecure. Instead create the elements with jQuery() as well, like:
jQuery('<input type="text"/>').attr({
value: '',
placeholder: '...',
id: '..'
})
.addClass('foo').appendTo( .. )
In addition, don't forget to create labels for these new elements as well (if appropiate).
Another few best practices relevant to this scenario:
If you're going to be dynamically making new form elements appear (as opposed to adding more additional fields for an existing field), it is best to not create these with JavaScript. Instead make sure they are present in the page output from the beginning, then hide them from $(document).ready
with .hide(). That way it will be a lot easier (as all you need is a reference to the hidden element, and call .show() when you have to). And that way it doesn't rely on javascript flow being present, enabled and functioning as expected because this way if anything happened along the way (exception thrown, cdn issues, whatever) the form will fallback to a fully-present version that just works.
If you're going to have a lot of these "+" or "add" button scenarios, I'd make a .clone() of the original field, strip it (clear value, remove id-attribute), and store it in a local variable. Then from the click handler, clone that, and put it into the document where you need it. You may also want to have a server-side fallback by making the add button a submit button with a certain name/value pair that the server detects as a non-final input in which case it will return the same page with the values pre-filled but with more fields.
回答6:
Basing solution on this blog post jQuery – Dynamically Adding Form Elements by Charlie Griefer, you could try the following:
Markup:
<div id="searchFields" class="control-group inlineForm">
<form id="myForm">
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
<label for="regNr">Regnr</label>: <input type="text" name="regNr" placeholder="Regnr." size="6" maxlength="6" />
<label for="poNr">PO.nr</label>: <input type="text" id="poNr" placeholder="PO.nr." size="12" maxlength="12">
</div>
<div>
<input type="button" id="btnAdd" value="add another Reg field" />
<input type="button" id="btnDel" value="remove fields" />
</div>
<input type="button" value="GET INFO" class="last" id="getBaseInf">
</form>
</div>
Javascript:
$('#btnAdd').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// manipulate the name/id values of the input inside the new element
newElem.children(':first').attr('id', 'regNr' + newNum).attr('regNr', 'regNr' + newNum);
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
// enable the "remove" button
$('#btnDel').removeAttr('disabled');
// business rule: you can only add 5 names
if (newNum == 5)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.clonedInput').length;
$('#input' + num).remove(); // remove the last element
$('#btnAdd').attr('disabled',''); // enable the "add" button
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');
DEMO: http://jsfiddle.net/chridam/qW9ra/