Codeigniter 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);
...

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

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.

Struts- About saving checkboxes when following a link

I'm working on a jsp containing some checkboxes. My jsp is linked to a form (called SuiviTransfertForm), and this form has an attribute called checkboxUID, which is an array containing the ids of my checked checkboxes.
private String[] checkboxUID = {};
This attribute is mapped with the checkboxes of my jsp like this :
<html-el:multibox name="suiviTransfertForm" property="checkboxUID"/>
I would like to follow a link on this jsp and get the content of checkboxUID when I'm on the next page.
On the next page, I'm getting back my form like this :
SuiviTransfertForm suiviTransfertForm = (SuiviTransfertForm) form;
The problem is that checkboxUID is correctly filled if I stay on the same page, but always empty when I'm changing page. I can't find a way to achieve this.
Many thanks for your help !
When you're clicking the link it's not submit the form. Hence you cannot get any values from form. Try sending through URL (script way - though it's not a best practice)
var arrayValues = [12,34,54,67]; //Get the selected checkbox values when clicking link
var QueryString = JSON.stringify(arrayValues);
var a = document.getElementById('yourlinkId');
a.href = 'myLink?params='+QueryString;
or you can use jQuery for simple code,
$('#yourlinkId').attr({"href" : '/myLink?params=' + arrayValues.join(',')});
Try and let me know if it helps.
I finnaly fixed the problem by listing my checked checkboxes and setting them to the form after clicking my link.
Many thanks for your help guys !

Jquery doesn't update an attribute as expected

I have an MVC App and on one of my pages as part of the display I will render one of two partials based on a user selection of a radio button. This bit all works ok, but I have a button on the main form where I need to set/reset values that will be passed to my controller based on the user selection. The button is declared on my main form as:
#Html.GlobalModalAuthorizeButton("Upload Document", "Upload", "Documents", new { serviceUserId = Model.ServiceUser.Id, folderId = Model.CurrentFolderId, viewType = Model.ViewTypes.ToString() }, new { #class = "icon upload btn-primary" })
when this page is initially rendered the viewtype is set to the default view that the user is initially presented with. when the user changes the view the viewtype doesn't seem to get updated. So from the partial that has been loaded I try to set the value to the correct value. Using the Chrome browsers Developer tools if I do the following:
$(this).parent().parent().parent().parent().find($('.upload')).attr('data-url').replace('FileView', 'TreeView');
it returns in the console window the value I want (idea is that i set the value on the button before the user presses it). The trouble is the above doesn't really seem to have changed the data-url attribute on the button so consequently when the controller is hit, 'FileView' is still passed through.
For full attribute:
var new_attr = "/ServiceUser/Documents/Upload?serviceUserId=21&viewType=FileView";
$(this).parent().parent().parent().parent().find($('.upload')).attr('data-url', new_attr);
Or, as #Rup already suggested, you should first get the original attribute value, modify that using replace method and then reassign the new_attr.
jQuery got a special method to read and write data attributes:
var uploadButton = $(this).parent().parent().parent().parent().find('.upload');
var currentUrl = uploadButton.data('url');
uploadButton.data('url', currentUrl.replace('FileView', 'TreeView'));

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.

Cannot select table row id using jquery after ajax update

I have a html table containing data rows. I am building add/edit/delete functionality to the table using AJAX.
The format of my table row is as follows:
<tr id="281"><td class="todo-task">fdgdg</td><td>some more data</td><td>EDIT BUTTON</td></tr>
At the moment I have a working AJAX function to both add a new row and edit a row via a prepend().
In order to edit a table row, you click the edit button which pulls the values into the form and submits ... simples so far. Here's the code for the edit click and the form markup. Note the id from the edit click goes into a hidden field in the form.
$("button.edit-todo").bind("click", function(){
var task = $(this).closest('tr').children('td.todo-task').text();
var todoID = $(this).closest('tr').attr("id");
$("div#todo-form input.todo-task").val(task);
$("div#todo-form input.key").val(todoID);
});
...
<form id="mgnt-edit-todo-form" class="record-edit-form">
<input type="text" class="todo-task input" name="task">
<input class="key" name="key" type="hidden" value="279">
<button class="update uk-button uk-modal-close" type="submit">Save</button>
</form>
... and the ajax bit which binds the hidden field for the update.
$("button.update").bind("click", function(e){
var key = $(this).closest('.key').attr('value');
$.ajax({
type: "POST",
url: "update-record.php",
//etc etc etc
The problem
The first update works fine, it will prepend a table row including the id. The issue occurs when I then wish to make a further update to that same "prepended" row. Whilst the DOM shows the markup as correct the function on button.edit-todo will no longer get the id. When looking at the form markup in the DOM, the value of the hidden field is blank.
I've looked at the source in Chrome and I can see that it does not match the view in the browser/DOM. For example, the markup is all the same, but the rows have been put into a different order - it looks as though by date. (There is a date field but I have cut down the fields for this example..) I think this is causing the issue ... question is why? and how do i fix it?
Thanks
Update
Here is my markup in the DOM, looks fine to me.
To be absolutely clear the issue is occuring when clicking the edit button.
It calls the following function (now using 'on':
$("button.edit-todo").on("click", function(){
//load the data from this row
var task = $(this).closest('tr').children('td.todo-task').text();
var client = $(this).closest('tr').children('td.todo-client').text();
var due = $(this).closest('tr').children('td.todo-due').text();
var todoid = $(this).closest('tr').attr('id');
$("div#todo-form input.todo-task").val(task);
$("div#todo-form select").val(client);
$("div#todo-form input.todo-due").val(due);
$("div#todo-form input.key").val(todoid);
});
Clicking row 286 works as intended (it was present on the page load) in that the tr id is added to the hidden field in the form. Clicking row 297 (as far as I'm aware in the DOM?) does not pass the id to the hidden field...
Please help!!! Doing my head in...!
Instead of .bind use .on:
$("button.edit-todo").on("click", function(){
(...)
and
$("button.update").on("click", function(e){
(...)
Using ID for loaded data is not very comfortable way anymore. Use class instead of ID.
Also jQuery has changed "bind" to "on" method. I recommend to use "on".
For example:
$(document).on("click", ".edit-todo", function(){
var task = $(this).closest('tr').children('.todo-task').text();
var todoID = $(this).closest('tr').attr("id");
$(".todo-form .todo-task").val(task);
$(".todo-form .key").val(todoID);
});
Also, source shows the code when the document loads, not the dynamic DOM.

Categories

Resources