Create new form fields with jQuery - javascript

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">add another</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?

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">add another</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>
​

You can do it, using jquery append method.
here I leave a link with some examples:
http://api.jquery.com/append/

I guess, you might just be looking for something like this.

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/

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/

To add any HTML with jQuery you will eventually end up calling .append(), or one of its variations like .before, .appendTo, etc.
These can be given raw HTML strings, but unless you have an HTML template ready and plain, don't use string concatenation to build your HTM. This is fragile and insecure. Instead, create the elements with jQuery() directly, like so:
jQuery('<input type="text"/>').attr({
value: '',
placeholder: '...',
id: '..'
})
.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.

Related

In Django, how to modify field names in dynamic forms using Java Script

I created a form. Using jQuery got first para of form. Using add function I am adding it again.
With this I am getting same names for all the new fields. I am not able to retrieve its values in views.py.
Is there any way to change form field names in js? or any other solution to it?
JS Function:
$(".add").click(function() {
$("form > p:first-of-type").clone(true).insertBefore("form > p:last-child");
return false;
});
$(".remove").click(function() {
$(this).parent().remove();
});
With this JS I am cloning this lines,
<input type="text" name="med" maxlength="100" required id="id_medicine">
While sending it back, I need to change name of the input field(med to med1). So, that I can fetch all values in views.py
You are just cloning what is there on first para of form, use input name as array and use different empty inputs with same array name when adding of next para.
for eg-
<div class="row">
<input type="text" name="arr1[]" >
<input type="text" name="arr2[]" >
</div>
<button id="add"> Add</button>
$('#add').click(function(){
$('.row').append('<input type="text" name="arr1[]" ><input type="text" name="arr2[]">');
})

Move data from on input field to another and submit form

I am trying to get one input field that is higher up the page, move it's content to a form field at the bottom of the page and submit the form.
Please see what I have done here (doesn't work):
$('#move_down').click(function() {
$('#input_1').val($('#input_2').val())
});
<input type="text" id="input_1" value="">
<br>
<button id="move_down">Click Here</button>
<br>
<input type="text" id="input_2" value="">
<script src="//code.jquery.com/jquery-3.2.0.js"></script>
Moving the data is just the first part, I am also trying to get it to take the user down to the main form and submit it - is this possible with jQuery?
Updated the question to fix my silly error of omitting the ID selectors. Just need to figure out how to submit the form now.
You are right; just correct your query selector:
$('#move_down').click(function() {
$('#input_2').val($('#input_1').val())
});
http://jsfiddle.net/82x28ryr/4/
Missing the # prefix for id selector
Works fine doing
$('#move_down').click(function() {
$('#input_2').val($('#input_1').val())
});
<input type="text" id="input_1" value="">
<br>
<button id="move_down">Click Here</button>
<br>
<input type="text" id="input_2" value="">
<script src="//code.jquery.com/jquery-3.2.0.js"></script>
As for "moving down" you have only provided html in demo for 2 inputs. You need to update question with all relevant html in order to implement additional features

How to add a hidden list of IDs to a form in Javascript?

I've got a simple form in html:
<form action="" method="post">
<input id="title" name="title" size="30" type="text" value="">
<input type="submit" value="Save this stuff">
</form>
I also have a file upload on the page, which handles uploads using ajax and adds the files to a mongoDB. The file upload returns the mongoDB id of the file (for example 12345) and I want to add that id to the form as a hidden field so that the id is POSTed to the server upon submitting the form. Since the user can add multiple files though, I want to add a list of id's to the form.
I found how I can add one hidden field to a form from javascript, but this always handles a single field, not a field with multiple values. So I thought of adding a checkbox field to the form so that I can submit multiple values in one element, but it kinda feels like a hack.
Can anybody hint me in the right direction on how I can add a hidden list of values to a form using Javascript? All tips are welcome!
[EDIT]
In the end I would like the form to look something like this:
<form action="" method="post">
<input type="hidden" name="ids" value="[123, 534, 634, 938, 283, 293]">
<input id="title" name="title" size="30" type="text" value="">
<input type="submit" value="Save this stuff">
</form>
I am not sure if I understand your question correctly, so I may just be guessing here.
Try adding multiple hidden inputs with a name such as ids[] so that they will be posted to the server as an array.
Example:
<form action="" method="post">
<input type="hidden" name="ids[]" value="123">
<input type="hidden" name="ids[]" value="534">
<input type="hidden" name="ids[]" value="634">
<input type="hidden" name="ids[]" value="938">
<input type="hidden" name="ids[]" value="283">
<input type="hidden" name="ids[]" value="293">
<input type="submit" value="Save this stuff">
</form>
Why not simply concatenating all the ids into a string like so "123,456,890,..etc" and then adding them as a value to ids inupt. When you need them, simply split by ',' which would give you an array with ids?
Todo so only with javascript something like this should work
var elem = document.getElementById("ids");
elem.value = elem.value + "," + newId;
Do you mean that for each time the user clicks the 'upload' button you need to add a hidden field to the form?
Can you post the entire form, that should clear things up...
[Edit]
you could store the id's in an Array, everytime an id should be added to the hidden field's value you could do somthing like:
$('#ids').attr('value', idArray.join());
I'm just typing this out of the box so excuse any little errors

Copy input field's value to multiple hidden fields... but with same ID's?

1) I have 3 input radio buttons with unique values.
For e.g.
<input type="radio" id="id1" value="This is first value" />
<input type="radio" id="id2" value="This is second value" />
<input type="radio" id="id3" value="This is third value" />
2) Next, I have 2 hidden form like this:
<form action="//mysite.com/process1.php"><input type="hidden" id="uniqueid" value=""></form>
<form action="//mysite.php/process2.php"><input type="hidden" id="uniqueid" value=""></form>
3) Based upon whichever radio button the user clicks, I need to copy its value to the value of both the above forms hidden field.
For e.g. If user clicks on radio with id1, then it's value "This is first value" should be copied to both the forms hidden field.
CONSTRAINTS:
1) Have to use javascript or jquery, no server side processing available.
2) Note: both the final forms have one input field, but with same id. This is a constraint.
3) Why? Because based on some other actions on the page, the user gets to see one of the 2 forms. The only difference between them is their action is unique. All fields are same.
WHAT I HAVE SO FAR:
Using this, I am able to copy the value from the radio button to a hidden field's value, but it only copies to a field with a UNIQUE ID.
var $unique = $("#unique");
$("#radio1").keyup(function() {
$unique.val(this.value);
});
$("#email").blur(function() {
$unique.val(this.value);
});
Can someone guide as to how can the value be copied to multiple input fields, but with same id's?(Yes, the id's of the initial radio buttons can be unique.)
Having two HTML elements with same ID is an error.
You cannot treat this as a constraint, this is NOT a valid HTML code and it will cause inconsistent behavior in different browsers.
Use classes instead:
<form action="//mysite.com/process1.php"><input type="hidden" class="uniqueid" value=""></form>
<form action="//mysite.php/process2.php"><input type="hidden" class="uniqueid" value=""></form>
And javascript:
var $unique = $(".uniqueid");
However, I couldn't find any #radio1 or #email in your code, are you sure you have the right selectors?
My recommendation for the JS will be: (Working jsFiddle)
var $unique = $(".uniqueid");
$('input[type="radio"]').click(function(){
$unique.val(this.value);
});
Notes for jsFiddle:
I've used click event instead of keyup (don't really understand why you used keyup here..).
I've given all radio buttons the same name so they will cancel each other out when selected.
I've turned the hidden fields to text so you could see the result.
<form action="//mysite.com/process1.php"><input type="hidden" class="uniqueid" id="uniqueid" value=""></form>
<form action="//mysite.php/process2.php"><input type="hidden" class="uniqueid" id="uniqueid" value=""></form>
var $unique = $("input[type=hidden].uniqueid");
$("#radio1").keyup(function() {
$unique.val(this.value);
});
$("#email").blur(function() {
$unique.val(this.value);
});
As said by others, id must be unique. Try using a data-attribute:
<form action="//mysite.com/process1.php">
<input type="hidden" data-shouldupdate="true" value="">
</form>
<form action="//mysite.php/process2.php">
<input type="hidden" data-shouldupdate="true" value="">
</form>
Now you can use that attribute as selector to do something like:
$('[data-shouldupdate]').val(this.value);
I agree with all other who posted that id have to be unique to have correct HTML document. So if it's possible I strictly recommend you to fix the HTML document to remove all duplicates.
I write my answer only for the case that you can't remove id duplicates because of some reason and you still have the same requirements. In the case you should change the line
var $unique = $("#uniqueid");
to
var $unique = $("*[id=uniqueid]");
The selector *[id=uniqueid] (or just [id=uniqueid]) works slowly as #uniqueid, but it allows you to get all elements with the specified id attribute value. So it works even in case of id duplicates on the HTML page.
The most simple solution is to give a same name to both inputs. Check this link jsfiddle to see a working example. The code used is the one given is below:
HTML:
<input type="radio" name="copiedValue" id="id1" value="This is first value" />
<input type="radio" name="copiedValue" id="id2" value="This is second value" />
<input type="radio" name="copiedValue" id="id3" value="This is third value" />
<form action="//mysite.com/process1.php"><input name="uniqueid" id="uniqueid" value=""></form>
<form action="//mysite.php/process2.php"><input name="uniqueid" id="uniqueid" value=""></form>
jQuery/javascript:
$("input:radio[name=copiedValue]").click(function() {
$("input[name=uniqueid]").val($(this).val());
});
The radio-buttons should have the same name. I removed the type="hidden" so u can see it working correctly.
Hope it useful!

radio buttons + input field for one of them

I tried the following but it returns two pieces of data to the server. This is a problem for my gateway, and I get an error.
I used this for one of my attempts:
<script type="text/javascript">
if( $('#other).is('):selected') )
{
// user wants to enter own value
$('[name="installments"]").not('[type="text"]').attr('name', '') // remove all
values apart from the entered text.
}
</script>
<body>
<FORM ACTION="http://www.cs.tut.fi/cgi-bin/run/~jkorpela/echo.cgi" METHOD="POST">
<br><br>
<input type="radio" name="installments" id="r1" checked="checked" value="99">
Open-Ended - I can stop them via email at any time.<br>
<label for="installments">number of payments</label><br>
<input type="radio" name="installments" id="other" value="Enter Custom.."><br>
<input type="text" name="installments" value="" maxlength="4" size="4">
<br><br><br>
<input type="submit" name="btnSubmit" value="Submit" />
</form>
This returns either -
installments 99
installments (empty)
or
installments Enter Custom..
installments 5
I can only have one return for the var 'installments' either 99 or the number they imputed.
I have tried various ways of doing this using JS and allowing the user to make a choice with the same results - two instances of the var 'installments' being sent.
Is there a javascript way to test the input field and if a number is entered then disable using id(s) the extra radio button so it can't send any data? Or is there a better way to do this?
Solved
I found the answer & Here it is
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#user_input').change(function() {
$('#use_user_input').val($(this).val());
});
});
</script>
And Html Here:
Total number of payments...</span><br>
<input type="radio" name="installments" checked value="99">
Open-Ended -
<input id="use_user_input" type="radio" name="installments" value="">
limited number of payments -
<input id="user_input" type="text" value="" maxlength="4" size="4"></span>
You would want to give the input text field a different name from the radio inputs, then handle the text field's POST as a separate variable from the radio buttons in the HTTP request. Also, give the second radio input a value, such as "other" so you know to handle the associated text input.
If you only have the ability to receive one field from the form you will need to alter the form as the user fills it in. Currently the form works if the user selects one of the values delimited by the radio buttons. The problem, I gather, is that the status of the radio buttons overrides the value of the text field even if the user selects the "other" option of filling in the text box.
The solution is to use a script that is triggered when the user changes the content of the text box. This script will read the value of the text box and assign that value to the 'other' radio button.
We can do this using the onchange event:
<input id="otherRadio" type="radio" name="installments" value="" /><br />
<input id="otherText" type="text" value="" maxlength="4" size="4" onchange="applyOtherOption()" />
If you try this now, it will cause a javascript error on your page when you change the value of the the text field. This is because the browser fails to find a javascript function with the name applyOtherOption. Let's change that now:
<script type="text/javascript">
function applyOtherOption() {
var textField = document.getElementById("otherText");
var radioField = document.getElementById("otherRadio");
radioField.value = textField.value;
}
</script>
The result is that the "other" radio button's value is always changed to whatever the user enters into the text field and if this radio is selected, this is what is sent with the form.
Important
I've been a bit lazy here and typed out the easiest way to access the content of the form elements. This will work on most (probably all major) browsers but it is not the way it should be done. The proper method is to access the form first, then from the form element access the fields. To do it right you should read this article on setting the value of form elements.
I hope this is useful.

Categories

Resources