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();
}
Related
I'm using jQuery to get values from ajax rest call, I'm trying to concatenate these values into an 'a' tag in order to create a pagination section for my results (picture attached).
I'm sending the HTML (divHTMLPages) but the result is not well-formed and not working, I've tried with double quotes and single but still not well-formed. So, I wonder if this is a good approach to accomplish what I need to create the pagination. The 'a' tag is going to trigger the onclick event with four parameters (query for rest call, department, row limit and the start row for display)
if (_startRow == 0) {
console.log("First page");
var currentPage = 1;
// Set Next Page
var nextPage = 2;
var startRowNextPage = _startRow + _rowLimit + 1;
var query = $('#queryU').val();
// page Link
divHTMLPages = "<strong>1</strong> ";
divHTMLPages += "<a href='#' onclick='getRESTResults(" + query + "', '" + _reg + "', " + _rowLimit + ", " + _startRow + ")>" + nextPage + "</a> ";
console.log("Next page: " + nextPage);
}
Thanks in advance for any help on this.
Pagination
Rather than trying to type out how the function should be called in an HTML string, it would be much more elegant to attach an event listener to the element in question. For example, assuming the parent element you're inserting elements into is called parent, you could do something like this:
const a = document.createElement('a');
a.href = '#';
a.textContent = nextPage;
a.onclick = () => getRESTResults(query, _reg, _rowLimit, _startRow);
parent.appendChild(a);
Once an event listener is attached, like with the onclick above, make sure not to change the innerHTML of the container (like with innerHTML += <something>), because that will corrupt any existing listeners inside the container - instead, append elements explicitly with methods like createElement and appendChild, as shown above, or use insertAdjacentHTML (which does not re-parse the whole container's contents).
$(function()
{
var query=10;
var _reg="12";
var _rowLimit="test";
var _startRow="aa";
var nextPage="testhref";
//before divHTMLPages+=,must be define divHTMLPages value
var divHTMLPages = "<a href='#' onclick=getRESTResults('"+query + "','" + _reg + "','" + _rowLimit + "','" + _startRow + "')>" + nextPage + "</a>";
///or use es6 `` Template literals
var divHTMLPages1 = `` + nextPage + ``;
$("#test").append("<div>"+divHTMLPages+"</div>");
$("#test").append("<div>"+divHTMLPages1+"</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>
Is it possible for me to carry the value of a button over to the function that that the button executes?
Simple concept, how would I get the value "5" to be carried over to my function where I can define it as a variable?
<button onclick="functionHere()" value="5">Delete</button>
Code actually looks more like:
<button onclick="functionHere()" value="' + aData[5] + '">' + 'Delete</button>
In your example you can reference the button element using this.
HTML:
<button onclick="functionHere(this)" value="' + aData[5] + '">' + 'Delete</button>
JS:
function functionHere (btn) {
var buttonValue = btn.value;
}
this references the context of the function. So in this case since the function was called by setting it as the onclick of the button, the functions context is the button element.
EDIT: I am mistaken actually this doesn't seem to be set automatically when used how you use it. Code updated. Here is a fiddle:
http://jsfiddle.net/9nv4sz6L/
You can do it like this.
<input type="button" value='Hello World' onclick='ShowValue(this)'/>
<script>
function ShowValue(btn){
alert(btn.value);
}
</script>
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
Basically, on clicking any image on a html page I want the id associated to be passed to a function.
This is what I have tried. It seems I am making a minor mistake here as I am getting the first id passed no matter what image I click from the array. I tried $(this).attr("id") as well, but did not work.
for(var i=0;i<jsonObj.length-1;i++){
var rows = '';
var bg_img = jsonObj[i].img;
var bg_img = decodeURIComponent(bg_img);
rows = "<img id='" + jsonObj[i].source_id + "' src='" + bg_img + "'/>";
document.getElementsByClassName('subscription')[i].innerHTML = rows;
}
$("body").delegate(".subscription", "click", function() {
// var id = $(this).attr("id");
alert("Welcome Test " + $('img').attr("id"));
return false;
});
$("img").click(function()
{
var id = $(this).attr("id");
});
Your $('img') selector is not confined to any specific area, so it will give you the first image on the entire page.
Try $('img',this) instead.
I have this code:
<html>
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#k123").click(function () {
//var text=$(this).val(); //this does not work
var text=$(this).text();
var k='<div id="k123"><textarea rows="10" cols="10">' + text + '</textarea><br /><input type="button" onclick="save();" value="save"><input type="button" onclick="cancel();" value="cancel"></div>';
$(this).replaceWith(k);
});
});
function save() {
}
function cancel() {
//alert(text);
var k='<div id="k123"></div>';
$("#k123").replaceWith(k);
}
</script>
</head>
<body>
<div id="k123">aaaaa</div>
</body>
</html>
My question is :
1)In both functions : cancel & save , How can I get content of div id->#k123->textarea->content
functions cancel & save are outside the scope and they are independent functions I cannot tell $(this).parent().
I need to ask about div which has id #k123 , then get inside to textarea's content and get it.
and I have also to get id #k123 automatically because if I have many divs I cannot tell save & cancel manually the div's id, cancel & save should know the div's id sender from the input type='button'`s parent id.
**please I do not prefer the suggestion of sending div id from input button
**We are assuming that both input buttons have no IDS or Names
I tried another way but still having same problem
I replaced
$(document).ready(function() {
$("#k123").click(function () {
var text=$(this).text();
var k='<div id="k123"><textarea rows="10" cols="10">' + text + '</textarea><br /><input type="button" value="save"><input type="button" value="cancel"></div>';
$(this).replaceWith(k);
});
//$("#k123 > input").click(function() {
$("#k123").children("input:second").click(function() {
alert("hi");
});
});
thank you.
I have the working code for you below. You don't even need an id.. just a container div and delegation of events. The below accomplishes what I thought you were after, in what I believe to be a much simpler, and much more efficient fashion:
(I've added comments to assist in understanding the code)
$(document).ready(function() {
$(".container").on('click', function(e) {
if (!$(e.target).is('input') && !$(e.target).is('textarea')) { //check to make sure the target is neither an input or a textarea
var div_text = $(e.target).text(); // use a variable named something other than text, because text is already a method for another element
$(e.target).data('text',div_text); // set the div's current contents as a hidden data attribute, to be retrieved later. You can get rid of this and the other line if you want cancel to completely wipe the div.
var k = '<textarea rows="10" cols="10">' + div_text + '</textarea><br /><input type="button" value="save"><input type="button" value="cancel">';
$(e.target).html(k); //set the inner HTML of the div, so we don't lose any data saved to that div
}
if ($(e.target).is('input') && $(e.target).val() == 'save') {
$(e.target).parent().html($(e.target).parent().find('textarea').val()); // replace the current contents of the parent div with the contents of the textarea within it.
} else if ($(e.target).is('input') && $(e.target).val() == 'cancel') {
$(e.target).parent().html($(e.target).parent().data('text')); //set the contents to the old contents, as stored in the data attribute. Just replace the contents of the .html() here with '' to completely clear it.
}
});
});
DEMO
REVISED - WORKS
Check this out... not quite there but close!
REVISED JS Fiddle
function editit() {
var divId = $(this).attr('id');
var text = $(this).html();
var k = '<div id="' + divId + '" class="editable"><textarea id="newvalue' + divId +'" rows="10" cols="10">' + text + '</textarea><br /><input id="save' + divId + '" type="button" value="save"><input id="cancel' + divId + '" type="button" value="cancel"></div>';
$('#' + divId).replaceWith(k);
$('#cancel' + divId).click(function() {
$('#' + divId).replaceWith('<div id="' + divId + '" class="editable">' + text + '</div>');
$('.editable').bind('click', editit);
});
$('#save' + divId).click(function() {
$('#' + divId).replaceWith('<div id="' + divId + '" class="editable">' + $("#newvalue" + divId).val()+ '</div>');
$('.editable').bind('click', editit);
});
}
$('.editable').bind('click', editit);