I have the following markup
<div class="col-md-4">
<div class="row">
<img name="previewImage" alt="" src="" style="max-height:300px;max-width :350px;">
</div>
<div class="row">
<button name="btnPushPhoto" type="button" class="btn btn-default" tabindex="-1">Push</button>
<button name="btnRemovePhoto" type="button" class="btn btn-default" tabindex="-1">Remove</button>
</div>
</div>
When I click on the remove photo button, I'm able to set my image to null (in the server side), however at the client side, I'm having some difficulties locating the image tag, and refresh it.
$(document).on("click", "[name=btnRemovePhoto]", function () {
var r = confirm("Are you sure you want to remove the photo?");
if (r == true) {
var uniqueId = $(this).data('uniqueId');
$.post($("#remove-photo-url").val(), { uniqueId: uniqueId })
.done(function () {
//var img = $(this).closest('[name=previewImage]');
var img = $(this).parent().parent().find('[name=previewImage]');
console.log(img);
img.attr('src', '');
img.attr('src', img.attr('src') + '?' + Math.random());
});
}
});
Nothing seems to happen here. No error in the browser's console.
This is the output of console.log(img);
[prevObject: x.fn.x.init[0], context: undefined, selector: "[name=previewImage]"]
You should store the $(this) in some variable before post request since inside the callback, this refers to the jqXHR object of the Ajax call, not the element the event handler was bound to :
_this = $(this);
Then you could use parents() instead :
var img = _this.parents('.col-md-4').find('[name="previewImage"]');
Hope this helps.
Try this:
$(document).on("click", "[name=btnRemovePhoto]", function () {
var r = confirm("Are you sure you want to remove the photo?");
if (r == true) {
var uniqueId = $(this).data('uniqueId');
var $this = $(this); //Insert this line
$.post($("#remove-photo-url").val(), { uniqueId: uniqueId })
.done(function () {
var img = $this.closest("div.col-md-4").find("img"); //USE $this
console.log(img);
img.attr('src', '');
img.attr('src', img.attr('src') + '?' + Math.random());
});
}
});
You should move img definition before the $.post function:
$(document).on("click", "[name=btnRemovePhoto]", function () {
var img = $(this).parent().parent().find('[name=previewImage]');
var r = confirm("Are you sure you want to remove the photo?");
if (r == true) {
var uniqueId = $(this).data('uniqueId');
$.post($("#remove-photo-url").val(), { uniqueId: uniqueId })
.done(function () {
//var img = $(this).closest('[name=previewImage]');
console.log(img);
img.attr('src', '');
img.attr('src', img.attr('src') + '?' + Math.random());
});
}
});
I think the way you are searching/looking at the relationship needs to be edited slightly. There are a few jquery methods that may help but I usually like to map out the relationships in my head like below:
<div name="PARENT_of_PARENT_of_X">
<div name="Sibling_of_PARENT_of_X OR child_of_PARENT_of_PARENT_of_X>
<img name="Child_of_SIBLING_of_PARENT_of_X OR CHILD_of_PARENT_of_PARENT_of_X" />
</div>
<div name="PARENT_of_X">
<button ></button>
<button name="SOURCE X" >Remove</button>
</div>
</div>
You could use jQuery selector "closest"
https://api.jquery.com/closest/
$(document).on("click", "[name=btnRemovePhoto]", function () {
var clickedButton = $(this);
var r = confirm("Are you sure you want to remove the photo?");
if (r == true) {
var uniqueId = $(this).data('uniqueId');
$.post($("#remove-photo-url").val(), { uniqueId: uniqueId })
.done(function () {
var img = clickedButton .closest("div.col-md-4").find("img");
console.log(img);
img.attr('src', '');
img.attr('src', img.attr('src') + '?' + Math.random());
});
}
});
Related
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
In my AJAX success function, I've written:
rt = JSON.parse(responseText);
for (i = 0; i < rt.length; i++) {
$("#inv").append("<tr><td>" + rt[i][0] +
"</td><td><input type='submit' value='Sync' " +
"class='syncnow' id='sync"+rt[i][6]+"' /></td></tr>");
}
I've tried jQuery code:
$(".syncnow").on("click", function() {
alert("Hi");
});
Tried .click(), $(".tdclass").on("click", ".syncnow", function() {}) etc., but to no avail. Can anyone help me with this?
You can't add an event to a not yet created element. You need to add it to a higher place and catch it when it is bubbling up.
Try this:
$("body").on("click", ".syncnow", function() {
console.log('clicked');
} )
$("#inv").append("<input type='submit' value='Sync' class='syncnow' id='sync' />");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inv">
</div>
You can attach event to element when created using jQuery()
$.each(rt, function(i, value) {
$("<tr>", {
appendTo: "#inv",
html: $("<td>", {
html: value[0],
append: $("<input>", {
type: "submit",
value: "Sync",
"class": "syncnow",
id: value[6],
on: {
click: function(event) {
console.log("clicked");
}
}
})
})
})
})
Try this one
$(document).on("click", ".syncnow", function() {
alert('clicked');
} )
$("#inv").append("<input type='submit' value='Sync' class='syncnow' id='sync' />");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inv">
</div>
I've written a jquery function, to append syncbuttons to an invElement
$.fn.appendSyncElements = function(responseText, onComplete) {
var invElement = $(this);
var rt = JSON.parse(responseText);
var base_sync_attrs = [];
base_sync_attrs.push("type=\"submit\"");
base_sync_attrs.push("value=\"Sync\"");
base_sync_attrs.push("class=\"syncnow\"");
var base_sync_attrs_str = base_sync_attrs.join(' ');
for(var i = 0; i < rt.length; i++) {
var crt = rt[i];
var crt_sync_label = crt[0];
var crt_sync_attrs = crt[6];
var sync_attrs = [];
sync_attrs.push(base_sync_attrs_str);
sync_attrs.push("id=\"sync_" + String(i) + "\"");
sync_attrs.push("data-sync_index=\"" + String(i) + "\"");
sync_attrs.push(crt_sync_attrs);
var sync_attrs_str = sync_attrs.join(' ');
var syncElement = $('<input ' + sync_attrs_str + ' />');
syncElement.click(function(e) {
var syncBtn = $(this);
console.log("the syncBtn was clicked at index " + String(syncBtn.data('sync_index'));
var syncEvent = {
'event' : e,
'button' : syncBtn,
'fullresponse': crt,
};
if(typeof(onComplete) === 'function') {
onComplete(syncEvent)
};
});
var tableRowElement = $('<tr><td class="synclabel" ></td><td class="syncinput" ></td></tr>');
tableRowElement.find("td.synclabel").html(crt_sync_label);
tableRowElement.find("td.syncinput").append(syncElement);
invElement.append(tableRowElement);
};
};
Usage
$("#inv").appendSyncElements(responseText);
Or
$("#inv").appendSyncElements(responseText, function(syncResult) {
console.log("This is a custom Complete Method");
});
You can use document on click event:
$(document).on("click",".syncnow",function() {
alert("Working");
});
Also you can check my answer here:
Why is jQuery on-click event handler not working properly for dynamic loaded DOM elements?
Thanks
$("body").on("click",".syncnow", function() {} )
I want to create links, based on a specific format.
When I type this:
google->apple
I want get get this link:
https://www.google.hu/search?q=apple
I tried this way, but unfortunately it is not working:
//Intelligent actions start
function replace(){
var str = $('.smile').html();
var re = /google->([^ \n$]+)/g;
var url = "https://www.google.hu/search?q=" + re.exec(str)[1];
}
//Intelligent actions end
Update
Based #vinayakj answer, I start create a solution for this:
//Intelligent actions start
function googleSearch(val){
var url = "https://www.google.hu/search?q=" + val.split('->')[1];
alert(url)
//location.href = url;
}
$( document ).ready(function() {
googleSearch($('.comment-content p').text())
$( ".comment-content p" ).replaceWith( "<a href='url'>url</a>" );
});
//Intelligent actions end
And looks like replacewith function reaplce all content in
.comment-content p
with:
url
And this function it has some problem:
Reaplce all text even if dosen't find this sting in div:
google-->some word
The link is absolute incorrect becouse I get back this value everywhere:
url
What am I doing wrong?
function googleSearch(val){
var url = "https://www.google.hu/search?q=" + val.split('->')[1];
alert(url)
location.href = url;
}
<input onchange="googleSearch(this.value)" type=text>
Here is the final solution after all your comments
var urls = {
"google":"https://google.com/search?q=#",
"bing":"https://....q=#&bla=bla"};
function getUrl(str) {
var parts = str.split("->");
var url = urls[parts[0]].replace("#",encodeURI(parts[1]));
return = $("<a/>",{href: url, class:parts[0]+"-search"}).text("Keresés ..."+parts[1]);
}
$(function() {
$("div.comment-content > p.smile").each(function() {
var $link = getLink($(this).text());
$(this).html($link);
});
});
Old answer
var urls = {
"google":"https://google.com/search?q=#",
"bing":"https://....q=#&bla=bla"};
function getUrl(str) {
var parts = str.split("->");
return urls[parts[0]].replace("#",parts[1]);
}
window.onload=function() {
document.getElementById("myForm").onsubmit=function() {
var str = document.getElementById("q").value;
var url = getUrl(str);
if (url) alert(url); // location.href=url;
return false; // cancel the submit
}
}
<form id="myForm">
<input id="q" type="text">
</form>
I found the solution, but thanks for everybody:
$("div.comment-content > p.smile").each(function(){
var original = $(this).text();
var replaced = original.replace(/google->([^.\n$]+)/gi, '<a class="google-search" href="https://www.google.hu/search?q=$1" target="_blank">Keresés a googleben erre: $1</a>' );
$(this).html(replaced);
console.log("replaced: "+replaced);
});
$("a.google-search").each( function() {
this.href = this.href.replace(/\s/g,"%20");
});
I have two divs.
<div class="my_thing" data-id="123"></div>
<div class="my_thing" data-id="529"></div>
When a div is clicked, I want to get the data-id for the clicked div, and the data-id for the one that wasn't clicked. So I end up with this object:
{
clicked_id = 123,
not_clicked_id = 529
}
How can I do this? This is what I have so far.
$('.my_thing').click(function(){
var clicked_id = $(this).attr('data-id');
var not_clicked_id = ?????
});
If there will be only 2 .my_thing elements then you can use .not() like
var $divs = $('.my_thing').click(function() {
var clicked_id = $(this).attr('data-id');
var not_clicked_id = $divs.not(this).attr('data-id');
log(clicked_id + '-' + not_clicked_id)
});
var log = (function() {
var $log = $('#log');
return function(msg) {
$('<p/>', {
text: msg
}).prependTo($log)
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="my_thing" data-id="123">123</div>
<div class="my_thing" data-id="529">529</div>
<div id="log"></div>
I've just created an dynamic HTML form and two of its fields are of type date. Those two fields are posting their data into two arrays. I have 2 issues:
a) The array data are not printed when I press the button.
b) Since I created the arrays to store the data, my dynamic form doesn't seem to be fully functional. It only produces new fields when I press the first "Save entry" button on the form. It also doesn't delete any fields.
My code is:
$(document).ready(function () {
$('#btnAdd').click(function () {
var $address = $('#address');
var num = $('.clonedAddress').length;
var newNum = new Number(num + 1);
var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress');
newElem.children('div').each(function (i) {
this.id = 'input' + (newNum * 10 + i);
});
newElem.find('input').each(function () {
this.id = this.id + newNum;
this.name = this.name + newNum;
});
if (num > 0) {
$('.clonedAddress:last').after(newElem);
} else {
$address.after(newElem);
}
$('#btnDel').removeAttr('disabled');
});
$('#btnDel').click(function () {
$('.clonedAddress:last').remove();
$('#btnAdd').removeAttr('disabled');
if ($('.clonedAddress').length == 0) {
$('#btnDel').attr('disabled', 'disabled');
}
});
$('#btnDel').attr('disabled', 'disabled');
});
$(function () {
$("#datepicker1").datepicker({
dateFormat: "yy-mm-dd"
}).datepicker("setDate", "0");
});
var startDateArray = new Array();
var endDateArray = new Array();
function intertDates() {
var inputs = document.getElementsById('datepicker1').value;
var inputsend = document.getElementsById('datepicker2').value;
startDateArray[startDateArray.length] = inputs;
endDateArray[endDateArray.length] = inputsend;
window.alert("Entries added!");
}
function show() {
var content = "<b>Elements of the arrays:</b><br>";
for (var i = 0; i < startDateArray.length; i++) {
content += startDateArray[i] + "<br>";
}
for (var i = 0; i < endDateArray.length; i++) {
content += endDateArray[i] + "<br>";
}
}
JSFIDDLE
Any ideas? Thanks.
On your button you are using element ID's several times, this is so wrong, IDs must be unique for each element, for example:
<button id="btnAdd" onclick="insertDates()">Save entry</button>
</div>
</div>
<button id="btnAdd">Add Address</button>
<button id="btnDel">Delete Address</button>
jQuery will attach the $('#btnAdd') event only on the first #btnAdd it finds.
You need to use classes to attach similar events to multiple elements, and in addition to that simply change all the .click handlers to .on('click', because the on() directive appends the function to present and future elements where as .click() only does on the existing elements when the page is loaded.
For example:
<button id="btnDel">Delete Address</button>
$('#btnDel').click(function () {
[...]
});
Becomes:
<button class="btnDel">Delete Address</button>
$('.btnDel').on('click', function () {
[...]
});
Try this : I know its not answer but it's wrong to get element value using id
Replace
var inputs = document.getElementsById('datepicker1').value;
var inputsend = document.getElementsById('datepicker2').value;
With
var inputs = document.getElementById('datepicker1').value;
var inputsend = document.getElementById('datepicker2').value;
You are using jQuery so i will strongly recommend you to stick with the jQuery selector,
var inputs = $('#datepicker1').val();
var inputsend = $('#datepicker2').val();
where # is used for ID selector.
I have the following content in -
var jsonObj = [ {"name" : "Jason"},{"name":"Bourne"},{"name":"Peter"},{"name":"Marks"}];
<!---->
$("#getname").click(function() {
var response = getNames(jsonObj);
$("#nameData").html(response);
});
function getNames(jsonObj){
var response = JSON.stringify(jsonObj);
for ( var i = 0, len = jsonObj.length; i < len; i++) {
var nameVal = jsonObj[i].name;
response = response.replace(nameVal,replaceTxt(nameVal,i));
}
return response;
}
function replaceTxt(nameVal,cnt){
return "<u id='"+cnt+"' name='names' >"+nameVal+"</u> ";
}
$('u[name="names"]').dblclick(function(){
var currentId = $(this).attr('id');
alert(currentId);
});
});
and html as below -
<button id="getname">Get Name</button>
<div id="nameData"></div>
Double clicking on names value doesn't generating alerts.
are you sure it is..
<dev id="nameData"></dev>
OR
<div id="nameData"></div>
this works...but you have an extra }); in the question...(don't know if it is a typo)
fiddle here
Try this:
$(document).ready(function(){
$('u[name="names"]').live("dblclick", function(){
var currentId = $(this).attr('id');
alert(currentId);
});
});
Try moving this code:
$('u[name="names"]').dblclick(function(){
var currentId = $(this).attr('id');
alert(currentId);
});
});
inside
$("#getname").click(function() {
var response = getNames(jsonObj);
$("#nameData").html(response);
});
like:
$("#getname").click(function() {
var response = getNames(jsonObj);
$("#nameData").html(response);
$('u[name="names"]').dblclick(function(){
var currentId = $(this).attr('id');
alert(currentId);
});
});
});
You don't need the last "});" Or you didn't paste the whole code.
Look here: http://jsfiddle.net/4cajw/1/
As your code suggest that you are .dblclick()ing on dynamically generated element, that don't work, you have to select parent elem which exist in the document
$(document).on('dblclick','u[name="names"]', function(){
var currentId = $(this).attr('id');
alert(currentId);
});
try this out.
JSON.stringify - object -> JSON.
JSON.parse - JSON -> object