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?
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
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
sorry but I am French and my English is bad, I use "Google Trad" to help me, I am sorry if it is weird reading me.
I create a "Blind Test" type game, I ask for 3 titles from a singer, so I create an object in Javascript with the singer then the titles.
function Chanson(chanteur, titre1, titre2, titre3, titre4, titre5, titre6, titre7, titre8, titre9, titre10) {
this.chanteur = chanteur;
this.titre1 = titre1;
this.titre2 = titre2;
this.titre3 = titre3;
this.titre4 = titre4;
this.titre5 = titre5;
this.titre6 = titre6;
this.titre7 = titre7;
this.titre8 = titre8;
this.titre9 = titre9;
this.titre10 = titre10;
}
Then I create some singers and songs.
let Sardou = new Chanson("Michel Sardou", "Les lacs du Connemara", "Je vais t'aimer", "La maladie d'amour", "En chantant", "Être une femme", "La java de Broadway", "Le rire du Sergent", "La France", "Je vole", "Afrique adieu")
let Goldman = new Chanson("Jean-Jacques Goldman", "Il suffira d'un signe", "Comme toi", "Envole-moi", "Au bout de mes rêves", "Je marche seul", "Il changeait la vie", "La vie par procuration", "A nos actes manqués", "Encore un matin", "Né en 17 a Leydenstadt")
let Dassin = new Chanson("Joe Dassin", "Les Champs-Elysées", "Et si tu n'existais pas", "L'été Indien", "Dans les yeux d'Émilie", "A toi", "Siffler sur la colline", "Le petit pain au chocolat", "Ca va pas changer le monde", "Salut les amoureux", "La fleur aux dents", "<img src='img/joedassin.jpg'>")
let Hallyday = new Chanson("Johnny Hallyday", "L'envie", "Allumer le feu", "Quelque chose de Tenessee", "Le pénitencier", "Diego libre dans sa tête", "Requiem pour un fou", "Je te promet", "Que je t'aime", "Gabrielle", "Vivre pour le meilleur")
let Indochine = new Chanson("Indochine", "J'ai demandé à la lune", "L'aventurier", "Trois nuits par semaine", "3e Sexe", "Tes yeux Noir", "Un été Français", "Nos célébrations", "Juste toi et moi", "Miss Paramount", "Les Tzars")
let Aznavour = new Chanson("Charles Aznavour", "La Bohème", "Emmenez-moi", "Hier encore", "J'me voyais déjà", "Mes emmerdes", "For me Formidable", "Les Comédiens", "Non je n'ai rien oublié", "La mamma", "Mourir d'aimer")
I then make a table.
const MesChansons = [Sardou, Goldman, Dassin, Hallyday, Indochine, Aznavour]
Then I use a "Math Random" to have a singer randomly. And I place them in my DOM.
const ChansonHasard = MesChansons[Math.floor(Math.random() * MesChansons.length)];
document.getElementById("achanger").innerHTML = ChansonHasard.chanteur
document.querySelector("p.t1").innerHTML = ChansonHasard.titre1
document.querySelector("p.t2").innerHTML = ChansonHasard.titre2
document.querySelector("p.t3").innerHTML = ChansonHasard.titre3
document.querySelector("p.t4").innerHTML = ChansonHasard.titre4
document.querySelector("p.t5").innerHTML = ChansonHasard.titre5
document.querySelector("p.t6").innerHTML = ChansonHasard.titre6
document.querySelector("p.t7").innerHTML = ChansonHasard.titre7
document.querySelector("p.t8").innerHTML = ChansonHasard.titre8
document.querySelector("p.t9").innerHTML = ChansonHasard.titre9
document.querySelector("p.t10").innerHTML = ChansonHasard.titre10
Then I hide them with an image, and I create a "Flip ()" to flip and see the title (a bit like "Family Feud")
I can't memorize all the locations when I play so I would like to have another "Response" page.
The same page without the images that hides the answers.
The problem is that I use "Math Random" so from page to page I wouldn't have the same singer.
So ... do you have any ideas?
Thanks again for reading me.
Below is my suggestion
Its cleaner/safer to have the values saved in a database as against another web page.
So create a database and have the values inputed into it everytime a title is chosen, i hope this helps.
Use url parameters to pass a seed. The host page can provide a link including the seed. The link can be to the same page, but with url parameters. Host/guest uses the seed provided or generates one otherwise. This is consistent.
I'm getting function () { [native code] } value in HTML result.
function getWarning(type) get the warning by type from warnings array.
function getCaches() get all cached warning from caches array.
function cacheWarning(type) add cached warning if not in caches
array.
JavaScript :
var warnings=['- Le nom très petite !','- Cette prénom très petite ! !',"- Votre age invalide, le moin de l'age est 18 !","- Le numéro de téléphone incorrect !",'- Email invalide !',"- Le mot de pass doit de contient les caractéres et les nombres !",'- Le mot de pass sans confirmer !'];
var caches=new Array("");
var i=0;
function getWarning(type){
i=0;
for(i in warnings){
if(warnings[i].includes(type)){return warnings[i];}
}
}
function getCaches(){
let allCaches="";
i=0;
for(i in caches){
allCaches+=caches[i]+"<br/>";
}
return allCaches;
}
function cacheWarning(type){
i=0;
for(i in caches){
if(caches[i]==getWarning(type)){
return -1;
}
}
caches[caches.length]=getWarning(type);
}
if(document.getElementsByName("prenom")[0].value.length<=2){if(cacheWarning("prénom")!=-1){$("#content").html(getCaches())}}
Debugage result:
HTML result:
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.