Adding multiple variables in the page URL using javascript - php

Since I'm relativly new to the use of php and javascript I ran into this problem while trying to add multiple variables in a URL
I use the following script:
<script>
function refresh() {
var PCWDE = document.getElementById("PC");
var NMWDE = document.getElementById("naam");
var VNMWDE = document.getElementById("voornaam");
var ONDWDE = document.getElementById("onderneming");
var BTWWDE = document.getElementById("btwnummer");
var LNDWDE = document.getElementById("land");
this.document.location.href = "http://example.com/form.php?PCS=" + PCWDE.value "&nm=" + NMWDE.value "&vnm=" + VNMWDE.value "&ond=" + ONDWDE.value "&btw=" + BTWWDE.value "&lnd=" + LNDWDE.value;
}
</script>
That's beeing activated trough the following html code:
<?php
$pc = $_GET['PCS'];
echo '<input type="text" name="pc" id="PC" onblur="refresh()" value="'.$pc.'">'
?>
The main reason for the use of this html code was that I needed to execute a query without submitting the form, while still beeing able to hold the value of the text box even when the page would refresh. The above html code is used multiple times with the use of different ID's.
The problem I face while trying to do this is that my code only works when only adding 1 variable to the URL like so:
this.document.location.href = "http://example.com/form.php?PCS=" + PCWDE.value;
Otherwise it does not work. Either the 'onblur' event fails to work, or the script fails to run.
Is there a way to add the multiple variables to the URL in a similiar way to what i'm doing now?

You forgot plus signs. That's a syntax error and you should see the error message if you open the error console. (on firefox you press control-shift-j)
Shoule be:
this.document.location.href = "http://example.com/form.php?PCS=" + PCWDE.value + "&nm=" + NMWDE.value + "&vnm=" + VNMWDE.value + "&ond=" + ONDWDE.value + "&btw=" + BTWWDE.value + "&lnd=" + LNDWDE.value;

Related

Generating tags to search for in Flickr API from database

I'll try to keep this simple and clear. I'm pretty new to using API's but I'm using the Flickr API to search for and display photos on my website based on a certain tag. For a simple, static web page this is quite simple and I've already got it working as intended. This is the jquery script I found to use:
$(function() {
var apiKey = 'MY_API_KEY_IS_IN_HERE';
var tag = '%23FFLIVE2014-09-03';
var perPage = '25';
var showOnPage = '6';
$.getJSON('http://api.flickr.com/services/rest/?format=json&method='+
'flickr.photos.search&api_key=' + apiKey +
'&tags=' + tag + '&per_page=' + perPage + '&jsoncallback=?',
function(data){
var classShown = 'class="lightbox"';
var classHidden = 'class="lightbox hidden"';
$.each(data.photos.photo, function(i, rPhoto){
var basePhotoURL = 'http://farm' + rPhoto.farm + '.static.flickr.com/'
+ rPhoto.server + '/' + rPhoto.id + '_' + rPhoto.secret;
var thumbPhotoURL = basePhotoURL + '_s.jpg';
var mediumPhotoURL = basePhotoURL + '.jpg';
var photoStringStart = '<a ';
var photoStringEnd = 'title="' + rPhoto.title + '" href="'+
mediumPhotoURL +'"><img src="' + thumbPhotoURL + '" alt="' +
rPhoto.title + '"/></a>;'
var photoString = (i < showOnPage) ?
photoStringStart + classShown + photoStringEnd :
photoStringStart + classHidden + photoStringEnd;
$(photoString).appendTo("#flickr");
});
$("a.lightbox").lightBox();
});
});
Create a #flickr div on a page and load that script, photos tagged #FFLIVE2014-09-03 would be displayed, if there are any. My problem is that the site/page I want to show the photos on is dynamic with data generated from a database. So website.com/page.php is the single page, in the database is data for a certain date and a performance that happened on it (For a band).
So what I'm struggling with is how to dynamically edit the tags searched for in the script. With the above script placed in my page.php obviously page.php?id=1 and page.php?id=261 will show the same photos, because the tags searched will be the same when in fact they should be different, based on the date for the data.
So, is there some way to do this? Generate the correct date tag to search for based on the database data? I can generate the correct tag inside the PHP file itself quite easily, just echo the first part of the tag then the date. But how would I do that in relation to the javascript? I gather it is possible to use PHP within Javascript but that would be outside the database, so it wouldn't know what it was generating.
I hope that makes sense!

jQuery AJAX can't work when injected on external URL?

I am currently trying to retrieve some data from book search sites and populate a personal database with that data. My idea is to inject the necessary jQuery on the page, so that when I see a title I think I'd like to return to in future, I can then just click a cheeckbox, make necessary additional comments, which I then hope to submit by AJAX to a PHP script which then populates my MySQL database for me with the appropriate title.
Do look at this example for a library catalogue:
// for every book entry, append checkboxes
$('.document-frame').append('<p>Choose:?<input type="checkbox" class="Jcustom_c" /></p><p>Serendepity?:<input type="checkbox" class="Jserep" /></p><p>Include snippet?:<input type="checkbox" class="Jsnippet" /></p>');
// append a Submit button at the bottom of the page, and a blank div for feedback upon success in POST-ing the necessary data
$('#resultPage').append('<input id="Justin" class="Jcustom" type="submit"/><div id="Jfeedback"></div>');
// whenever my checkbox is checked, retrieve / "scrape" the necessary book data
$('.Jcustom_c').change(function() {
if ($(this).is(':checked'))
{
var title = $(this).parent().parent().find('.title a').text();
var author = $(this).parent().parent().find('.authors a').text();
var publishd = $(this).parent().parent().find('.publisher').text();
var status = $(this).parent().parent().find('.metadata .summary').text();
var img_link = $(this).parent().parent().find('img.artwork').attr("src")
// create an XML string from that data. Escape "<" and ">", otherwise when we append the string to the browser for feedback, the browser will not render them correctly.
var appended = '<div class="Jappended"><item><title>' + title + '</title><author>' + author + '</author><publisher_n_edn>' + publishd + '</publisher_n_edn><status>' + status + '</status><image>' + img_link + '</image><serep>N</serep></item></div>';
// show the string just below the book title. Hence if I "pick" the book from the catalogue, the XML string will show up to confirm my the fact that I "picked" it.
$(this).parent().parent().append(appended);
}
// if I uncheck the box, I remove the XML string
else {
$(this).parent().nextAll(".Jappended").remove(appended);
$(this).parent().prevAll(".Jappended").remove(appended);
}
});
And then I have the AJAX:
$('#Justin').click(function(e) {
e.preventDefault;
var string = "<itemset>";
$(".Jappended").each(function() {
var placeh = $(this).text();
string = string + placeh;
$('.results_container').append(string);
})
// these come from <textarea> boxes I append to the end of the page just before the Submit button. (Above, I did not include the jQuery to append these boxes.)
var odp = $("#odp").val()
var mre = $("#motivation_revisit").val()
var mra = $("#motivation_rationale").val()
var stu = $(".hdr_block h5 span").text()
var string = string + "<odpath>" + odp + "</odpath><stused>" + stu + "</stused><motivation><revisit>" + mre + "</revisit><rationale>" + mra + "</rationale></motivation></itemset>"
var post_var = { xml_string : string, source : "NUS" };
$.post('http://localhost:8888/db-ajax.php', post_var , function(data) {
$('#Jfeedback').html(data);
});
My problem is that I can't seem to get the AJAX to work: When I click on my Submit button, I do not see the output I would expect when I used the exact same jQuery on an HTML file I called from localhost. This, which I called using http://localhost:8888/some_html.html worked:
<html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script>
$(document).ready( function() {
...
$('#Justin').click(function(e) {
e.preventDefault;
var string = "<itemset>";
/*
$(".Jappended").each(function() {
var post_var = { xml_string : "hello", source : "NUS" };
$.post('http://localhost:8888/db-ajax.php', post_var , function(data) {
// if (data == "Success") {
$('#Jfeedback').html(data);
// }
});
});
});
</script>
<body>
...
</body>
</html>
db-ajax.php is simply:
echo "Success";
I have read this post: jQuery cannot retrieve data from localhost, which mentions something about "JavaScript cannot currently make direct requests cross-domain due to the Same-origin Policy". Is this the reason why my code didn't work on the external page? If yes, what can I do to make the code work, or what other approaches can I adopt to achieve the same goal? I have mutliple book search sites that I am working on, and many of these do not have an API where I can extract data directly from.
Thank you in advance.
P.S.: I've also tried the suggestion by CG_DEV on How to use type: "POST" in jsonp ajax call, which says that $.post can be done with jsonp, which is the data type to use for cross-domain AJAX. Result: On Firebug I do see the POST request being made. But my function callback is not fired, and firebug doesn't register a Response body when at least "Success" should be returned.
you can set allow cross origin resource sharing
Follow two steps:
From server set this on response header
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:*
//* if you want to allow it for all origin domain , or you can specify origin domains also to which you want to allow cors.
In client side add this on your page
$.support.cors = true;
Cons: It is not fully supported on ie < ie10.

Implementing a counter on function returning files from gdrive

I want to implement a counter which keeps track of the number of times a file is downloaded. The function retrieves files from the google drive and it is printed on to the screen using for loop. Please help with a logic where to implement the counter to keep track of the count.
The function is as follows:
function makeRequest() {
var request = gapi.client.drive.files.list();
request.execute(function(resp) {
for (i=0; i<resp.items.length; i++) {
var titulo = resp.items[i].title;
var fechaUpd = resp.items[i].modifiedDate;
var userUpd = resp.items[i].lastModifyingUserName;
var userEmbed = resp.items[i].embedLink;
var userAltLink = resp.items[i].alternateLink;
var download = resp.items[i].webContentLink;
var hold="Download";
var flag=0;
<!-- var fileInfo = document.createElement('li');
<!-- fileInfo.appendChild(document.createTextNode('TITLE: ' + titulo + ' - LAST MODIF: ' + fechaUpd + ' - BY: ' + userUpd +' url: ' + hold.link(download)));
<!-- document.getElementById('content').appendChild(fileInfo);
document.write(titulo + " ");
document.write(hold.link(download) + "<br>");
<!--flag=1;
}
<!--if(flag!=1){
<!--document.write("not found!");
<!--}
}); ;
}
I am not sure I understand what you want to keep track off.
If you want to a single user to be able to see how many times that user has downloaded a file, it could be implemented in javascript and store the information in a cookie.
If you on the other hand want to see how many times a file has been downloaded by any user, it has to be implemented on the server side using PHP or whatever language you have available.
The key question here is if you can/want to implement the functions on the server or the client side. To do it on the client side you use javascript, to do it on the server side you can use PHP.

Dynamic URL too long (2568 characters), trying to make it shorter

i'm working with a javascript on a drupal website, but the saving function seems to work only as soon as i click 2 times on the "save" button. the code that fires the function is:
var param ="&usuario="+usuario+"&nivel="+nivel+gano+porc_gano+gasto+porc_gasto+tengo+porc_tengo+debo+ porc_debo+plazo_debo;
var s = document.createElement("script");
s.type = "text/javascript"; s.async = true;
s.src = server_direction +"setMisDatos?callback=respuestaGuardarMisDatos&param="+encodeURIComponent(param);
var h = document.getElementsByTagName("script")[0];
h.parentNode.insertBefore(s, h); //or h.appendChild(s);
the chrome console tells me the error is in the last line i copied, but i don't undertand what kind of error it is.
using chrome console (specifically the "network" one), i see that it's written in red, status/text "failed", type "undefined" size/content "13 B / 0 B"; when it works it's: status/text "200/OK", type "text/json", size/content "256 B/ 38B". i'm not an expert with this, is there some more information that could be useful?
the code fires a netbeans function, that stores data to a postgresql database, so i have like 100 variables that has to be stored when i click on the "save button".
The variables are written like this (in the js file):
var plazo_debo_casa1 = (getValor("plazo_debo_casa1"));
var plazo_debo_casa2 = (getValor("plazo_debo_casa2"));
var plazo_debo_casa3 = (getValor("plazo_debo_casa3"));
var plazo_debo_prestamo1 = (getValor("plazo_debo_prestamo1"));
var plazo_debo_prestamo2 = (getValor("plazo_debo_prestamo2"));
var plazo_debo_prestamo3 = (getValor("plazo_debo_prestamo3"));
var plazo_debo ="&plazo_debo_casa1="+plazo_debo_casa1+"&plazo_debo_casa2="+plazo_debo_casa2+"&plazo_debo_casa3="+plazo_debo_casa3+"&plazo_debo_prestamo1="+plazo_debo_prestamo1+"&plazo_debo_prestamo2="+plazo_debo_prestamo2+"&plazo_debo_prestamo3="+plazo_debo_prestamo3;
and then together in the "param" variable. Is it clearer now?
I installed httpfox in firefox, then i checked what happens, and finally i think i got the error: it says NS_ERROR_NET_RESET. Is it the actual error? what can i do to solve it?
I have been searching around the internet and probably my problem is that the URL is too long,
http://www.mirodinero.com:8080/mirodinero-war/setMisDatos?callback=respuestaGuardarMisDatos&param=%26usuario%3DIsa%20Mirodinero%26nivel%3D109%26gano_sal_neto%3D211113.45%26gano_sal_prof%3D2480%26gano_monet%3D0%26gano_renta_fija%3D0%26gano_renta_vble%3D0%26gano_inmuebles%3D2226.75%26gano_otros%3D2223.73%26gano_otros_ing%3D2411.12%26porc_gano_monet%3D0%26porc_gano_rentaf%3D0%26porc_gano_rentav%3D0%26porc_gano_inm%3D2%26porc_gano_otros%3D2%26porc_gano_otros_ing%3D1%26gasto_casa1%3D1306.46%26gasto_casa2%3D2402.38%26gasto_casa3%3D3999.57%26gasto_prestamo1%3D93475.58%26gasto_prestamo2%3D7325.88%26gasto_prestamo3%3D34090.9%26gasto_tarjetas%3D29443.2%26gasto_ibi%3D5670%26gasto_imp_otros%3D6780%26gasto_seg_inm%3D1320%26gasto_seg_pens%3D3451.22%26gasto_seg_vida%3D2330%26gasto_seg_plan%3D34230%26gasto_seg_medico%3D21220%26gasto_seg_coche%3D220%26gasto_luz%3D620%26gasto_agua%3D4550%26gasto_gas%3D320%26gasto_telef_f%3D22320%26gasto_telef_m%3D2350%26gasto_internet%3D20%26gasto_tv%3D3450%26gasto_hogar%3D20%26gasto_comida%3D20%26gasto_cenas_copas%3D20%26gasto_viajes%3D20%26gasto_vacaciones%3D220%26gasto_mobiliario%3D220%26gasto_ropa%3D2320%26gasto_transp%3D230%26gasto_otros%3D3620%26gasto_colegios%3D240%26gasto_univ%3D340%26gasto_master%3D2230%26gasto_otros_gastos%3D7323433%26porc_gasto_tarjetas%3D0%26porc_gasto_ibi%3D0%26porc_gasto_trib%3D0%26porc_gasto_seg_inm%3D0%26porc_gasto_seg_pens%3D0%26porc_gasto_seg_vida%3D2%26porc_gasto_seg_plan%3D2%26porc_gasto_seg_med%3D0%26porc_gasto_seg_coche%3D0%26porc_gasto_sum_luz%3D2%26porc_gasto_sum_agua%3D2%26porc_gasto_sum_gas%3D0%26porc_gasto_sum_teleff%3D0%26porc_gasto_sum_telefm%3D0%26porc_gasto_sum_int%3D0%26porc_gasto_sum_tv%3D0%26porc_gasto_nivel_hogar%3D0%26porc_gasto_nivel_comida%3D0%26porc_gasto_nivel_cenas%3D0%26porc_gasto_nivel_viajes%3D0%26porc_gasto_nivel_vacac%3D0%26porc_gasto_nivel_mob%3D0%26porc_gasto_nivel_ropa%3D20%26porc_gasto_nivel_transp%3D30%26porc_gasto_nivel_otros%3D30%26porc_gasto_colegios%3D2%26porc_gasto_univ%3D0%26porc_gasto_master%3D0%26porc_gasto_otros_gastos%3D23%26tengo_casa1%3D1231.11%26tengo_casa2%3D10000%26tengo_casa3%3D22240%26tengo_otras%3D23560%26tengo_monetario%3D1212.34%26tengo_planpensiones%3D23230%26tengo_otros%3D23330%26porc_tengo_casa1%3D1%26porc_tengo_casa2%3D0%26porc_tengo_casa3%3D2%26porc_tengo_otras%3D0%26porc_tengo_monet%3D0%26porc_tengo_plan%3D0%26porc_tengo_otros%3D0%26debo_casa1%3D4340%26debo_casa2%3D23450%26debo_casa3%3D23430%26debo_prestamo1%3D23330%26debo_prestamo2%3D6871.11%26debo_prestamo3%3D11340%26debo_tarjetas%3D61340%26porc_debo_casa1%3D30%26porc_debo_casa2%3D10%26porc_debo_casa3%3D12%26porc_debo_prestamo1%3D1%26porc_debo_prestamo2%3D12%26porc_debo_prestamo3%3D1%26porc_debo_tarjetas%3D4%26plazo_debo_casa1%3D230%26plazo_debo_casa2%3D450%26plazo_debo_casa3%3D122%26plazo_debo_prestamo1%3D3%26plazo_debo_prestamo2%3D12%26plazo_debo_prestamo3%3D4
I counted it, it's 2568 characters. So I tried to split it in two parts, since there is "what i earn", "my debts", etc. Problem is, that if my function only saves some columns, then it simply deletes the remaining one in postgres. How can this problem be solved?
since my webpage has different parts where to put the data, i thought that a good idea would be to create smaller function for parts of variable, for example putting 30 variables and the do the callback. I did like this:
function guardaLoQueGano(){
var nivel = parseInt(document.getElementById('progreso_nivel_total').style.marginLeft);
/*idUsusario*/
var usuario = miGetElementsByClassName('title', document.getElementById('block-user-1'))[0].innerHTML;
/*gano*/
var gano_sal_neto = getValor("gano_sal_neto");
var gano_sal_prof = getValor("gano_sal_prof");
var gano_monet = getValor("gano_monet");
var gano_renta_fija = (getValor("gano_renta_fija"));
var gano_renta_vble = (getValor("gano_renta_vble"));
var gano_inmuebles = (getValor("gano_inmuebles"));
var gano_otros = (getValor("gano_otros"));
var gano_otros_ing = (getValor("gano_otros_ing"));
/*gano porcentajes*/
var porc_gano_monet = getValor("porc_gano_monet");
var porc_gano_rentaf = getValor("porc_gano_rentaf");
var porc_gano_rentav = getValor("porc_gano_rentav");
var porc_gano_inm = getValor("porc_gano_inm");
var porc_gano_otros = getValor("porc_gano_otros");
var porc_gano_otros_ing = getValor("porc_gano_otros_ing");
var param = "&usuario=" + usuario + "&nivel=" + nivel + "&gano_sal_neto=" + gano_sal_neto + "&gano_sal_prof=" + gano_sal_prof + "&gano_monet=" + gano_monet + "&gano_renta_fija=" + gano_renta_fija + "&gano_renta_vble=" + gano_renta_vble + "&gano_inmuebles=" + gano_inmuebles + "&gano_otros=" + gano_otros + "&gano_otros_ing=" + gano_otros_ing + "&porc_gano_monet=" + porc_gano_monet + "&porc_gano_rentaf=" + porc_gano_rentaf + "&porc_gano_rentav=" + porc_gano_rentav + "&porc_gano_inm=" + porc_gano_inm + "&porc_gano_otros=" + porc_gano_otros + "&porc_gano_otros_ing=" + porc_gano_otros_ing;
var s = document.createElement("script");
s.type = "text/javascript"; s.async = true;
s.src = direccion_servidor + "setMisDatos?callback=respuestaGuardarMisDatos&param=" + encodeURIComponent(param);
var h = document.getElementsByTagName("script")[0];
// adesso h.appendChild(s);
h.parentNode.insertBefore(s, h);
alert("Datos de lo que gano actualizados correctamente");
}
This kind of function works perfectly, but has a big problem: it changes the values of the columns of this function, but deletes the remaining ones. How can I create different smaller function, in a way to save only on some columns without changing the others? Shall I write the netbeans function setMisDatos to make it more clear?
New finding:
I've been searching in the internet, and maybe found that my problem is that i might change the GET method to a POST protocol, so that it could take any kind of length.
On my page there is a php code to call the javascript function that is:
<div id="lo_que_gano" class="mis_datos" style="display:none">
<div class="generic todo_izq">
<div class="ancho_lado_izq generic">
<div class="texto_form generic">Salario neto</div>
<div class="generic">
<input class="numero" id="gano_sal_neto" type="text" value="0" onchange="calculoGano()" onkeypress="tecla('gano_sal_prof', event);"/></br>
</div>
</div>
//all the values that has to be stored
</div>
<div class="generic botonGuardar">
<input type="button" value="Guardar" onclick="return guardaTodo()"/>
</div>
</div>
how can i convert the GET method to POST? Shall it be implemented in the javascript or in the php code? I'm sorry i'm really not an expert on this.
I tried to change &usuario= with &u=, and it works, but then when i try to change "gano_sal_neto" (i changed &gano_sal_neto= with &gsn=), it will delete the corresponding value in the postgres table (a NULL value). Where is the error now? I'm sorry but i'm really not an expert on this.
And I have an observation: why do i get error after 30 seconds, but not in that in interval?
the change i did, based on the answer i got, from "gano_sal_neto" to "gsn" in:
the javascript file that is loaded by the source code of the page;
the php code of the drupal page;
the netbeans files;
i created a new column named "gsn" in the same table as where the data are stored.
what am i missing to make the new URL work?
Better explanation of what is happening now:
i have 2 types of error:
in the netbeans log file, it tells me:
Code:
error:
java.lang.NullPointerException
at com.mirodinero.web.calculos.Calculos.getTotalGano(Calculos.java:182)
at com.mirodinero.web.calculos.CalcularSegmentos.ejecutar(CalcularSegmentos.java:65)
at com.mirodinero.web.servlets.setMisDatos.actualizarSegmentos(setMisDatos.java:543)
where getTotalGano at those lines is:
public float getTotalGano() {
float res = user.getGanoMonet() + user.getGanoRentaFija() + user.getGanoRentaVble() + user.getGanoInmuebles() + user.getGanoOtros() + user.getGanoSalNeto() + user.getGanoSalProf() + user.getGanoOtrosIng();
return res;
}
and ejecutar() is:
public void ejecutar() {
boolean existe = true;
DatosUsuario datosUser = datosUsuarioFacade.findById(atributosUsuario.getIdUsuario());
if (datosUser != null) {
List<Cartera> lc = carteraFacade.findByIdUsuario(atributosUsuario.getIdUsuario());
Calculos c = new Calculos(datosUser, accionesDatosFacade, fondosDatosFacade, bonosDatosFacade, lc);
ahorroLiquido = c.getTengoDisponible() / c.getTotalGasto();
ingresoAnual = c.getTotalGano(); /*this is line 65 */
diferenciaGanoGasto = c.getSupDefTotal();//indica lo que gano menos lo que gasto
modificarAtributos(c, datosUser);
}
on the postgres log file, i get:
2012-05-22 11:10:46 CESTLOG: could not receive data from client: Unknown winsock error 10061
2012-05-22 11:10:46 CESTLOG: unexpected EOF on client connection
2012-05-22 11:19:12 CESTLOG: CreateProcess call failed: Unknown winsock error 10004 (error code 1115)
2012-05-22 11:19:12 CESTLOG: could not fork autovacuum worker process: Unknown winsock error 10004
but i don't know what does it mean. Maybe is there something i should do with pgadmin to "upgrade" the database to the changes:i added a column named gsn -real and default 0 like gano_sal_neto-, without deleting the gano_sal_neto (that still has stored the data of the users).
still nobody able to help me with this? i don't what's the problem with changing columns name in postgres, maybe a procedure i'm missing?
The answer was to change the settings in glassfish HTTP service listenings: I changed the timeouts to a bigger interval, and now it works!
Because what you are doing is constructing a <script src=...> element, with the src attribute dynamically generated, it's not possible to use POST. All HTTP requests use GET. What you may be able to do instead is encode your querystring to make it shorter. The server-side processing can decode it to send the right script file.
For example, you don't need &usario= when you could call that &u= because your server-side process shouldn't need it to be called usario. You've saved five bytes just by doing that.
You could encode the values to make them shorter, and decode them server-side. I've no idea what the data actually is; this may not be practical.

How would I duplicate form elements AND the data inside them with jQuery?

See this form - http://schnell.dreamhosters.com/form.php
This form has a portion of it where you enter data and can choose to add more of the same data by clicking a button called 'Add A Site' and it will make another of that section to enter another site. This is the jQuery that performs the duplication...
$(function () {
var sites = 1;
var siteform = $("#site1").html();
$(".addsites").live("click", function(e) {
e.preventDefault();
sites++;
$("#events").append("<div id='site" + sites + "'>"
+ "<br /><hr><br />"
+ siteform
+ "<center><button class='removesites' title='site"
+ sites + "'>Remove This Site</button><br />"
+ "<button class='addsites'>Add Another Site</button>"
+ "</center></div>");
});
$(".removesites").live("click", function(e) {
e.preventDefault();
var id = $(this).attr("title");
$("#" + id).remove();
});
});
The duplication works perfectly, but one thing that's bugging me is that when I have to enter data for someone claiming a LOT of sites, it gets very annoying having to repeat same or similar parts of this section of the form (like every site is in the same city, on the same day, by the same person, etc.) So I had the idea that with each duplication, the values of the form elements would also carry over and I just edit what's not the same. The current implementation only duplicates the elements, not the data. I'm not sure how to easily copy the data into new sections, and I can't find any jQuery tools to do that.
PS - This part isn't as important, but I've also considered using this same form to load the data back in for viewing/editing, etc. The only problem with this is that the reprinting of the form means that there will be a form section with the id "Site7" or something, but jQuery starts its numbering at 1, always. I've thought about using selectors to find the highest number site and start off the variable 'sites' at that number, but I'm not sure how. Any advice how to do this, or a better system overall, would be much appreciated.
You want to itterate over the input fields in siteform and store them in an object using their name attribute as a key.
Then after the duplication of the object you made and look for the equivelant fields in the new duplicated form ans set their values.
Somthing like this (not tested, just the idea)
var obj = new Object();
$("#site1 input").each(function(){
obj[this.id] = this.value;
);
// Dupicate form
$.each(obj, function(key, value){
$('#newform input[name="'+key+'"]').value = value;
});
Mind you these two each() functions differ from each other.
http://api.jquery.com/jQuery.each/
http://api.jquery.com/each/
You could consider using cloneNode to truely clone the previous site-div and (by passing true to cloneNode) all of its descendants and their attributes. Just know that the clone will have the same id as the original, so you'll have to manually set its id afterwards
Try this in your click-function
var clone = $("#site" + sites).clone(true, true); // clone the last div
sites++; // increment the number of divs
clone.attr('id', "site" + sites); // give the clone a unique id
$("#events").append(clone); // append it to the container
As Scuzzy points out in a comment jQuery does have its own clone() method (I don't use jQuery much, so I didn't know, and I didn't bother to check before answering). Probably better to use jQuery's method than the built-in cloneNode DOM method, since you're already using jQuery for event listeners. I've updated the code
The query to transfer values is quite simple (please, check the selector for all the right types on the form):
$("#site1").find("input[checked], input:text, input:hidden, input:password, input:submit, option:selected, textarea")
//.filter(":disabled")
.each(function()
{
$('#site2 [name="'+this.name+'"]').val(this.value);
}
Ok I finally figured this out. It's, more or less, an expansion on Alex Pakka's answer.
sites++;
$("#events").append("<div id='site" + sites + "'>"
+ "<hr><br />"
+ siteform
+ "<center><button class='removesites' title='site"
+ sites + "'>Remove This Site</button><br />");
$("#site1").find("input:checked, input:text, textarea, select").each(function() {
var name = $(this).attr("name");
var val = $(this).val();
var checked = $(this).attr("checked");
var selected = $(this).attr("selectedIndex");
$('#site' + sites + ' [name="'+name+'"]').val(val);
$('#site' + sites + ' [name="'+name+'"]').attr("checked", checked);
$('#site' + sites + ' [name="'+name+'"]').attr("selectedIndex", selected);
});
I used extra vars for readability sake, but it should do just as fine if you didn't and used the methods directly.
Dont forget to create a function for registering the event! Its very important because when the DOM is loaded, all new attributes need to be registrated to the DOM.
Small example:
<script>
$(document).ready(function(){
$('#click-me').click(function(){
registerClickEvent();
})
function registerClickEvent(){
$('<input type="text" name="input_field_example[]">').appendTo('#the-div-you-want')
}
registerClickEvent();
})
</script>

Categories