hide a dynamically created element with jquery - javascript

I am getting data through ajax.I have an array holding all the data.Now I am running a loop through the array and dynamically creating a 'p' and a 'button' corresponding to each element of the array.If I click the button the innerHTML of corresponding 'p' should be passed to ajax and the button must disappear.Here is the sample of what i tried:
<script>
for(var i=0;i<foo.length;i++)
{
addElement(foo[i],i);
}
function addElement(foo,i)
{
ni=document.getElementById("asdf");
new_but=document.createElement('input');
new_p=document.createElement('p');
new_p.id='text'+toString(i);
new_p.innerHTML=foo;
new_but.type='button';
new_but.value='add';
new_but.id=toString(i);
new_but.className='but';
ni.appendChild(new_p);
ni.appendChild(new_but);
}
$(document).ready(function(){
$('.but').each(function(){
$(this).click(function(){
$.ajax({
type:'POST',
data:'awdwad',
url:'aadwewq.php',
success:function(result)
{
if(result==no_error)
$(this).hide();
}
});});});});
</script>
The elements are created but I am unable to access them later using their ids or classes with jquery.

The problem is because the click handler is being assigned onload, when the .but element does not exist. You need to delegate the click handler to the parent element like this:
$(document).ready(function(){
$('#asdf').on('click', '.but', function(){
$.ajax({
type:'POST',
data:'awdwad',
url:'aadwewq.php',
success:function(result) {
if (result == no_error)
$(this).hide();
}
});
});
});
Also, you can shorten your addElement function using jQuery like this:
function addElement(foo, i) {
var $ni = $('#asdf');
var $p = $('<p></p>', { 'id', 'text' + toString(i) }).html(foo).appendTo($ni);
var $button = $('<input></input>', {
'type': 'button',
'id': toString(i),
'class': 'but'
}).appendTo($ni);
}

Use .on and attach event on some parent object or document. Also there is no need to iterate over objects.
$(document).on("click", ".but", function(){
});

this inside your success callback of your $.ajax call refers to the ajax call itself.
You should make a reference to the button first.
With the feedback of the other answers combined:
$(function() {
$(document).on('click', '.but', function() {
var btn = $(this);
$.ajax({
type:'POST',
data:'awdwad',
url:'aadwewq.php',
success:function(result)
{
if(result==no_error)
$(btn).hide();
}
});
});
});

function addElement(foo,i){
ni=document.getElementById("asdf");
new_but=document.createElement('input');
new_p=document.createElement('p');
new_p.id='text'+i; //remove toString
new_p.innerHTML=foo;
new_but.type='button';
new_but.value='add';
new_but.id=i; // remove toString
new_but.className='but';
ni.appendChild(new_p);
ni.appendChild(new_but);
}

Related

How to make jquery find the row and fire an action on success (using "this")

This is a jquery code that performs a database update when the user modifies a cell:
$( document ).ready(function() {
$('tr').on('blur', 'td[contenteditable]', function() {
$.post("ajax/modQtyModels", {
modelId: $(this).closest('tr').children('td.idmodel').text(),
qty: $(this).closest('tr').children('td.editQty').text(),
ajax: true,
success: function(data) {
$(this).closest('tr').children('td.editQty').addClass("success");
}
});
});
});
In the "success" part I want it to just change the class (to change its color as it uses bootstrap) of that cell to show the user that their data changed successfully but it doesn't seem to notice that it has to change the color. I've tried everything on that line but I guess the line is not the problem. Other actions like an alert work well so I suspect of the $(this).
In the success callback you are dealing with another function, so the scope is no longer the one of your blur event callback, so this keyword will point out to another object and not your jQuery element.
So you need to save the this value in another variable and refer to your element with this neww variable, inside the success callback.
(document).ready(function() {
$('tr').on('blur', 'td[contenteditable]', function() {
var tr = $(this);
$.post("ajax/modQtyModels", {
modelId: $(this).closest('tr').children('td.idmodel').text(),
qty: $(this).closest('tr').children('td.editQty').text(),
ajax: true,
success: function(data) {
tr.closest('tr').children('td.editQty').addClass("success");
}
});
});
});
this inside of success: function(data) { does not refer to this inside of $('tr').on('blur'
You can save the value of this (typically in a variable called that), so that when you are in that new function, you can do:
$( document ).ready(function() {
$('tr').on('blur', 'td[contenteditable]', function() {
var that = this;
$.post("ajax/modQtyModels", {
modelId: $(this).closest('tr').children('td.idmodel').text(),
qty: $(this).closest('tr').children('td.editQty').text(),
ajax: true,
success: function(data) {
$(that).closest('tr').children('td.editQty').addClass("success");
}
});
});
});

Jquery addClass -- Function for New Class

I have a issue in my js file.
This is my Js Code.
<script type="text/javascript">
$(document).ready(function()
{
$(".abc").click(function()
{
$(this).addClass('testingClass');
});
$(".testingClass").click(function()
{
alert("hiiiiiiiiiiiiiiiiii")
});
});
</script>
My HTML :
<button class="abc">Demo</button>
When i load this page in Browser, The addClass function is successfully executing and adding new class named "testingClass".
But When Try to click again t that button (meens : class="testingClass") the alert function does not working. What is the error.
Is JS is not supporting frequent execution of an element ?
Anybody Please help me.
Steps..
One Button has class named abc
When click on it an ajax function will storing current time in database.(ajax function not in stack-code).
after successful ajax response the button class changed to testingClass.
now the class name of the button is testingClass
After some time Click on the Button again (class named:testingClass), i want to call a ajax function with current time of click and store the values in database.
Then the Button class name will changed to old ( abc).
You need to event delegation for dynamic added element
$(document).on("click",".testingClass",function()
{
alert("hiiiiiiiiiiiiiiiiii")
});
Event delegation
Update
For the changed question, you are looking for something like this.
Here is a demo.
$('body').on('click', '.abc', function () {
// event attached to .abc
// updateTime is a method that takes context (this), current timestamp and a function
// we need to send the context so that we have access to the current
element inside the below function which is executed outside the scope
updateTime.call(this, new Date().getTime(), function (data) {
$(this).addClass('testingClass').removeClass('abc');
$('#log').append('Time: ' + data + 'from abc <br/>');
});
}).on('click', '.testingClass', function () {
// event attached to .abc
updateTime.call(this, new Date().getTime(), function (data) {
$(this).addClass('abc').removeClass('testingClass');
$('#log').append('Time: ' + data + ' from testingclass <br/>');
});
});
function updateTime(currentTime, successCallback) {
$.ajax({
context: this, // the context sent from the above methods is used here
url: '/echo/html/',
data: {
html: currentTime
},
method: 'post',
success: successCallback
});
}
Using .one() will help you attach event only once upon multiple clicks.
This handler is executed at most once per element per event type.
I think this is what you are looking for. Adding a handler after the class is added.
$(".abc").click(function(){
$(this).addClass('testingClass');
$(".testingClass").one('click', function() {
alert("hiiiiiiiiiiiiiiiiii");
});
});
$(document).ready(function() {
$(".abc").click(function() {
$(this).addClass('testingClass');
$(".testingClass").one('click', function() {
alert("hiiiiiiiiiiiiiiiiii");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="abc">Demo</button>

How to add two different ID with Ajax

I am using an Ajax function for show the auto suggestions for search field. But, I've to search field on the same page. So, when I am trying to use this then one is work and another one isn't. It's because Both of those are using couple of same ID and Class. I style them with CSS for different width and height.
Can anyone please help me know how may I add one more ID and Class on the below code for each field?
$(document).ready(function() {
$("#email").keyup(function() {
var searchid = $(this).val();
var dataString = 'type=' + searchid;
if (searchid != ' ') {
$.ajax({
type: "POST",
url: "type_process.php",
data: dataString,
cache: false,
success: function(html) {
$("#result").html(html).show();
}
});
}
return false;
});
$(document).click(function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("get_types")) {
jQuery("#result").fadeOut();
}
});
$('#email').click(function(){
jQuery("#result").fadeIn();
});
});
When you select 2 element (or more) you can refer to a single one by specifing the element index.
$('.item').eq(0); // return the first element in a collection with class '.item'
or
$('.item').eq(1); // return second element in a collection with class '.item'
BTW, you should avoid having elements with the same ID in the DOM
If you want to select lots of differents elements, use a Class tag instead.
Mark all your elements with the same class, like: class="mySelectorClass" and then, use a jquery selector:
$(".mySelectorClass").each(function(index,value){
// ... your code for each element goes here!
});
https://api.jquery.com/jQuery.each/

jquery onclick runs twice

I have the following javascript when my script is loaded:
var current_selected_note = $('#new_note');
current_selected_note.addClass('hover active');
$('#note-item-lists').on('click', '.list-group-item', function () {
//removes the hover color from the previous selected
current_selected_note.removeClass('hover active');
// sets the currently selected equal to the selected note
current_selected_note = $(this);
// adds the hover active to the currently selected
current_selected_note.addClass('hover active');
//adds the title of the currently selected to the title input field
$('#txt_new_note_title').val($(this).find('Strong').text());
selected_note_id = $(this).get(0).id;
getNote(selected_note_id);
load_comments(selected_note_id);
});
$( "#note-item-lists").find('li').first().trigger( "click" );
Now AFTER this is loaded i click one of my buttons which has the following javascript:
$('#note-item-lists').on('click','.close',function(){
var r = confirm('Are you sure you wish to delete "'+$(this).next('div').find('.new_note_title').text()+'" ?')
if(r == true){
deleteNote($(this));
$( "#note-item-lists").find('li').first().click();
}
})
function deleteNote(button){
var id = button.closest('li').get(0).id;
$.ajax({
type: 'POST',
url: '/solo/ajax_delete',
dataType: 'json',
data: {
id: id
},
success: function (data) {
}
});
button.closest('li').remove();
}
When this happens (i debug it) and the event function is called first 1 time (adding the class correctly) but is then happens immediatly again.
Anyone tried this before?
Try this, It will call one time.
$('#note-item-lists .close').on('click',function(){
alert("Hello");
});
Try using .off()
$('#note-item-lists').on('click', '.list-group-item', function () {
$(this).off(); //add this here

jQuery: Referencing the calling object(this) when the bind/click event is for a class

Thanks for reading this.
I am dynamically generating some data which includes a select drop-down with a text box next to it. If the user clicks the select, I am dynamically populating it (code below). I have a class on the select and I was hoping the following code would work. I tested it with an ID on the select and putting the ONE on the ID I got it to work. However, in changing the code to reference a class (since there will be multiple data groups that include a select with a text box next to it) and $(this), I could not get it to work. Any ideas would be helpful. Thanks
The relevance of the text box next to the select is the second part of the code...to update the text box when an option is selected in the select
.one is so the select is updated only once, then the .bind allows any options selected to be placed in the adjacent text box.
$('.classSelect').one("click",
function() {
$.ajax({
type: "post",
url: myURL ,
dataType: "text",
data: {
'_service' : myService,
'_program' : myProgram ,
'param' : myParams
},
success:
function(request) {
$(this).html(request); // populate select box
} // End success
}); // End ajax method
$(this).bind("click",
function() {
$(this).next().val($(this).val());
}); // End BIND
}); // End One
<select id="mySelect" class="classSelect"></select>
<input type="text">
$(this) is only relevant within the scope of the function. outside of the function though, it loses that reference:
$('.classSelect').one("click", function() {
$(this); // refers to $('.classSelect')
$.ajax({
// content
$(this); // does not refer to $('.classSelect')
});
});
a better way to handle this may be:
$('.classSelect').one("click", function() {
var e = $(this);
$.ajax({
...
success : function(request) {
e.html(request);
}
}); // end ajax
$(this).bind('click', function() {
// bind stuff
}); // end bind
}); // end one
by the way, are you familiar with the load() method? i find it easier for basic ajax (as it acts on the wrapped set, instead of it being a standalone function like $.ajax(). here's how i would rewrite this using load():
$('.classSelect').one('click', function() {
var options = {
type : 'post',
dataType : 'text',
data : {
'_service' : myService,
'_program' : myProgram ,
'param' : myParams
}
} // end options
// load() will automatically load your .classSelect with the results
$(this).load(myUrl, options);
$(this).click(function() {
// etc...
}); // end click
}); // end one
I believe that this is because the function attached to the success event doesn't know what 'this' is as it is run independently of the object you're calling it within. (I'm not explaining it very well, but I think it's to do with closures.)
I think if you added the following line before the $.ajax call:
var _this = this;
and then in the success function used that variable:
success:
function(request) {
_this.html(request); // populate select box
}
it may well work
That is matching one select. You need to match multiple elements so you want
$("select[class='classSelect']") ...
The success() function does not know about this, as any other event callback (they are run outside the object scope).
You need to close the variable in the scope of the success function, but what you really need is not "this", but $(this)
So:
var that = $(this);
... some code ...
success: function(request) {
that.html(request)
}
Thanks Owen. Although there may be a better to write the code (with chaining)....my problem with this code was $(this) was not available in the .ajax and .bind calls..so storing it in a var and using that var was the solution.
Thanks again.
$('.classSelect').one("click",
function() {
var e = $(this) ;
$.ajax({
type: "post",
url: myURL ,
dataType: "text",
data: {
'_service' : myService,
'_program' : myProgram ,
'param' : myParams
},
success:
function(request) {
$(e).html(request); // populate select box
} // End success
}); // End ajax method
$(e).one("click",
function() {
$(e).next().val($(e).val());
}); // End BIND
}); // End One

Categories