im having some trouble while processing some information, the thing is i have an npm module that is called pdf-parser it basically reads a pdf and extracts the information inside. What is need next is to send the information to an API that punctuates how well written is the text.
Thing is when i log the information on display it looks like this:
Entornos personales de aprendizaje
PLE (personal learning environmnent o entorno personal del aprendizaje) es un concepto de
mucho interés y causa de debate en los círculos de la tecnología educativa.
Un PLE puede definirse como el conjunto de herramientas tecnológicas elegidas como
integradas y utilizadas por un individuo para acceder a las nuevas fuentes de conocimiento.
Un PLE se conforma por tres procesos básicos según Atwell estos son: leer, reflexionar y
compartir.
1.La fuentes a las que accedo me ofrecen información.
2.Entornos o servicios en los que puedo transformar la información.
3.Entornos donde me relaciono con las personas de las que aprendo.
Donde acceder a la información: Sitios web, videos, archivos multimedia, noticas, etc.
Donde modificar la información: Herramientas de dedición, mapas conceptuales,
cronogramas, creación de presentaciones, etc.
Donde puedo relacionarme con otros: Redes sociales.
But the information inside the object that i made looks like this:
'\n' +
'\n' +
'Entornos personales de aprendizaje\n' +
'PLE (personal learning environmnent o entorno personal del aprendizaje) es un concepto de \n' +
'mucho interés y causa de debate en los círculos de la tecnología educativa.\n' +
'Un PLE puede definirse como el conjunto de herramientas tecnológicas elegidas como \n' +
'integradas y utilizadas por un individuo para acceder a las nuevas fuentes de conocimiento.\n' +
'Un PLE se conforma por tres procesos básicos según Atwell estos son: leer, reflexionar y \n' +
'compartir.\n' +
'1.La fuentes a las que accedo me ofrecen información.\n' +
'2.Entornos o servicios en los que puedo transformar la información.\n' +
'3.Entornos donde me relaciono con las personas de las que aprendo.\n' +
'Donde acceder a la información: Sitios web, videos, archivos multimedia, noticas, etc.\n' +
'Donde modificar la información: Herramientas de dedición, mapas conceptuales, \n' +
'cronogramas, creación de presentaciones, etc.\n' +
'Donde puedo relacionarme con otros: Redes sociales.'
Is there a js function that parses the information into a simple string, because the API won't give the same results while the text is written "codelike"
Thanks in advance and sorry form y rough english
Related
Closed. This question is not written in English. It is not currently accepting answers.
Stack Overflow is an English-only site. The author must be able to communicate in English to understand and engage with any comments and/or answers their question receives. Don't translate this post for the author; machine translations can be inaccurate, and even human translations can alter the intended meaning of the post.
Closed 6 days ago.
Improve this question
fiz uma barra de progresso em um projeto, seguindo essa lógica:
`const carregarBarra = () => {
const totalPercent = 100;
const totalProperties = Object.keys(data).length;
let porcentagem = (totalPercent * validatedInputs) / totalProperties;
if(data.produto){
validatedInputs += 1
}
if(data.quantidade){
validatedInputs += 1
}
if(data.preco){
validatedInputs += 1
}
if(data.tipoDoProduto){
validatedInputs += 1
}
console.log("porcentagem:",porcentagem)
console.log("inputs preenchidos: ",validatedInputs)
return porcentagem
}`
Então, eu coloco o valor de carregarBarra() em um width para mostrar o progresso conforme o usuário preenche os inputs, assim que todos os 4 são preenchidos o input de submit deveria ser ativado imagem do Modal.
O problema é o seguinte: o valor de "porcentagem" deve ser 100 de acordo com essa lógica, para assim desativar o disabled do input "submit", porém na DOM a barra carrega os 100% mas no console o valor de "porcentagem" é 200, mesmo não havendo nada multiplicando ela fora dessa função.
<input type="submit" value='Salvar' disabled={carregarBarra() !== 100} />
console após o preenchimento de todos os inputs
compreender oq esta havendo que o valor de porcentagem esta duplicando no console
I want to write a csv file for my outputs after scraping with puppeteer i've tried different methods but i can't get a result here's the part of the code of data that i want to export to a csv file.
async function main(){
const allinks = await getLinks();
//console.log(allinks);
const browser = await puppeteer.launch({headless:false});
const page = await browser.newPage();
await page.setDefaultNavigationTimeout(0);
for (let link of allinks){
const data = await getInfoscrape(link,page);
}
} main();
and my data structure is :
Poste
Contrat
Salaire
Diplome
Experience
Travail
Description
for the result i have this as a json , so i want to write in csv file
'''
{
Poste: 'Lead Développeur',
Contrat: 'CDI ',
Salaire: 'Salaire entre 65K € et 75K €',
Diplome: 'Bac +5 / Master',
Experience: '> 3 ans',
Travail: 'Télétravail partiel possible',
Description: 'En tant que Lead Développeur(se), tu seras chargé(e) de mentorer des développeurs de Galadrim dans l’objectif de les faire progresser. Les tâches typiques du poste sont les suivantes :faire des code reviews sur différents projets\n' +
'participer au choix des technologies et de l’architecture sur les nouveaux projets\n' +
'faire des sessions de pair-programming avec les développeurs\n' +
'aider à la résolution des problèmes les plus complexes\n' +
'faire de la veille technique\n' +
'Une application mobile de rencontres\n' +
'Un moteur de réservation en ligne pour des parcours de golf\n' +
'Un site web de commande de box par abonnement pour un grand groupe de cosmétiques\n' +
'Un logiciel de caisse'
},
'''
I use Node's built-in "fs" module to write .csv.
Something like this:
const fs = require("fs")
let data = fs.readFileSync("./data.json") // an array of objects
data = JSON.parse(data);
let csv = "locationPoint\taddress\tschedule\tfarmName\n";
data.forEach( ferme => {
csv += ferme.locationPoint + `\t`;
csv += ferme.fullAddress + `\t`;
csv += ferme.schedule + `\t`;
csv += ferme.farmName + "\n";
})
console.log('#success', csv);
fs.writeFileSync("fermes.csv", csv)
Note that in my example, I'm using tabs instead of commas; my data is prone to contain commas.
For your case, you'd replace :
let csv = "locationPoint\taddress\tschedule\tfarmName\n";
with:
let csv = "Poste\tContrat\tSalaire\tDiplome\tExperience\tTravail\tDescription\n";
And, similarly for the rest of the values in the forEach loop.
I'm a JavaScript beginner and also ReactJS.
I am doing an exercise just to improve my knowledge. This exercise is a list of investment funds. I render this list and display some details about each investment fund.
What I'm trying to do now is to organize this list according to its respective category and subcategory. Showing a piece in the list in the image below, you can see that I render a list, and that each item in that list has a category and a subcategory.
I tried using reduce, but I really didn't understand how it works and I couldn't apply the examples I saw on the internet. To organize the list as it is now, I used the .map().
Here's my code I put into codesandbox
Here's the Gist I'm using to get the list
Can you tell me how to organize/list each investment fund according to its category and subcategory?
Thank you in advance.
We can use Array.reduce to group the funds by Category or by Category and Subcategory, this will create objects keyed on these properties.
Once we have funds grouped by category, we could display only those in a given group, e.g.
groups["Renda Variável"]
We can also use Array.sort to sort by any property (or combination of properties).
Also, if you only want funds for a given category you can use Array.filter, like so:
// Show only funds from "Estratégias Diferenciadas"
console.log("Desired category:", funds.filter(fund => fund.Category === "Estratégias Diferenciadas"));
For example (I've selected 20 random items from all the funds here):
let funds = [{"Category":"Renda Variável","SubCategory":"Valor Long Only","Name":"Normandia Institucional Fundo de Investimento em Cotas de Fundo de Investimento em Ações","Type":"Ações"},{"Category":"Renda Fixa","SubCategory":"Crédito Privado","Name":"Fundo de Investimento Vinci Renda Fixa Crédito Privado","Type":"Renda Fixa"},{"Category":"Renda Variável","SubCategory":"Valor Plus","Name":"Novus Ações Institucional Fundo de Investimento em Cotas de Fundos de Investimento em Ações","Type":"Ações"},{"Category":"Renda Fixa","SubCategory":"Cotas de FIDCs Próprios","Name":"SRM Exodus 60 Fundo de Investimento em Cotas de Fundos de Investimento Multimercado - Créd. Priv.","Type":"Multimercado"},{"Category":"Estratégias Diferenciadas","SubCategory":"Estratégia Específica - Investimento no Exterior","Name":"Exploritas Alpha America Latina Fic de Fi Multimercado","Type":"Multimercado"},{"Category":"Estratégias Diferenciadas","SubCategory":"Long & Short Direcional","Name":"3R Genus Hedge Fundo de Investimento Multimercado","Type":"Multimercado"},{"Category":"Renda Variável","SubCategory":"Equity Hedge/Long Biased","Name":"NCH Maracanã Long Short Select Fundo de Investimento de Ações","Type":"Ações"},{"Category":"Renda Variável","SubCategory":"Valor Plus","Name":"Perfin Institucional Fundo de Investimento em Cotas de Fundos de Investimento em Ações","Type":"Ações"},{"Category":"Renda Fixa","SubCategory":"Renda Fixa","Name":"Brasil Plural Yield Fundo de Investimento Renda Fixa Referenciado DI","Type":"Renda Fixa"},{"Category":"Renda Fixa","SubCategory":"Crédito Privado","Name":"Augme 45 Fundo de Investimento em Cotas de Fundos de Investimento multimercado Crédito Privado","Type":"Renda Fixa"},{"Category":"Renda Fixa","SubCategory":"Crédito Privado","Name":"Daycoval Classic Fundo de Investimento Renda Fixa Crédito Privado","Type":"Renda Fixa"},{"Category":"Renda Fixa","SubCategory":"Crédito Privado","Name":"BNP Paribas Match DI Fundo de Investimento Renda Fundo de Investimentoxa Referenciado Crédito Privado","Type":"Renda Fixa"},{"Category":"Renda Fixa","SubCategory":"Direitos Creditórios","Name":"Fundo de Investimento em Direitos Créditorios TG Real","Type":"Direito Creditório"},{"Category":"Renda Fixa","SubCategory":"Crédito Privado","Name":"Leste Credit Brasil Fundo de Investimento em Cotas de Fundos de Investimento Multimercado Crédito Privado","Type":"Multimercado"},{"Category":"Renda Variável","SubCategory":"Valor Plus","Name":"Rio Bravo Fundamental Fundo de Investimento em Ações","Type":"Ações"},{"Category":"Estratégias Diferenciadas","SubCategory":"Estratégia Específica - Investimento no Exterior","Name":"NW3 Event Driven Fundo de Investimento em Cotas de Fundos de Investimento Multimercado","Type":"Multimercado"},{"Category":"Renda Fixa","SubCategory":"Cotas de FIDCs Multigestor","Name":"Solis Capital Antares Crédito Privado - Fundo de Investimento em Cotas de Fundos de Investimento Multimercado - Longo Prazo","Type":"Multimercado"},{"Category":"Estratégias Diferenciadas","SubCategory":"Macro Valorização","Name":"Adam Macro Strategy II Fundo de Investimento em Cotas de Fundos de Investimento Multimercado","Type":"Multimercado"},{"Category":"Renda Fixa","SubCategory":"Cotas de FIDCs Próprios","Name":"Valora Guardian Fundo de Investimento em Cotas de Fundos de Investimento Multimercado Crédito Privado","Type":"Multimercado"},{"Category":"Estratégias Diferenciadas","SubCategory":"Long & Short Neutro","Name":"Távola Long & Short Fundo de Investimento Multimercado","Type":"Multimercado"}]
console.log("Funds grouped by Category:", funds.reduce((groups, fund) => {
// We use this key to group funds, we could make it anything, e.g. Name etc.
let key = fund.Category;
groups[key] = [...(groups[key] || []), fund];
return groups;
}, {}));
console.log("Funds grouped by Category, Subcategory:", funds.reduce((groups, fund) => {
// We use this key to group funds, in this case we're grouping by Category and SubCategory
let key = fund.Category + ", " + fund.SubCategory;
groups[key] = [...(groups[key] || []), fund];
return groups;
}, {}));
console.log("Funds sorted by Category:", [...funds].sort((a, b) => a.Category > b.Category ? 1: -1));
console.log("Funds sorted by Category, SubCategory:", [...funds].sort((a, b) => {
if (a.Category !== b.Category) {
return a.Category > b.Category ? 1: -1;
}
return a.SubCategory > b.SubCategory ? 1: -1;
}));
Here is my problem : I have a bunch of <p>HTML.
For example :
<p> Paris </p> <p>London</p> <p> NewYork</p>
When I want to get the Text of a specific <p> when I click on it, I do (using JQuery)
$("#saved_research").click(function(){
console.log($(this).text());
});
it returns me ParisLondonNewYork.
And not the specific text of the <p>.
Do you know why ?
Respectfully,
Here is the exact HTML
<!DOCTYPE html>
<html lang="fr">
<head>
<title>My News</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="shortcut icon" type="image/x-icon" href="favicon-js.ico">
<link rel="stylesheet" type="text/css" media="screen" href="news.css">
</head>
<body onload="init();">
<header>
<img id="banniere" src="img/job.png"/>
</header>
<!--HERE -->
<div id="recherches">
<h3 class="titre"> recherches stockées</h3>
<div id="recherches-stockees">
</div>
<h3 class="titre">nouvelle recherche</h3>
<div id="nouvelle-recherche">
<input type="text" name="zone_saisie" id="zone_saisie"/>
<img id="disk" class="icone-disk" src="img/disk30.jpg" onclick="ajouter_recherche()" />
<BR/>
<input id="bouton_recherche"type="button" value="OK" onclick="rechercher_nouvelles()"/>
</div>
</div>
<div id="zone-centrale">
<div id="resultats-container">
<h3 class="titre">résultat</h3>
<div id="wait"></div>
<div id="resultats"></div>
</div>
</div>
<!-- Inclusion des librairies jQuery & Scripts JS -->
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<script
src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
crossorigin="anonymous"></script>
<script src="scripts/jquery.cookie.js"></script>
<script src="scripts/util.js"></script>
<script src="scripts/news.js"></script>
</body>
</html>
Here is the exact JS
// Tableau contenant des chaines de caractères correspondant aux recherches stockées
var recherches = [];
// Chaine de caractères correspondant à la recherche courante
var recherche_courante;
// Tableau d'objets de type resultats (avec titre, date et url)
var recherche_courante_news = [];
/*class Paragraphe{
constructor(id,value){
this.id = id;
this.value = value;
}
}*/
/*1.1 */
//si clic sur l'image disk alors ajout chaine au tableau recherches[]
//function ajouter_recherche()
function ajouter_recherche(){
//recuperer la chaine de carachtere
//verifier si dans recherches, il y a la meme recherche
const donneeEntree = $("#zone_saisie").val();
if(recherches.indexOf(donneeEntree) == -1){
recherches.push(donneeEntree);
//ajouter l'element aux recherches stockées
$("#recherches-stockees").prepend('<p class="titre-recherche" ><label onclick=selectionner_recherche(this)>'+donneeEntree+'</label><img src="images/croix30.jpg" class="icone-croix " onclick="supprimer_recherche(this)"/></p>');
//sauvegarde dans sessionStorage(plus de place que cookie) pour conserver les recherches deja effectuées
localStorage.setItem("recherches",JSON.stringify(recherches));
}
//si clic sur le label => selectionner_recherche(this)
//si clic sur croix => supprimer_recherche(this)
}
function supprimer_recherche(elt) {
//supprimer l'element p dans recherches-stockees
$(elt).parent().remove();
// localStorage.clear(); == localStorage.removeItem("recherches");
//supprimer la recherche du tableau recherches[]
const indexSupprimer = recherches.indexOf($(elt).parent().parent().val());
recherches.splice(indexSupprimer);
//supprimer dans localstorage aussi
//localStorage.removeItem(this);
//c'est moche A REFAIRE
localStorage.setItem("recherches",JSON.stringify(recherches));
}
//controller
function selectionner_recherche(elt) {
$("#zone_saisie").val("");
$("#resultats").empty();
//jquery ??????
$("#zone_saisie").val(elt.innerText);
recherche_courante = elt.innerText;
//variable globale recherche_courante_news => cookie
//localstorage.getItem => recuperer le "cookie" === nom de la recherche
recherche_courante_news = JSON.parse(localStorage.getItem($("#zone_saisie").val()));
//affichage des recherche sauvegardées dans la zone resultats
$.each(recherche_courante_news,function(index,value){
$("#resultats").append('<p class="titre_result"><a class="titre_news" href='+decodeHtmlEntities(value.url)+
' target="_blank">'+decodeHtmlEntities(value.titre)+
'</a><span class="date_news">'+decodeHtmlEntities(value.date)+'</span><span class="action_news" onclick="sauver_nouvelle(this)"><img src="img/horloge15.jpg"/></span></p>');
});
}
//model
function init() {
//recuperer les données du stockage local
let obj_json = localStorage.getItem("recherches");
let obj = JSON.parse(obj_json);
if(obj != ""){
$(obj).each(function(index,value){
recherches.push(value);
$("#recherches-stockees").prepend('<p class="titre-recherche" ><label onclick=selectionner_recherche(this)>'+value +'</label><img src="images/croix30.jpg" class="icone-croix " onclick="supprimer_recherche(this)"/></p>');
});
}
//on remplit la partie recherches-stockées de ces données
}
//model
function rechercher_nouvelles() {
//faire une requeste get ? !!!pas secure!!! avec les données de recherche_courante ? ou direct avec value ?
//on nettoye la zone de resultat pour eviter d'afficher encore et encore
$("#resultats").empty();
$("#wait").css("display","block");
const data = $("#zone_saisie").val();
//.get est asynchrone
$.get("https://carl-vincent.fr/search-internships.php?data="+data,maj_resultats);
//vider recherche_couraznt_news sinon tout les cookies se superposeront ( 1: coucou ..... 2 : coucou, salut)
recherche_courante_news = []; //argh c moche
//et on la remplis avec le contenu du localstorage de la recherche en question
//on ne peut pas utiliser $("#zone_saisie").val() car si l'utilisateur change la recherche mais veut quand m
//même faire l'action alors ça marchera pas => exemple impossible d'acceder à l'element car non existant
//il faudrait récuperer le label sur la recherche_saved sur laquelle on clic
/* recherche_courante_news = JSON.parse(localStorage.getItem($("#recherches-stockees").click(function(){
return $(this).text();
})
));*/
/*$("#recherches-stockees > p").click(function(){
console.log($(this).text());
alert("yes");
})*/
//HERE/////////////////////////////////////////
$('#recherches-stockees > p').on('click', function() {
console.log($(this).text());
});
}
//function callback => si jamais la requete ajax get reussis alors on fait celle ci
//view
function maj_resultats(res) {
$("#wait").css("display","none");
//res est un objet de plusieurs offres, on veut toute les afficher dans la case resultat
$(res).each(function(index,value){
$("#resultats").append('<p class="titre_result"><a class="titre_news" href='+decodeHtmlEntities(value.url)+
' target="_blank">'+decodeHtmlEntities(value.titre)+
'</a><span class="date_news">'+decodeHtmlEntities(value.date)+'</span><span class="action_news" onclick="sauver_nouvelle(this)"><img src="img/horloge15.jpg"/></span></p>');
});
}
//manque : creer un objet à envoyer
//delete dans recherche_courante_news
function sauver_nouvelle(elt) {
//parentElement => titre
let obj = {
"titre" : $(elt).parent().find("a").text(),
"date" : $(elt).parent().find(".date_news").text(),
"url" : $(elt).parent().find("a").attr('href')
}
//$(elt).firstChild.attr("src","");
//$(elt).attr("src","img/disk15.jpg");
$(elt).html("<img src = img/disk15.jpg />");
$(elt).attr("onclick","supprimer_nouvelle(this)");
//creer l'objet il faut
if(indexOfResultat(recherche_courante_news,obj) == -1){
recherche_courante_news.push(obj);
localStorage.setItem("recherches_courante_news",JSON.stringify(recherche_courante_news));
//on a donc 1 cookie par recherche, faire des verif pour pas pouvoir mettre le même plusieurs fois ??
localStorage.setItem( $("#zone_saisie").val(),JSON.stringify(recherche_courante_news));
}
}
function supprimer_nouvelle(elt) {
let obj = {
"titre" : $(elt).parent().find("a").text(),
"date" : $(elt).parent().find(".date_news").text(),
"url" : $(elt).parent().find("a").attr('href')
}
//$(elt).attr("src","");
//$(elt).attr("src","img/horloge15.jpg");
$(elt).html("<img src = img/horloge15.jpg />");
$(elt).attr("onclick","sauver_nouvelle(this)");
if(indexOfResultat(recherche_courante_news,obj) != -1){
recherche_courante_news.splice(indexOfResultat(obj,recherche_courante_news));
localStorage.setItem("recherches_courante_news",JSON.stringify(recherche_courante_news));
localStorage.setItem($("#zone_saisie").val(),JSON.stringify(recherche_courante_news));
}
}
//Autocompletion
//A chaque Entrée de clavier => keyup, verifier si le mot n'a pas une ressemblance dans le localstorage (recherches sauvegardées)
//Apparement Jquery UI le fait tres bien
//Model et view
var test = ['Grenoble','Lyon','Paris'];
$("#zone_saisie").autocomplete({
source : recherches,
focus : true
}).keypress(function(event){
if(event.keyCode === 13){
rechercher_nouvelles();
}
});
Seems like the reason you are getting all the concatenated p text is because you are handling the click event on the parent div, and the this reference is to that div. Calling .text() on this parent reference gives all the child text. The click handler should be invoked with an event object that has the specific target, and you can use that to get the text only of what was clicked.
$("#saved_research").click(function(event){
var x = event.target; // event.target has the exact element clicked
console.log($(x).text()); // the text of the clicked element
});
Add the listener to the <p>s, not the parent container, and then referencing this inside the listener will refer to a <p>, so $(this).text() will give you the text of an individual <p>:
$('#saved_research > p').on('click', function() {
console.log('1p',$(this).children().eq(0).text());
console.log('2p',$(this).children().eq(1).text());
console.log('3p',$(this).children().eq(2).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="saved_research">
<p>Paris</p> <p>London</p> <p>NewYork</p>
</div>
Or use event delegation:
$('#saved_research').on('click', 'p', function() {
console.log($(this).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="saved_research">
<p>Paris</p> <p>London</p> <p>NewYork</p>
</div>
So, your javascript is saying "get all the <p> inside of #saved_research" You'll need to add a specific identifier to your html. There are many ways to do this, but one of the best ways to do this is with data attributes:
<div id="saved_research">
<p data-paragraph="1">Paris</p>
<p data-paragraph="2">London</p>
<p data-paragraph="3">New York</p>
</div>
$("#saved_research").click(function() {
console.log($("[data-paragraph='1']").text());
});
Use data attributes - rather than ids or classes - to denote things in your html that are related to javascript. This is considered by some (myself included) to be a best practice. It allows you to know what in your html is specifically for javascript. For example, when you're looking at your html in the future, will you remember that id #saved_research is used by javascript? If not, someone doing design work on the page may change #saved_research to #save_research thinking it is only involved with the CSS. Thus, they break the javascript. By using data attributes, it's very clear: this identifier is used for javascript.
Edit: based on your comment about the html not existing on the page when the page loads, here's what you need to do:
$(window.document).on('click', "#saved_research", function() {
console.log($("[data-paragraph='1']").text());
});
Notice the different format, with .on('click' ? This format is required when you have elements that are dynamically added to the page. The .click format only works if the element exists on the page when the page first loads. You can use this .on('click' format with any of the other answers listed on this page, they all work with this format.
I'm trying to streamline my code a little by setting up functions rather than repeating the same lines of code over again:
function pledgeSpanish() {
$(name).attr('placeholder', 'Tu nombre... *');
$(email).attr('placeholder', 'Tu correo electrónico... *');
$(nationality).text('Nacionalidad....');
$(radioPublic).text('Soy miembro del compromiso global de apoyo a las comunidades afectadas por las mineras.');
$(radioCommunity).text('Provengo o trabajo en una comunidad afectada por las mineras. Me gustaría contactar con otros miembros del movimiento “Si a la Vida, No a la Minera” y recibir las últimas actualizaciones.');
$(buttonSubmit).val('Firma La Petición');
}
But when I try to run the script, I get the error
email is not defined
Funnily enough, I don't get an error for the 'name' field
How would I go about modifying it so that I can access the variables from within the function?
Amended like so:
var name = $('#form-pledge .field-name input');
var email = $('#form-pledge .field-email input');
var nationality = $('#form-pledge .field-nationality select option:first');
var radioPublic = $('#form-pledge .gfield_radio li:first label');
var radioCommunity = $('#form-pledge .gfield_radio li:last label');
var buttonSubmit = $('#form-pledge input[type="submit"]');
function pledgeSpanish() {
$(name).attr('placeholder', 'Tu nombre... *');
$(email).attr('placeholder', 'Tu correo electrónico... *');
$(nationality).text('Nacionalidad....');
$(radioPublic).text('Soy miembro del compromiso global de apoyo a las comunidades afectadas por las mineras.');
$(radioCommunity).text('Provengo o trabajo en una comunidad afectada por las mineras. Me gustaría contactar con otros miembros del movimiento “Si a la Vida, No a la Minera” y recibir las últimas actualizaciones.');
$(buttonSubmit).val('Firma La Petición');
}
Is this the best way to go about it?