jQuery change image src based on data attribute - javascript

I have a list of dynamically generated divs all with unique data-id's and several image icons contained within. When an Icon is clicked a box pops up allowing a selection dependent on the action chosen. This updates the database via ajax.
I need the first icon to change when the ajax reauest returns 3.
var ls="<div class='list_body'>
<div class='lister1'>
<img src='"+path+stat1+"' data-icon_no='1' data-status='"+split_stats[0]+"' data-job_id='"+split_stats[18]+"' />
<img src='"+path+stat2+"' data-icon_no='2' data-status='"+split_stats[1]+"' data-job_id='"+split_stats[18]+"' />
<img src='"+path+stat3+"' data-icon_no='3' data-status='"+split_stats[2]+"' data-job_id='"+split_stats[18]+"' />
<img src='"+path+stat4+"' data-icon_no='4' data-status='"+split_stats[3]+"' data-job_id='"+split_stats[18]+"' />
<img src='"+path+stat5+"' data-icon_no='5' data-status='"+split_stats[4]+"' data-job_id='"+split_stats[18]+"' />
<img src='"+path+stat6+"' data-icon_no='6' data-status='"+split_stats[5]+"' data-job_id='"+split_stats[18]+"' />
</div>
<div class='lister'>"+split_stats[6]+" "+split_stats[7]+" "+split_stats[8]+"<br />["+split_stats[13]+"]"+"</div>
<div class='lister'>"+split_stats[14]+"</div>
<div class='lister'><a href='javascript:void(0);' class='lister_a'>View Appointment & Actions</a></div>
</div>";
(I have tried to space the code to make it more readable but basically this is just one line of many that is appended to the document)
My jQuery so far is...
$(document).on('click', '.submit_acc', function(){
var selected=$('.conf_app').val();
var agent=$('body').data('agent_id');
if(selected==0)
{
alert("Please make a selection from the available options.");
return;
}
var reason=$('.ag_com').val();
var data="agent_id="+agent+"&selected="+selected+"&reason="+reason+"&job_id="+gl_job_id;
alert(data);
$.ajax({
type:"POST",
url:"admin_includes/conf_job.php",
data:data,
context:gl_job_id,
success:function(html){
if(html=="3")
{
//this is where I can't get it to work......
$('.lister1[data-job_id="'+gl_job_id+'"'').find('img').eq(0).src("images/icons/start_green.png");
}
}
})//end ajax
});
I am baiscally having trouble identifying the row where to change the image.
gl_job_id is a global variable that holds the job_id which is used as the identifier in data-job_id (does that make sense ??)..
Currently this is throwing an error on the selector line but obviously the syntax is totally wrong :(

Wrong selector here:
$('.lister1[data-job_id="'+gl_job_id+'"'').find('img').eq(0).src("images/icons/start_green.png");
you trying to select div by data-job_id, also remove one ' and add ]
Something like this must be:
$('.lister1 [data-job_id="'+gl_job_id+'"]').attr('src', "images/icons/start_green.png");
this code select div, then find by data-job_id and set src attribute

Related

Using other attribute instead of id in html and javascript

I am making a project of a chat app, I made a code that if the user is not your user it will be in the left side, and if the user is your user it will be on the right side, the code I do works, but there is a single error. The problem is that I do this:
html
<div class="msg right-msg" id="side">
<div class="msg-img" style="background-image: url(https://image.flaticon.com/icons/svg/145/145867.svg)"></div>
<div class="msg-bubble">
<div class="msg-info">
<div class="msg-info-name">{{ chat.user }}</div>
<div class="msg-info-time"></div>
</div>
<div class="msg-text">{{ chat.message }}</div>
</div>
</div>
javascript
$( "#side" ).each(function() {
//console.log( index + ": " + $( this ));
var users = $(".msg-info-name").text()
if (users != me) {
$("#side").removeClass("msg right-msg");
$("#side").addClass("msg left-msg");
};
});
The problem is that there are many of the same html code(That has the same id, class, etc..), So I realized that I can use id in only one, I use id and this was the product Image of the product, it only change the place in the first one, So that doesn´t work.
So I try using class but instead of changing the first one side it change nothing, so class doesn´t works. What can I do?, is another way to loop into all of this, ALSO, the javascript example is using id's. thank for the help
use class not id for multiple elements.
$( ".msg" ).each(function() {
var users = $(this).find(".msg-info-name").text();
if (users != me) {
$(this).removeClass("msg right-msg");
$(this).addClass("msg left-msg");
};
});

How to preview dynamically uploaded images before upload?

I am trying to understand why I can't preview multiple images that are in different divs.
I am appending a new div that includes a new input for a file upload, sort of a section for a set of instructions, each has it's own image.
When I try uploading, the preview only works for the first div, not the rest. I thought the on event handler would work, but it does not.
$('.instructions__add-new').on('click', function() {
$('.instructions__append-inputs').append('<div class="instructions__container"><img id="instructionsImg" src=""><input type="file" class="instructions__image-input" name="recipe_instructions_image[]" onchange="document.getElementById("instructionsImg").src = window.URL.createObjectURL(this.files[0])"></div><div class="instructions__append-inputs"></div>');
});
#instructionsImg {
width: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="instructions__container">
<img id="instructionsImg" src="">
<input type="file" class="instructions__image-input" name="recipe_instructions_image[]" onchange="document.getElementById('instructionsImg').src = window.URL.createObjectURL(this.files[0])">
</div>
<div class="instructions__append-inputs"></div>
<div class="instructions__add-new">+ New Instruction</div>
If you make a small change, it will work. Instead of find it using previousSibling selector in javascript.
https://jsfiddle.net/e4wez2d1/1/
$('.instructions__add-new').on('click', function() {
$('.instructions__append-inputs').append('<div class="instructions__container"><img id="instructionsImg" src=""><input type="file" class="instructions__image-input" name="recipe_instructions_image[]" onchange="this.previousSibling.src = window.URL.createObjectURL(this.files[0])"></div><div class="instructions__append-inputs"></div>');
});
In your JQuery script, check your quotes in your string.
onchange = " document ( " quote error " ) "
Use antislash quotes. Like \"
From your code, i think you should use the event of jquery for input changing.
$('input.instructions__image-input').on('change',function(){
var divParent = $(this).closest("div.instructions__container");
$("#instructionsImg",divParent).attr("src",window.URL.createObjectURL(this.files[0])) ;
});

My function dont work, Ajax call,JQuery, calling outside ? I dont know

if you want to understand my problem, please read every step of that shitty code that make me angry :
The context of all of this is an API, so I have to do an ajax call to an external JSon file. The call works : I get the response, and I can manage data like I wanna.
jQuery(function($) {
$.ajax({
url: 'http://MY JSON URL/',
contentType: "application/json; charset=windows-1252",
dataType: "json",
success: function(content) {
var api = content.contents.response // Dont care about this, it work.
var AnyDataFromJsonIWantToGet = api.data // Dont care about this, it work.
$('#myAPI').html("Some HTML content, syntax checked" +
$('#mainbuy').html()
+ "Some HTML content, syntax checked");
},
/* Error */
error: function(xhr, status, error){
alert("No Json" + xhr.status);
},
});
As you can see, I call $('#mainbuy').html() in $('#myAPI').html(). My problem is in $('#mainbuy').html() but occur only when called in $('#myAPI').html(). Here is the main page HTML code for $('#mainbuy').html(), I keep all my <div class> and others <div> cause maybe you will find the source of my problem in it, but you will see later why I think its absolutely not about my CSS tricks.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainbuy" style="display:none;">
<div class="coachbtn"><div class="dropup"><div id="buybtn">
<select class="selectpicker" data-style="btn-primary" id="pickhour" name="pickhour">
<option value="1">1H</option>
<option value="2" selected>2H</option>
<option value="3">3H</option>
<option value="4">4H</option>
</select>
</div></div></div>
<div class="coachbtn2"><div id="buybtn2">
<a id="egglink" class="button button-large" style="width: 260px">Reserver</a>
</div></div>
<script type="text/javascript">
$(document).ready(function(){
$('#pickhour').change(function(){
pickhour1 = $(this).val();
$("#egglink").attr("href", "http://my-link/" + pickhour1 + "/end/of/my/link/");
});
});
</script>
</div>
So, in this :
-A dropdown select-box : ID "pickhour"
-A button (<a></a> with style) : ID "egglink"
My script used to get the .val() of selected value in my select-box, and put it in a link which is .attr() href to my button.
The problematic :
If I show the select box + the button + the script in my main page without calling it elsewhere : It works fine !
If I want to show <div id="mainbuy" style="display:none;"> with $('#mainbuy').html() in $('#myAPI').html() : The result is showing every elements like it should but the script dont work, no HREF on my button.
I dont know if it is important but I use Fancybox to open $('#myAPI').html() :
<div id="openAPI" style="display:none;width:auto;height:auto;">
<div id ='myAPI'>
</div></div>
<a class="hover-wrap fancybox-media" data-fancybox-group="video" title=" " href="#openAPI">
Im not really smart with JavaScript and actually Im lost in this, it seem to be easy and working, but its not.. :(
Thanks you for readind, I hope someone here can help me.
Maybe your DOM is not updated (cause your AJAX request), try this :
$('#buybtn2').on('change' , '#pickhour' , function(){
pickhour1 = $(this).val();
$("#egglink").attr("href", "http://my-link/" + pickhour1 + "/end/of/my/link/");
});
I don't know if that work..
Sorry in advance for my bad english.
it's not "#buybtn2" but "#buybtn" sorry for that.
Actually, you try to change href attribute, but this button doesn't have any href attribute. Maybe it's that your problem.
try to add a href at your button :
<div class="coachbtn2">
<div id="buybtn2">
<a id="egglink" class="button button-large" href="" style="width: 260px">Reserver</a>
</div>
</div>
For the newest versions of jquery attr refers to the originally html. So changing it won't update the DOM. Try using prop instead.
$('#buybtn2').on('change' , '#pickhour' , function(){
pickhour1 = $(this).val();
$("#egglink").prop("href", "http://my-link/" + pickhour1 + "/end/of/my/link/");
});

Unable to Clone HTML & Values into jQuery Datatables 1.10

This question has been asked on a few occasions, for example:
Store Cloned Element in Variable
Copy DOM Element
However, I'm having issues selecting say <div id="XYZ"></div> and cloning it to a variable for the jQuery DataTable fnStateSaveParams to save. When the page refreshes it is then meant to reload the cloned object back into the HTML via fnStateLoadParams. I am trying to use .clone() over .html() because I also need the values stored within the dynamically generated textboxes.
If I'm not saving and loading via the Datatables plugin, then it works perfectly. As soon as I try calling code similar to the below then it ceases to work (please bare in mind I've tried a number of variations to the below code). Has anyone got any ideas or suggestions?
"fnStateSaveParams": function (oSettings, oData) {
var clonedHtml= $("#XYZ").clone(true);
oData.storedHtml = clonedHtml;
},
"fnStateLoadParams": function (oSettings, oData) {
//$("#displayHtml").append(oData.storedHtml);
//$("#displayHtml").html(oData.storedHtml);
//$(oData.storedHtml).prependTo("#displayHtml")
}
<div id="XYZ">
<div data-template="">
<label class="bolder"></label>
<div class="input-append">
<div class="inline-block advancedSearchItem">
<input type="text" id="test1" value="Test Scenario" />
</div>
<a href="#" data-id="" class="btn btn-small btn-danger removeField">
<div class="hidden-phone">Remove</div>
<i class="icon-trash icon-only hidden-tablet hidden-desktop"></i>
</a>
</div>
</div>
</div>
The end scenario will be more complex, however the above is the simplest form of what I am trying to create. If you need more information, feel free to ask and I'll update the question accordingly.
I didn't find a way of utilising .clone() to grab all HTML and Text Box values. However, I did come up with a solution and the code below is for anyone who needs a reference point.
Using .html() (as most will know) will only copy the available HTML and ignore what is essentially 'placeholder' text within text fields. My solution though is to force the value into the HTML rather than being treated as 'placeholder' text, this allows it to be used again when the page is loaded.
$(document).on("click", "#advancedSearchButton", function(event) {
event.preventDefault();
// DO SOME STUFF HERE
$("[data-value]").each(function(index) {
if (index > 0) {
fieldCount++;
$(this).attr("value", $(this).val());
}
});
oTable.fnFilter("");
});
function loadData() {
// ... ... ...
"fnStateSaveParams": function(oSettings, oData) {
oData.advancedSearchHtml = $("#addedSearchFields").html();
oData.fieldCount = fieldCount;
oData.isAdvancedSearch = isAdvancedSearch;
},
"fnStateLoadParams": function(oSettings, oData) {
$("#addedSearchFields").html(oData.advancedSearchHtml);
if (oData.isAdvancedSearch == true) {
$("#collapseElement").removeClass("collapsed");
$("#collapseIcon").removeClass().addClass("icon-chevron-up");
$("#filter").hide();
}
isAdvancedSearch = oData.isAdvancedSearch;
advancedSearchFields = oData.fieldCount;
}
// ... ... ...
}

JQuery Ajax call stop refresing the page

I have the following html code:
<div>
<form id="ChartsForm">
<div id="optionsheader">
<p>Choose your page:</p>
<div id="dateoptions">
<p>Until date: <input type="date" name="until_date" value="Until date"></p>
<p>Since date: <input type="date" name="since_date" value="Since date"></p>
</div>
</div>
<select name="accmenu" id="accmenu" style="width:300px; float:left; clear:both;">
<?php
$user_accounts = $facebook->api('/me/accounts','GET');
foreach($user_accounts['data'] as $account) {
?>
<option data-description="<?php echo $account['category'] ?>" data-image="https://graph.facebook.com/<?php echo $account['id']; ?>/picture" value="<?php echo $account['id'] ?>"><?php echo $account['name'] ?></options>
<?php
}
?>
</select>
<div class="insightsoptions">
<p>Choose your insights:</p>
<input id="newLikes" class="insightsbuttons" type="submit" name="submit" value="Daily new likes">
<input id="unlikes" class="insightsbuttons" type="submit" name="submit" value="Daily unlikes">
</div>
<div class="insightsgraphs">
<div id="dailyNewLikes"></div>
<div id="dailyUnlikes"></div>
</div>
</form>
</div>
which has a form with the id=ChartForm that contain two date inputs until_date and since_date, one select accmenu and two submit inputs with the values Daily new likes and Daily unlikes. I use the following Jquery function:
$(function () {
$('#accmenu').change(function() {
$(".insightsgraphs div").hide();
$(".insightsoptions input").attr("class","insightsbuttons");
});
$("#newLikes").one('click', function () {
$.ajax({type:'GET', url: 'newLikes.php', data:$('#ChartsForm').serialize(), success:
function(response) {
var json = response.replace(/"/g,'');
json = "[" + json + "]";
json = json.replace(/'/g,'"');
var myData = JSON.parse(json);
var myChart = new JSChart('dailyNewLikes', 'line');
myChart.setDataArray(myData);
myChart.setSize(960, 320);
myChart.setAxisNameX('');
myChart.setAxisValuesColorX('#FFFFFF');
myChart.setAxisNameY('');
myChart.setTitle('Daily New Likes');
myChart.draw();
}});
return false;
});
$("#newLikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyNewLikes').toggle();
});
$("#unlikes").one('click', function () {
$.ajax({type:'GET', url: 'unlikes.php', data:$('#ChartsForm').serialize(), success:
function(response) {
alert(response);
$("#dailyUnlikes").html(response);
}});
return false;
});
$("#unlikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyUnlikes').toggle();
});
});
for the application flow in the following manner: every time I click on one of the input submit buttons the script will make only one Ajax GET request to a specific php file that send me back a response with which I create a Chart in a hidden div with the id=dailyNewLikes or id=dailyUnlikes by case (for testing purposes I work for the moment only on the first button). The button it will change his background color into green and the div it will be shown. I use $("#newLikes").on('click', function(){ for change back and forth the background color and the display time of the div. (from green and display:block to red and display:none, you get the point I hope :D). Also I use $('#accmenu').change(function() { to change all buttons to red and hide the respective div in case an option from the select is changed. My problem is that after I refresh the page (Ctrl+R) choose since and until date, click on the first button (it change to green and the div is shown, also the toggle is working fine) and then click on the second button which works fine on the first click (is becoming green and div is shown) but on the second click I have an issue: the script is making another Ajax GET request (a wrong URL one) and the page is refreshed. Ex. of a good reguest URL:
http://localhost/smd/unlikes.php?until_date=2013-05-01&since_date=2013-04-01&accmenu=497232410336701
and an ex. of a wrong request URL:
http://localhost/smd/?until_date=2013-05-01&since_date=2013-04-01&accmenu=497232410336701&submit=Daily+unlikes#_=_
Like it can be seen (it doesn't need in the first to make this extra request) the php file is not present and also a new submit parameters is added. This also happen if I change from the select with another option. What am I do wrong? I really need to know, not just to have my code "fixed". It bugging me for a little while. Any feedback is more than welcomed. P.S. Also, how can I start the .one function only if both date inputs has been choosen? Something like how could help me?
var until = $('#dateoptions input[name="until_date"]').val();
var since = $('#dateoptions input[name="since_date"]').val();
if (until == "" || since == "") {
alert('Until date or Since date missing!');
return;
}
it will work that way? Sorry for the long question...
i think you should make your question a little shorter and just point what you need and what errors are you getting ..anyways...going through your code i see you have two click event for same button at the end for $("#unlikes").one and $("#unlikes").on(..and no return false in other function.
try adding return false
$("#newLikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyNewLikes').toggle();
return false;
});
$("#unlikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyUnlikes').toggle();
return false;
});
my guess is that , since you have two click event..when it gets clicked ..these event will fire and since you are missing return false in second click function...the form gets submitted hence refreshing the form.
however its better if put your codes in single click function than creating two seperate click event.

Categories

Resources