I would like to clone two input fields using JQuery - javascript

I am trying to create a form where the user might want to add two input fields dynamically, and this form is linked to the validate JQuery Plugin.
$('.addnote').on("click",function(){
countnotes++;
var newnote = $(".notes:first").clone();
newnote.find('input:file').val("");
newnote.find('input:text').val("");
var oldindexinput = countnotes-2;
var newindexinput = countnotes-1;
var attachement = newnote.find('#Justificatif'+oldindexinput+'Attachment');
attachement.attr('id','Justificatif'+newindexinput+'Attachment');
attachement.attr('name','data[Justificatif]['+newindexinput+'][attachment]');
var motif = newnote.find('#Justificatif'+oldindexinput+'Motif');
motif.attr('id','Justificatif'+newindexinput+'Motif');
motif.attr('name','data[Justificatif]['+newindexinput+'][motif]');
newnote.find('input:text[readonly]');
var firstnoteid = $(".notes:first").attr('id');
newnote.attr('id','notes'+countnotes);
newnote.attr('style','');
newnote.insertBefore('#'+firstnoteid).hide();
newnote.slideDown();
});
Here is the Html code
<input name="data[Justificatif][0][attachment]" type="text" readonly placeholder="Feuille de support" required>
<input name="data[Justificatif][0][motif]" placeholder="Motif de dépenses" class="input-medium" maxlength="255" type="text" id="Justificatif0Motif" required>
The problem with my code is that it clones the validation status as well with the new input fields, and I want to get rid of that.
Thank you
snapshot of the input fields cloned

Typically, during jquery validation, class='required' is applied to the elements which are validation during form submit.
Given, the elements you are cloning does have class='required' defined, you may simply remove it after cloning.
var newnote = $(".notes:first").clone();
newnote.removeClass('required');
Here's an example : http://jsfiddle.net/DinoMyte/TP768/268/

Some thoughts off the top of my head (based on a similar project I'm referencing):
Can you confirm that the id of the new input field is definitely unique. I see you calling "newnote.attr('id','notes'+countnotes);", but can you confirm the html is changed correctly?
If the id is unique, try unattaching and reattaching your validation engine. (In my code I kill everything and recreate my forms every time there's a change, then re-call jQuery($('form[name$="config_form"]')).validationEngine('attach');)

Related

Dynamically changing form action not working for MailChimp

I am using a checkbox to change the form action on a MailChimp-form dynamically. When the DOM is loaded, the form action URL is something like this:
https://X.us3.list-manage.com/subscribe/post?u=X&id=X&EBIRD=XYZ
When I submit the form, the EBIRD-value of XYZ is pushed to MailChimp. Now, when I check the checkbox, I can see from the DOM and my console that the new form action is this:
https://X.us3.list-manage.com/subscribe/post?u=X&id=X&EBIRD=NEW-VALUE
Why is it then, that submitting the form still pushes XYZ and not NEW-VALUE? I have been in touch with MailChimp technical support. They said that when choosing "View Source" on the page, the old value was still there. But isn't that just because that is how the page is loaded in the first place?
Relevant HTML:
<form action="https://X.us3.list-manage.com/subscribe/post?u=X&id=X&EBIRD=XYZ" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
Relevant jQuery:
var formActionYes = "https://X.us3.list-manage.com/subscribe/post?u=X&id=X&EBIRD=NEW-VALUE";
var formActionNo = "https://X.us3.list-manage.com/subscribe/post?u=X&id=X&EBIRD=NEW-VALUE-2";
$('#cu-ebird').change(function() {
if(this.checked) {
$("#mc-embedded-subscribe-form").prop('action',formActionYes);
console.log($("#mc-embedded-subscribe-form").prop('action'));
} else {
$("#mc-embedded-subscribe-form").prop('action',formActionNo);
console.log($("#mc-embedded-subscribe-form").prop('action'));
}
});
The console logs what I want. The DOM shows what I want. MailChimp recieves the old value.
What am I missing?
Don't use HTML entities like & in JavaScript strings. That's only processed in HTML code, not when properties are assigned in JavaScript.
var formActionYes = "https://X.us3.list-manage.com/subscribe/post?u=X&id=X&EBIRD=NEW-VALUE";
var formActionNo = "https://X.us3.list-manage.com/subscribe/post?u=X&id=X&EBIRD=NEW-VALUE-2";
Although I'm not sure why this would impact the EBIRD parameter. It should cause the id parameter to be renamed to amp;id.
Another thing you could try is using .attr() rather than .prop().
This can be solved by not trying to change the form action at all. Just remove the merge field from the form action. Instead, you need to add a hidden input field to your form:
<input id="ebird" type="hidden" name="EBIRD" value="">
Then you change the value of this using the script:
$("#ebird").attr('value','NEW-VALUE');
Voila, everything shows up in MailChimp as it should.

How do you you copy data from one field to another and append a text string in javascript

So I've got a pdf that is a form fillable student information card, my boss wants me to write javascript code that copies the whatever is typed in the username field into the email field and append the new text in the email field with #College.edu
So I've done bit of research and found a code snippet that gets the job half done with a function, but now I can't activate this function. All of my google searches either use jquery to get this done or html and I can't use either of those since I'm programming this in a pdf document
Here's the code I have so far:
function copydata(){
var box1 = document.getElementById("Username");
var box2 = document.getElementById("Email");
box1.value = box2.value;
}
I tried everything I can think of to get this function to execute with like an onblur or onfocus method, I would be fine with it if it copied over as the person was typing into the first field. Nothing I do works however and the debugger console literally tells me nothing. Any help would be appreciated.
Form Fallible
Debugger Error
Did you mean that?
function handleChange(e) {
document.getElementById("Email").value = e.target.value + "#College.edu";
}
Username.addEventListener("keyup", handleChange, false);
<input type="text" id="Username" />
<input type="email" id="Email" />

Javascript to "copy in real time" some fields from a form to another form (with different input names)

I'm trying to write a function to copy some fields (in real time) from a specific form, to another form
I try to be more specific:
I have 2 forms
- The first form is the one the user will fill in.
- The other form is hidden.
When the user will fill the first form, the second form (hidden) will be filled by the same informations.
Some fields are automatically filled by some calculations, so I can't use keyup/keypress or "click" to start the function
I wrote something like this, but it doesn't work
$(function(){
var form1 = $('#form1'),
form2 = $('#form2');
$('#fieldname_form1').change(function(){
$('input[name="inputname2"]', form2).val(function(){
return $('input[name="inputname1"]', form1).val();
});
});
});
You can copy in real time using the keyup function, something like this. Otherwise, when you say
Some fields are automatically filled by some calculations
What do you mean? These calculations are made by you using JS or what? Because, if you are using JS you can fill the two fields at the same time when you make the calculations.
this works for me...
$(function() {
$('#i1').change(function(evt) {
$('#i2').val(evt.target.value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="name1" id="i1" />
</form>
<form>
<input type="text" name="name2" id="i2" />
</form>
The change event is fired after the element has lost the focus. For the "user editable" elements you should use keyup (for the textbox) and change for the drop down elements.
On the other hand, for the fields filled automatically, you don't have any nice and clean solutions. I can think in two options:
If the calculations trigger is always the user changing some value, you could copy every form value after that happens.
(very bad option, but it would still work) You could be constantly checking for changes in every element and copying them using setInterval function.
As a side note
As well as your code should work, there is a simpler way to do it:
$('#fieldname_form1').change(function(){
var value = $('input[name="inputname1"]', form1).val();
$('input[name="inputname2"]', form2).val(value);
});
This should work -
$(function() {
var form1 = $('#form1'),
form2 = $('#form2');
$('#fieldname_form1').change(function() {
$('input[name="inputname2"]', form2).val($(this).val());
});
});

dynamic javascript when using load->view

I have a form with a « newInput » button, which add dynamically in javascript a new input when I click to it.
When I have an error in my form, I re-load the view with the form. It’s normal, but .. Because I use dynamic javascript for adding new input, all the input added are removed when I reload..
There is something I can do ?
This is an exemple of my view.tpl :
<input
type="text"
placeholder="ex: cerise"
onfocus="javascript:autoComplet('jigd1', '{site_url('recettes/getIngredient')}')"
value="{set_value('igd[]')}" id="jigd1" name="igd[]"
/>
{form_error('igd[]')}
I add a partiel code of my js file
var cpt=1;
function addField(uriIngredient, uriLabel) {
try
{
cpt=cpt+1;
var inputIgd = document.createElement('input'),
button = document.createElement('input'),
div = document.createElement('div'),
inputIgd.setAttribute('type','text');
inputIgd.setAttribute('name','igd[]');
inputIgd.setAttribute('id','jigd'+cpt);
button.setAttribute('type','button');
button.setAttribute('onclick','javascript:supField("igd'+cpt+'")');
button.setAttribute('value','Supprimer');
div.setAttribute('id','igd'+cpt);
div.appendChild(inputIgd);
div.appendChild(button);
document.getElementById("listIgd").appendChild(div);
...
After some research, I tried to look at what someone said me, that's say localStorage, and it is very nice. But I used an exemple for only one input because i wrote it in my html, but I don't know how to do for recreate all inputs .. And particularly because I use javascript to add new inputs, I don't know if I can recreate all inputs .
check the form before submitting, that way you won't have to reload the page, for example using jquery ...
$("#myformid").on("submit", function(){
var goodtogo = true;
// some code here to check the form, if there's an error --> goodtogo = false;
if (!goodtogo) return false; // and some other code to display the errors
});
That way, if there's an error , the form won't submit and won't reload.
If you have to check something in a database (for example) like checking if a username already exists, you'll have to use ajax.

Codeigniter dynamic javascript when using load->view

I have a form with a « newInput » button, which add dynamically in javascript a new input when I click to it.
When I have an error in my form, I re-load the view with the form. It’s normal, but .. Because I use dynamic javascript for adding new input, all the input added are removed when I reload..
There is something I can do ?
This is an exemple of my view.tpl :
<input type="text" placeholder="ex: cerise"
onfocus="javascript:autoComplet('jigd1', '{site_url('recettes/getIngredient')}')" value="{set_value('igd[]')}" id="jigd1" name="igd[]"/>
{form_error('igd[]')}
I add a partiel code of my js file
var cpt=1;
function addField(uriIngredient, uriLabel) {
try
{
cpt=cpt+1;
var inputIgd = document.createElement('input'),
button = document.createElement('input'),
div = document.createElement('div'),
inputIgd.setAttribute('type','text');
inputIgd.setAttribute('name','igd[]');
inputIgd.setAttribute('id','jigd'+cpt);
button.setAttribute('type','button');
button.setAttribute('onclick','javascript:supField("igd'+cpt+'")');
button.setAttribute('value','Supprimer');
div.setAttribute('id','igd'+cpt);
div.appendChild(inputIgd);
div.appendChild(button);
document.getElementById("listIgd").appendChild(div);
...
Since you are appending new input/button to dom dynamically and not saving its state by making ajax call/submitting form you cannot retain the input/button after reloading the page.
Using localStorage, to keep the information of previously added input/buttom would be preferable.
PS : since you havent added any code which you tried, its really hard to explain localStorage with specific code.
as soon as you append, add the state of the form into localStorage,
When you loading the page, look for the localStorage to check the previously added inputs
you can set the item into localStorage :
window.localStorage.setItem('key','value')
You can retrieve them like this :
window.localStorage.getItem('key')

Categories

Resources