variable in onclick function of dynamically created button - javascript

Hy,
Basically, I have a number of dynamically generated list items with a button in them. When I prepend the list item to the ul list, I have access to a variable that I want to pass when I click the button in the list items. But when I add the variable in the line of code shown below, it gives me a Uncaught ReferenceError: challenger is not defined error. How can I pass these variable along?
JAVASCRIPT:
window.GLOBAL_socket.on('challenged', function(data) {
console.log("You have been challenged by the player " + data.challenger);
var challenged = getUrlVars()['user'];
var challenger = data.challenger;
$("#challengesList").prepend("<li><div id='newChallenge'><p id='challenge_header'>You have been challenged by: </p><p id='challenge_challenger'>" + data.challenger +
"</p><input type='button' value='ACCEPT' id='challenge_accept' onclick='acceptChallenge(challenger)'></input><input type='button' value='DECLINE' " +
"id='challenge_decline' onclick='declineChallenge(this)'></div></li>");
});
The onclick method is found on line 6.
Thanks for your responses,
Zeno

The reason why challenger is not defined is because it's a local variable and is not accessible globally when you actually trigger the function with a click.
So instead of using the variable, just place it's actual value in the onclick.
Change your code to:
$("#challengesList").prepend("<li><div id='newChallenge'><p id='challenge_header'>You have been challenged by: </p><p id='challenge_challenger'>" + data.challenger +
"</p><input type='button' value='ACCEPT' id='challenge_accept' onclick='acceptChallenge(\""+challenger+"\")'></input><input type='button' value='DECLINE' " +
"id='challenge_decline' onclick='declineChallenge(this)'></div></li>");

Change your code as I mentioned in comments.
var challenged = [];
var challenger = [];
var counter = 0;
window.GLOBAL_socket.on('challenged', function(data) {
console.log("You have been challenged by the player " + data.challenger);
counter++;
challenged[counter] = getUrlVars()['user'];
challenger[counter] = data.challenger;
$("#challengesList").prepend("<li><div id='newChallenge'><p id='challenge_header'>You have been challenged by: </p><p id='challenge_challenger'>"
+ data.challenger
+ "</p><input type='button' value='ACCEPT' id='challenge_accept'"
// change of code --> passing value directly into the function
+ " onclick='acceptChallenge(challenger["+counter+"]
+")'></input><input type='button' value='DECLINE' "
+ "id='challenge_decline' onclick='declineChallenge(this)'></div></li>");
});
I just modified code, hope it works for you. Let me know

Related

LocalStorage element not corresponding with visual element after moving

I created a note-taking front end page which saves the data from text field into the localStorage. The problem occurs when the user deletes one field using the Delete button, which corresopndents to DeleteT function.
For example if we have three textareas with id txt1, txt2, txt3 they apper with the sames names in the localStorage. After the user deletes for example txt2 using the Delete button, in the local Storage the left ones are txt1 and txt3 but on the next reload there are two textareas with id txt1 and txt2 because in the localStorage the number of textareas is saved by key AllNum. The data from txt3 in the localStorage should go to txt2 in the DOM on the page.
The problematic functions:
// Deletes textelemnt
function DeleteT(num) {
localStorage.removeItem("txt" + num);
localStorage.removeItem("h" + num);
console.log('del');
i=i-1;
var now = localStorage.getItem("AllNum");
if((now-1)<0){
now=0;
localStorage.setItem("AllNum", (0));
}else{
localStorage.setItem("AllNum", (now-1));
}
$("div.textarea" + num).remove();
}
//Loads all the text elemnts with a for loop until the number of areas is reached
function load() {
if (document.getElementById("alltxt").childElementCount < localStorage.getItem('AllNum')) {
for (var i = 1; i <= localStorage.getItem('AllNum'); i++) {
$('#alltxt').append('<div class="textarea' + i + '"><input onkeyup="save()" id="h' + i + '"></input><textarea onkeyup="save()" id="txt' + i + '"></textarea></br><button onClick="cut(txt' + i + ')" class="f b">Cut</button> <button onClick="copy(txt' + i + ')" class="f b">Copy</button> <button onClick="speak(txt' + i + ')" class="f b">Speak</button> <button onClick="download(' + i + ')" class="f a">Save</button><button onClick="textFull(' + i + ')" class="f">Fullscreen</button> <button onClick="DeleteT(' + i + ')" class="f">Delete</button> </div>');
document.getElementById('txt' + i).innerHTML = localStorage.getItem("txt" + i);
document.getElementById("h" + i).setAttribute('value', localStorage.getItem("h" + i));
}
}
}
https://codepen.io/abooo/pen/NoqOXX?editors=1010
To experience the problem create three textareas using the + button. Then Enter data in the them. After this delete the latter. Finally reload the page and make sure the two textreas appeared. You can see the data from the second one is missing replaced with null value. How to fix this issue?
The result
LocalStorage values
The value "AllNum" only stores total number of items; it does not contain any information about which items were there before reloading. So in first load, if you add 3 items and remove the 2nd, your local storage will have "AllNum" equal 2, and the next time it loads, your load() function will iterate from 1 to 2, looking for data of text1 and text2. That's why only 1st item displays correctly.
Another problem that you might notice after fixing the above issue is that the iteration is not good for unique id; a simple test can prove it: you add 3 items, remove the 2nd - now you have text1 and text3 in localStorage, and AllNum is 2. If you add one more, the newest item will have id as 3 and all its data will be written on top of the existing text3 and h3.
2 suggestion for your code:
Use something else as unique id instead of iteration number. Use Math.random(), for example.
Store all your unique ids in localStorage, not AllNum. Rewrite your code to add and delete unique ids from localStorage.
A small example of how to modify the 2 function add() and save():
function add() {
var newId = Math.random();
// your render logic here. Replace i with newId
save(newId);
}
function save(newId) {
localStorage.setItem("txt" + newId, document.getElementById('txt' + a).value);
localStorage.setItem("h" + newId, document.getElementById('h' + a).value);
var allIds = JSON.parse(localStorage.getItem('AllIds'));
allIds.push(newId);
localStorage.setItem("AllIds", JSON.stringify(allIds));
}

onchange event handler failing to call function

I have a function that uses:
name = "textBox" + (h) + (j);
id = "textBox" + (h) + (j);
value = hoursEachDay[j-1];
textBox = "<input type='text' maxlength='6' size='6' name='" + name + "'id='"+ id +"' value='" + value + "' onchange='updateHrs()'>";//or parent.updateHrs(j)
(h, i,and j being integers) to call another function that follows directly after the first function. That function is :
function updateHrs()// or updateHrs(dayOfMonth)
{
alert("This is the day changed ");
//or alert("This is the day changed " + dayOfMonth);
return;
}
I get a 'function not defined' error from firebug when I run this and trigger the onchange event handler. I have, on the suggestion of a coworker, changed updateHrs() to parent.updateHrs(), which actually works for some reason, until I try to pass a variable into the updateHrs() function (ass seen commented out above), at which point it declares that updateHrs(j) is not defined.
I am guessing that somehow the updateHrs function is being read as out of scope, although I'm not really sure how. Both of these functions are right after one another and both are right before the tag (yes there is a tag well above them as well), so they should not have a scope issue, not that I'm aware of anyway.
Thanks for any help that you can provide.

JQuery how to id of the button that called the function

I have a button <button onclick="takedown()"> that when it is clicked JQuery will create a new button with the id of the text in a input and button, when that button is clicked it will call a function deltebutton() which should delete the button, but I need for JQuery to get the id of the button which called the function and set it to a String called id.
I tryed $(event.target).attr('id'); and $(this).attr('id'); but both of them did not work
I goggled it but could not find anything.
This is the functions
function takedown(){
note = document.getElementById("noteinput").value;
idh1 = note + "h1";
idbutton = note + "button";
idcenter = note + "center";
$('<center id="' +idcenter + '"> <h1 idh1="' + idh1 + '">' + note + '</h1> <button id="'+ idbutton +'" onclick="deletenote()"> Delete </button> </center>').appendTo("body");
}
and
function deletenote(){
String id = $(event.target).attr('id');
$(id).remove();
}
If anybody knows how to do this, it will be very helpful.
Dont use String in JS and jQuery. And your selector is wrong.
function deletenote(){
var id = event.target.id;
$('#'+id).remove();
}
Also I think you can just call remove without getting the ID.
function deletenote(){
$(this).remove();
}
A simpler solution building on the previous answer and comments would be:
function deletenote(){
$(event.target).remove();
}

Parsing in jquery

I am trying to parse what I am getting JQuery to show data ! I am consuming data from an API , but I am getting an error .
Can I do a Loop on JQuery this way ?
$.each(data.results, function (i, item) { // on this line
var Name = item.name;
var Date = item.auditInfo.dateCreated;
var Creator = item.creator.display;
$htmlstring.append($('<li/>').append('<p>Test</p>'));
$htmlstring.append("<div class='title'> Info : "
Name + Date + Creator "</div>");
}); $('#afficher').html($htmlstring);
I am sharing code on JSFiddle (Check drug_omrsRestCall function ) :
http://jsfiddle.net/zTXyq/23/
As #adeneo commented on the question, the concept is right but you should be careful about what element you are appending HTML content to.
With this snippet of your code:
$htmlstring.append("<div class='title'> Info : "
Name + Date + Creator "</div>");
(BTW, it is missing two plus signs for a correct concatenation, I hope that's not the error you are getting).
you append a DIV to the UL and you actually want to append it to the LI, for example:
$('<li />').append("<p>Test</p>")
.append("<div class='title'> Info : " + Name + Date + Creator + "</div>")
.appendTo($htmlstring);
Check this fiddle for a working solution of your issue:
http://jsfiddle.net/d3dcj/2/

term_exists not working in Javascript

I finally got my back-end to create the wheel codes from the checked taxonomies in the add custom post admin area.
Now, I want to add that tire code to the wheel_type taxonomy.
The below code ran great, until I added the if statement under //Add code to Taxonomy
Now nothing is working, but I get nothing in the error console.
I figure it must be a stupid syntax mistake - can anyone help me out?
Or am I missing something else?
jQuery('#replace').click(function(){
//get tire code and name
var code = jQuery('input[name="tire_code"]').val();
var name = jQuery('input[name="tire_name"]').val();
var bname = jQuery('input[name="tire_bname"]').val();
alert(code + " + " + name + " + " + bname);
//get tire brand
var tirebran = jQuery('#tire_brandchecklist').find(":checked").parent('label').text();
tirebran = jQuery.trim( tirebran );
//Add code to Taxonomy
if( term_exists( code, wheel_type ){
continue;
}
else
{
wp_insert_term( code, wheel_type );
}
//update title
var title = code + ' : ' + name + ' tires';
if(tirebran!=''){
title += ' with ' + bname + ' letters';
}
jQuery('input[name="post_title"]').focus().val(title);
});
//-->
</script>
unless i've misunderstood your question, you're trying to call wordpress methods via javascript.
term_exists() and wp_insert_term() are PHP methods within the wordpress code, not accessible directly via Javascript (unless you have written interfaces to them).
continue doesn't make any sense there; just check for !term_exists... and call wp_insert_term when it doesn't exist.
if (!term_exists(code, wheel_type)) {
wp_insert_term(code, wheel_type);
}
The continue statement is for continuing loops from the top of the loop; it does not stand on its own.

Categories