How I fix this jquery / ajax issue? - javascript

Basically I am having a table like below:
<tbody>
<tr>
<td><img class="img-thumbnail" src="./images/no_image.png" width="100" height="100"></td>
<td><button class="change_image" data-image_id="1">Change Image</button></td>
<td><input type="text" name="sort[]" size="7" placeholder="Sort order"></td>
</tr>
<tr>
<td><img class="img-thumbnail" src="./images/no_image.png" width="100" height="100"></td>
<td><button class="change_image" data-image_id="2">Change Image</button></td>
<td><input type="text" name="sort[]" size="7" placeholder="Sort order"></td>
</tr>
<tr>
<td><img class="img-thumbnail" src="./images/no_image.png" width="100" height="100"></td>
<td><button class="change_image" data-image_id="3">Change Image</button></td>
<td><input type="text" name="sort[]" size="7" placeholder="Sort order"></td>
</tr>
</tbody>
When click on .change_image button, its opening a modal to change that image.
This is how my modal open:
$('#manage_images').on('click', '.change_image', function(){
window.tr = $(this).parents('tr');
var image_id = $(this).data("image_id")
$('#chage_pro_image_form')
.find('[name="image_id"]').val(image_id).end();
$("#modal").modal({
"backdrop" : "static",
"keyboard" : true,
"show" : true
});
});
Next thing is I want to submit form (which is in the modal) to change this image. I did it correctly using jquery/ajax
Now I want to replace old image with newly change image on this table row after ajax success.
This is how I tried it in ajax success function:
success: function(json) {
var json = JSON.parse(json);
if (json.success) {
$('#modal.modal').modal('hide');
$('#chage_pro_image_form').formValidation('resetForm', true);
d = new Date();
window.tr.find('img').fadeOut(1000, function() {
$("img").attr("src", json.image+"?"+d.getTime());
}).fadeIn(1000);
} else {
// my errors
}
}
My problem is, its replacing all existing images in the table with new one. I created a global variable window.tr. But it doesn't work for me.
Can anybody help me to figure this out?
Thank you.

Use this to reference the image instance inside the animation callback
window.tr.find('img').fadeOut(1000, function() {
$(this).attr("src", json.image+"?"+d.getTime());
}).fadeIn(1000);

Well obviously the $("img") selector will select all img elements. You need to somewhere store which button you changed as a variable. For instance by pointing to the data-image_id attribute. Then you can select it using:
$('[data-image_id='+image_id+']')

Related

How get the image src value

I want to get the src of a image when i click the image .that is in a table column
structure be like of the table is
<html>
<body>
<div>
<table>
<tr>
<td img src=" xxx "></td>
</tr>
<tr>
<td img src=" xxx "></td>
</tr>
<tr>
<td img src=" xxx "></td>
</tr>
</table>
</div>
</body>
</html>
please tell me a way to get the src of that image when i click the image and also i want to send that src to another html page
There are few mistakes in your code.
img is an separate html tag. You cannot set it as an attribute of td.
SO you html will be like this
HTML
<div>
<table>
<tr>
<td><img src=" xxx ">1</td>
</tr>
<tr>
<td><img src=" xxx2 ">2</td>
</tr>
<tr>
<td><img src=" xxx3 ">3</td>
</tr>
</table>
</div>
To get the src value , you can use getElementsByTagName which will give you a collection of all images.
Then loop through it and add addEventListener inside a closure. You can also use getAttribute the get any attribute of the tag
JS
// get all the images
var getAllImages = document.getElementsByTagName('img');
// loop through it
for (var i = 0; i < getAllImages.length; i++) {
(function(x) { // closure starts here
getAllImages[x].addEventListener('click', function() {
alert(this.getAttribute('src'))
})
}(i)) // pass the value of i
}
DEMO
Try
const img = document.querySelector('img');
.addEventListener('click', (event) => {
alert(event.target.getAttribute('src'));
});
First of all your html is incorrect.Please correct your html like this
<table>
<tr>
<td> <img src=" xxx " /></td>
</tr>
<tr>
<td> <img src=" xxx " /></td>
</tr>
<tr>
<td> <img src=" xxx " /></td>
</tr>
</table>
And to get src of image clicked use this
$(function () {
$("img").click(function () {
var src = $(this).attr("src");
window.location = "yourpage.html?src=" + src;
});
});
Also you will need to include jquery library reference.
A table cell (i.e. <td>) does not have valid attributes img and src, though it could have a style attribute that contains background-image.
document.addEventListener('DOMContentLoaded', _ => {
document.addEventListener('click', event => {
if (event.target.tagName.toUpperCase() == 'TD') {
document.getElementById('imgSrc').value = event.target.style.backgroundImage.replace(/(url\(")|("\))/g, '');
}
});
});
td {
min-width: 32px;
line-height: 32px;
}
<div>Click on an image to have its src attribute set as the value of the text input below:
<table>
<tr>
<td style="background-image: url('https://www.gravatar.com/avatar/fff263875808fbce8d846947c6d56449?s=32&d=identicon')">
1
</td>
</tr>
<tr>
<td style="background-image: url('https://www.gravatar.com/avatar/616931b5c5ba8790a191fa6aea465c65?s=32&d=identicon')">
2
</td>
</tr>
<tr>
<td style="background-image: url('https://www.gravatar.com/avatar/56e1fa920ed4243286b8e62ab4fbdfef?s=32&d=identicon')">
3
</td>
</tr>
</table>
Image src:
<div><input type="text" id="imgSrc" size="80" readonly /></div>
</div>
A more common way would be to have an <img> tag with a src attribute.
To answer your "question":
tell me a way to get the src of that image when i click the image and also i want to send that src to another html page
Use JavaScript- and I recommended a technique called Event delegation. Bind an event handler for click events using with document.addEventListener() to the event DOMContentLoaded (to know when the page is loaded) and then observe clicks on the document with a single callback like in the example below. This way there is only one event listener for the whole page instead of one per image, which could lead to memory-leaks, etc. The value of the input can be submitted with a form or sent to another page (e.g. with an AJAX request).
document.addEventListener('DOMContentLoaded', _ => {
document.addEventListener('click', event => {
if (event.target.tagName.toUpperCase() == 'IMG') {
document.getElementById('imgSrc').value = event.target.src;
}
});
});
<div>Click on an image to have its src attribute set as the value of the text input below:
<table>
<tr>
<td>
1 <img src=" https://www.gravatar.com/avatar/fff263875808fbce8d846947c6d56449?s=32&d=identicon " />
</td>
</tr>
<tr>
<td>
2 <img src="https://www.gravatar.com/avatar/616931b5c5ba8790a191fa6aea465c65?s=32&d=identicon" />
</td>
</tr>
<tr>
<td>
3 <img src="https://www.gravatar.com/avatar/56e1fa920ed4243286b8e62ab4fbdfef?s=32&d=identicon" />
</td>
</tr>
</table>
Image src:
<input type="text" id="imgSrc" size="75" />
</div>
If you use a JavaScript library like jQuery, the code can be simplified, like in the example below, utilizing .ready(), .val(), etc. This article about event delegation with jQuery (using the .on() method) may also be helpful.
$(_ => {
$(document).click(event => {
if (event.target.tagName.toUpperCase() === 'IMG') {
$('#imgSrc').val(event.target.src);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<table>
<tr>
<td>
1 <img src=" https://www.gravatar.com/avatar/fff263875808fbce8d846947c6d56449?s=32&d=identicon" />
</td>
</tr>
<tr>
<td>
2 <img src="https://www.gravatar.com/avatar/616931b5c5ba8790a191fa6aea465c65?s=32&d=identicon" />
</td>
</tr>
<tr>
<td>
3 <img src="https://www.gravatar.com/avatar/56e1fa920ed4243286b8e62ab4fbdfef?s=32&d=identicon" />
</td>
</tr>
</table>
<!-- removed 1 from table1 -->
Image src:
<input type="text" id="imgSrc" size="75" />
</div>

jQuery remove row with matching file name as hidden

I have a markup like this
<table id="data">
<tr>
<td>Name</td>
<td>Test</td>
</tr>
<tr>
<td>
<input type="hidden" id="file-name" value="file.doc">
</td>
<td><input type="text" value="Test 1"></td>
</tr>
<tr>
<td>
<input type="hidden" id="file-name" value="file1.docx">
</td>
<td><input type="text" value="Test 2"></td>
</tr>
<tr>
<td>
<input type="hidden" id="file-name" value="file.pdf">
</td>
<td><input type="text" value="Test 3"></td>
</tr>
</table>
Remove File
In that markup you can see I have file name as hidden fields and under the table I have a remove file tag. So the thing is like this when I will click on the remove file then it will remove that entire row(tr tag) inside where the filename
file.doc is present. So for that I have made my js like this
<script type="text/javascript">
$(document).ready(function() {
$('#remove').click(function(e) {
var FileName = 'file.doc';
var GetRowVal = $('table#data td #file-name').val();
if(GetRowVal == FileName ) {
var Parent = $(GetRowVal).parent().remove();
}
else {
console.log(' error');
}
});
});
</script>
But it is not removing the row. So can someone kindly tell me whats the issue here? Any help and suggestions will be really apprecaible. Thanks
There are duplicate id's in your Html,just correct that issue and try below answer :
<script type="text/javascript">
$(document).ready(function() {
$('#remove').click(function(e) {
e.preventDefault();
var FileName = 'file.doc';
$('input[type="hidden"]').each(function(){
if( $(this).val() == FileName )
{
$(this).closest('tr').remove();
}
});
});
});
</script>
Following code return Array of Jquery Object.
Then function .val() cannot have meaning.
$('table#data td #file-name');
You have two probles in this code:
first : Ids are not unique.
second:
var GetRowVal = $('table#data td #file-name').val();
will hold only value eg. file.doc
so you can't later
remove the object in this line:
var Parent = $(GetRowVal).parent().remove();
so to repair it first change id to class like here:
<input type="hidden" class="file-name" value="file.doc">
and later You can modify your code:
$(document).ready(function() {
$('#remove').click(function(e) {
var GetRowVal = $(".file-name[value='file.doc']");
$(GetRowVal).parent().parent().remove();
});
});
Here jsfiddle

Why the alert message is not appearing?

I've a following HTML code:
<form name="question_issue_form" id="question_issue_form" action="question_issue.php">
<table class="trnsction_details" width="100%" cellpadding="5">
<tbody>
<tr>
<td></td>
<td>
<input type="checkbox" name = "que_issue[]" value = "Question is wrong" id ="chkQueWrong">Question is wrong</input>
</td>
</tr>
<tr>
<td></td>
<td><input type="checkbox" name = "que_issue[]" value = "Answers are wrong" id ="chkAnsWrong">Answers are wrong</input></td>
</tr>
<tr>
<td></td>
<td><input type="checkbox" name = "que_issue[]" value = "Question direction is incorrect" id ="chkDirIncorrect">Question direction is incorrecct</input></td>
</tr>
<tr>
<td></td>
<td><input type="checkbox" name = "que_issue[]" value = "Other" id ="chkOther">Other</input></td>
</tr>
<tr>
<td></td>
<td class="set_message" style="display:none;"><textarea name="que_issue_comment" rows="4" cols="25" maxlength="100"></textarea></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Submit" id="report_question_issue"></td>
</tr>
</tbody>
</table>
</form>
Following is my JS code:
$(document).on('click', '#report_question_issue', function (e) {
alert("Jumbo man");
}
And upon clicking the submit button I'm calling the alert to appear but it's not appearing. I'm not getting why this is happening? For your refrence following is link to the js Fiddle;
http://jsfiddle.net/TjK2N/
You are not including JQuery Reference. And you are missing to close );
DEMO
In your code bracket isn't closed properly at last. this is required ")" see this updated fiddle
$(document).on('click', '#report_question_issue', function (e) {
alert("Jumbo man");
});
$(document).on('click', '#report_question_issue', function (e) {
alert("Jumbo man");
}
$(XXX) this is a jquery syntax, but i saw you are in the Pure JS environment.
Should you use a js library?
The problem is with the submit action of the <form> that reload the page before the JS is called.
To avoid it, you can change it by one of following :
1st using JS into action attribute
<form name="question_issue_form" id="question_issue_form" action="javascript:alert('test')">
2nd using onsubmit attribute
<form name="question_issue_form" id="question_issue_form" onsubmit="alert('test');" action="question_issue.php">
3rd using jQuery on submit event
$('form#question_issue_form').submit(function() {
alert('test');
return false; //to avoid the reload
});
4th using jQuery on click event on the submit button
$('form#question_issue_form').click(function() {
alert('test');
return false; //to avoid the reload
});

jQuery Multiple Dynamic Forms + Foreach Loop

Okay, i'm completetly stuck. I tried every answer on here but I just can't get it to work.
My Aim: Updating dynamic forms with jQuery & AJAX
What's the problem: When clicking one of the "save" buttons it only saves the first value, I tried to do it with different ID's but as a newbie to jQuery I don't think I'm doing this right.
jQuery
$(document).ready(function() {
$("textarea").keyup(function(){
var txtArea = $('.txta').val();
var scriptString = $('.button').attr("url");
$(".button").click(function(){
$.ajax({
method: 'get',
url: '../wp-content/plugins/custom-text-editor/writefile.php',
data: {
'myString': scriptString,
'txt': txtArea,
'ajax': true
},
success: function(data) {
$('#'+myString).text(data);
return false;
}
});
});
});
});
writefile.php
$file = fopen("files/tab1.txt","w");
$txt = $_GET['txt'];
fwrite($file,$txt);
fclose($file);
echo "OK!";
Generated HTML
<table class=bordered>
<tr>
<th>Filename</th>
<th></th>
<th></th>
</tr>
<tr class=header>
<td class='plus'>+</td>
<td><p>tab1.txt</p></td>
<td><span id='ss' class='data'></span></td>
</tr>
<tr>
<td colspan="3" class="nopad">
<p><textarea cols="80" class="txta" rows="12" id="tab1.txt">asdasd</textarea>
<span id='tab1.txt' class='button' rel='qyz' url=tab1.txt>Save</span></p>
</td>
</tr>
<tr class=header>
<td class='plus'>+</td>
<td><p>tab2.txt</p></td>
<td><span id='ss' class='data'></span></td>
</tr>
<tr>
<td colspan="3" class="nopad">
<p><textarea cols="80" class="txta" rows="12" id="tab2.txt">This is file 2</textarea>
<span id='tab2.txt' class='button' rel='qyz' url=tab2.txt>Save</span></p>
</td>
</tr>
<tr class=header>
<td class='plus'>+</td>
<td><p>tab3.txt</p></td>
<td><span id='ss' class='data'></span></td>
</tr>
<tr>
<td colspan="3" class="nopad">
<p><textarea cols="80" class="txta" rows="12" id="tab3.txt">And File 3</textarea>
<span id='tab3.txt' class='button' rel='qyz' url=tab3.txt>Save</span></p>
</td>
</tr>
<tr class=header>
<td class='plus'>+</td>
<td><p>tab4.txt</p></td>
<td><span id='ss' class='data'></span></td>
</tr>
<tr>
<td colspan="3" class="nopad">
<p><textarea cols="80" class="txta" rows="12" id="tab4.txt">It works!</textarea>
<span id='tab4.txt' class='button' rel='qyz' url=tab4.txt>Save</span></p>
</td>
</tr>
</table>
This should resolve your problem:
$(document).ready(function () {
$(".button").click(function () {
var txtArea = $(this).closest('tr').find('.txta').val();
var scriptString = $(this).closest('tr').find('.button').attr("url");
$.ajax({
method: 'get',
url: '../wp-content/plugins/custom-text-editor/writefile.php',
data: {
'myString': scriptString,
'txt': txtArea,
'ajax': true
},
success: function (data) {
$('#' + myString).text(data);
return false;
}
});
});
});
How it works:
$(this) gives access to an element being clicked. Even "this" (without dollar sign and without quotes) gives such access, but it is not a jquery object, we need jquery object for further manipulations.
closest('tr') iterates the chain of parent elements until it finds an element satisfying the specified selector (in this case it searches for closest tr-element).
find('.txta') iterates the descendants (of the current element) until it finds an element satisfying the specified selector (in this case it searches for any element having "txta" class, within the tr element).
The rest of code is unchanged.
Further notes:
Event handlers within event handlers (like $("textarea").keyup(function(){ ... $(".button").click(function() { ... ) should be avoided, since the effect is: each time an outer event is handled, a new handler for the inner event is created and attached.
Think of jquery as being kind of "navigation system" over DOM-tree. With functions like "closest", "find", "next", "prev" you navigate around and get to the desired element dynamically, at runtime.
When the desired object has ID and is unique, address it with "#ID" syntax.
When the desired object is repeated (like a row/cell within the table or an element within the cell), then use css-classes and DOM-traversal functions in order to address it.
If you need more information on DOM-traversing:
http://learn.jquery.com/using-jquery-core/traversing/
http://api.jquery.com/category/traversing/

Dynamically changing ToolTipDialog content

My application has a list of indicators, each with its help button. Clicking on each button, brings up a ToolTipDialog with definition for each respectively. The way I have written the code (below), the content does not get refreshed when the user clicks on another help button within the list after having clicked the first one. I have not been able to figure out how to change the "content" dynamically. Any help will be appreciated:
HTML:
<div dojoType="dijit.layout.ContentPane" id="group1" title="Population projection" selected="true">
<table id="popIndTable">
<tr id="someID">
<td><input data-dojo-type="dijit.form.RadioButton" class="checkInd" id="checkCBR" name="checkInd" /></td>
<td id="indCBR">Crude Birth Rate</td>
<td id="infoCBR"><img id="imgCBR" src="Images/help_icon2.png" width="16px" onClick="showToolTipDialog(this,this.id);" /></td>
</tr>
<tr>
<td><input data-dojo-type="dijit.form.RadioButton" class="checkInd" id="checkTest1" name="checkInd" /></td>
<td id="indTest1">Test 1</td>
<td id="infoTest1"><img id="imgTest1" src="Images/help_icon2.png" width="16px" onClick="showToolTipDialog(this,this.id);" /></td>
</tr>
<tr>
<td><input data-dojo-type="dijit.form.RadioButton" class="checkInd" id="checkTest2" name="checkInd" /></td>
<td id="indTest2">Test 2</td>
<td id="infoTest2"><img id="imgTest2" src="Images/help_icon2.png" width="16px" onClick="showToolTipDialog(this,this.id);" /></td>
</tr>
</table>
</div>
JavaScript:
function showToolTipDialog(node,infoId){
var infoText;
var infoElem = dojo.byId(infoId).parentNode.id;
if (infoElem == "infoCBR"){
infoText = "This is the text container for CBR";
}
else if (infoElem == "infoTest1"){
infoText = "This is the text container for Test1";
}
if (!tooltipDialog) {
tooltipDialog = new dijit.TooltipDialog({
content: infoText,
style: "width:200px;height:auto;",
autofocus: !dojo.isIE, // NOTE: turning focus ON in IE causes errors when reopening the dialog
refocus: !dojo.isIE
});
dijit.popup.open({ popup: tooltipDialog, around: node});
tooltipDialog.opened_ = true;
}
else {
if (tooltipDialog.opened_) {
dijit.popup.close(tooltipDialog);
tooltipDialog.opened_ = false;
}
else {
dijit.popup.open({popup: tooltipDialog, around: node});
tooltipDialog.opened_ = true;
}
}
}
I believe the preferred way to change the value of a dojo widget programatically is to use the .set() method. ie:
this.myTooltipDialog.set("content", newContent);
Rather than:
this.myTooltip.content = newContent;
It looks like you never reset the content of your tooltipDialog. You create it once, but once it's created (new dijit.TooltipDialog({...})) it remains static.
I don't know the Dojo API. But can you just set the content value directly? Perhaps immediately after your first else:
tooltipDialog.content = infoText;
This is just a guess, but if Dojo's API is simple enough, that might do the trick.
If not, you might have to remove your if (!tooltipDialog) { check.
If your content is not too complicate, I suggestion you create a new TooltipDialog every call and clear it when blur, like
var dlgDiv = dojo.create("div");
var dlg = new dijit.TooltipDialog({
content: dlgDiv,
onBlur: function () {
popup.close(this);
this.destroyRecursive();
}
});
// you can create any content within dlgDiv at here dynamicly
dojo.popup.open({
around: yourArondNode ,
orient: ["below", "before", "after", "above"],
popup: dlg
});
dlg.focus();

Categories

Resources