dynamic javascript when using load->view - javascript

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.

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 I autofill a widget with form inputs using Javascript?

I'm working on a donation form that has a widget embedded in it. The widget opts users into our Mobile Giving giving program which uses separate software than our donation forms. I've been asked to see if we can make the widget invisible but transfer the form data to it and submit it when the user submits the donation form. I've already run into a problem with getting the form data to transfer to the widget though.
The form should get the donors first name, last name and phone number from the form and then autofill the widget when a checkbox is clicked stating that the user would like to receive mobile updates.
Below is what I've tried but it doesn't seem to be working. The code for the form is relatively long so I just included the relevant fields but here is link to the full form: http://support.ddfl.org/site/Donation2?df_id=9442&mfc_pref=T&9442.donation=form1
I'm very new to Javascript so I'm not entirely sure if this is possible. Just an fyi, I also included console statements so I could see if the values were working.
<input type="text" name="billing_first_namename" id="billing_first_namename"
<input type="text" name="billing_last_namename" id="billing_last_namename"
<input type="text" name="donor_phonename" id="donor_phonename"
<input type="checkbox" name="mcoptin" onclick="FillMobileCause(this.form)" value="this.form"> Opt in to receive mobile updates.
Mobile messaging powered by Mobilecause<script>!function(d,s){var s=d.createElement("script"),h=(document.head||d.getElementsByTagName('head')[0]);s.src="https://app.mobilecause.com/public/messaging_widgets/q71xd/source";h.appendChild(s);}(document);</script>
<script>
function FillMobileCause(f){
if(f.mcoptin.checked == true){
console.log(f.billing_first_namename.value);
console.log(f.billing_last_namename.value);
console.log(f.donor_phonename.value);
if(f.billing_first_namename.value.length>=1){
f.firstname.value = f.billing_first_namename.value;
}else {
f.firstname.value = '';
}
if(f.billing_last_namename.length>=1){
f.lastname.value = f.billing_last_namename.value;
}else{
f.lastname.value = '';
}
if(f.donor_phonename.length>=1){
f.mobilenumber.value = f.donor_phonename.value;
}else{
f.mobilenumber.value = '';
}
console.log(f.firstname.value);
}
}
</script>
Please let me know if I'm leaving off important details. This is also my first StackOverflow post. ;)
I appreciate your help!
Your main issue is that you were referring to inputs in the mobilecause form as if they were in the same form, but they are in another (nested in your f main form).
function FillMobileCause(f){
var mcF = f.getElementsByClassName('mc-triggersubscription')[0];
if(f.mcoptin.checked == true){
mcF.firstname.value = f.billing_first_namename.value;
mcF.lastname.value = f.billing_last_namename.value;
mcF.mobilenumber.value = f.donor_phonename.value;
}
}
f is still the main form (the one that is the parent of the checkbox).
But now we have another one, mcF (mobilecauseForm), which is selected using the getElementsByClassName (this will search for a child with the mc-triggersubscription class). The [0] part is so the first match is selected (getElementsByClassName returns an array.
After that, all we need to do is assign the f inputs' values to the mcF ones.
Note: I left behind the "if empty" validation for simplifying. Anyway I don't think it's really needed, if a value is empty, there is no major issue in just copying it to the mobilecause value.

process tag before converting it into tag using bootstrap tags input

i am using bootstrap tags input in my site.
basically what i am trying to do is,
ask user to type urls into a text field, now if the text is valid url then only convert it into tag otherwise don't.
is there any way to process text before converting into tags?
any help would be appriciated.
Thanks
Bootstrap tags have beforeItemAdd event which triggered just before an item gets added. Bootstrap tags
$('input').on('beforeItemAdd', function(event) {
/* Validate url */
if (/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?#)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(event.item)) {
event.cancel = false;
} else {
event.cancel = true;
}
});
Bootstrap Tags Input have a hidden input before convert to tags you find it by following code:
$(".bootstrap-tagsinput input[type="text"]").keyup(function(){
// do your validation
});
you can see it by get an inspect element in your page. it will convert to tags after you press enter button you can do your validation until it's on hidden input.
It will be there:
<div class="bootstrap-tagsinput">
<span class="tag label label-info">Test<span data-role="remove"></span></span>
<input type="text" style="width: 7em;" size="1"> // here is!
</div>
If your input id is "tag-input", all you have to do is use a beforeItemAddcallback provided by the library itself like so:
$('#tag-input').on('beforeItemAdd', function(event) {
var tag = event.item;
if(true){ //if tag is not a url or process other text conditions.
event.cancel = true
}
});
If you don't set event.cancel to false, the add will go through.
You can check the documentation on this method here.
Also , as it is clear in this case that documentation does not say how to cancel the event. In such cases its simple enough to just check the code itself. I this case this code in the plugins github repo makes it plenty clear how to use this option.

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')

Check if a checkbox is checked in JS

I am new to js and jquery. Currently, I have a form at form.php which contains a checkbox. When the user clicks submit, the form variables are sent to a form.js file where each value is checked to be null or not.
The form.js file works perfectly, however, for the checkbox nothing seems to happen. I have a feeling this is due to the way I have declared the variable.
The following is the code for the js file:
var email = $('#email').val();
var website = $('#website').val();
var CHECKBOX = $('CHECKBOX').val();
...
...
if (CHECKBOX.checked == FALSE){
var error = true;
$('#notchecked_error').fadeIn(500);
}else{
$('#notchecked_error').fadeOut(500);
}
Try using:
if ( $('#CHECKBOX').prop("checked") )
or:
if ( $('#CHECKBOX').is(":checked") )
Also, be sure your selector for the checkbox is correct.
I see two problems in your code. The first one is that the selector in your CHECKBOX assignation is faulty. It should be
var CHECKBOX = $('#CHECKBOX').val();
or
var CHECKBOX = $('input[type=checkbox]').val();
the second problem is that you are reading CHECKBOX.checked from the val() function, you need to read it from the checkbox itself.
if(CHECKBOX.checked)
$('input[type=checkbox]:checked') // If you have multiple checkboxes you can use this and loop through them to get additional info
$('#checkboxID:checked').length // To get one specific checkbox
`$('CHECKBOX').val();`
Will try to find an element with a tagname of CHECKBOX and return it's value. Presumably you want to reference the checkbox with an ID of CHECKBOX:
var CHECKBOX = $('#CHECKBOX');
To see if it's checked:
if (!CHECKBOX[0].checked) {
// CHECKBOX is not checked
}
You really should learn basic javascript before using jQuery. Usually validation is initiated from a form submit, which can give you are reference to the form. You can then reference all of the form elements as properties of the form, you don't need to create all of those jQuery objects. e.g. if you form is something like:
<form ... onsubmit="validate(this)"... >
<input type="checkbox" name="checkbox">
</form>
Then in your validate function:
function validate(form) {
if (!form.checkbox.checked) {
// the checkbox isn't checked
}
}
You can attach the listener dynamically if you wish.

Categories

Resources