Update data object with jquery - javascript

I am trying to update 'id' and 'selected' within data-options.
HTML:
<span class="re_highlight-feature" data-toggle="tooltip" data-animation="false" data-placement="top" title="" data-options="{'id':0,'name':'Appliance','value':'Dryer','selected':false}" data-original-title="Highlight Dryer">Dryer</span>
I am able to reference them and pass the correct values to my AJAX function.
JS:
$('.re_highlight-feature').click(function(e) {
e.preventDefault();
var feature = $(this);
var featureDislay = feature.text();
var featureData = feature.data('options');
feature.html('<i class="fa fa-refresh fa-spin fa-fw"></i><span class="sr-only">Loading...</span>');
$.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: {action:'highlightFeature', id:featureData.id, name:featureData.name, value:featureData.value, selected:featureData.selected},
success:function(json){
obj = JSON && JSON.parse(json) || $.parseJSON(json);
var recordID = obj.id;
if (recordID == 0){
featureData['id'] = 0;
featureData['selected'] = false;
} else {
featureData['id'] = recordID;
featureData['selected'] = true;
}
feature.html(featureDislay);
feature.toggleClass('mark');
},
error: function(errorThrown){
alert(errorThrown);
}
});
return false;
});
Everything works except this:
if (recordID == 0){
featureData['id'] = 0;
featureData['selected'] = false;
} else {
featureData['id'] = recordID;
featureData['selected'] = true;
}
I haven't been able to figure out how to update those values within my original element.

Note that properties of data-* at HTML should have properties surrounded by double quotes to set data-* attribute value as valid JSON within HTML document.
data-options='{"id":0,"name":"Appliance","value":"Dryer","selected":false}'
for ability to define a JavaScript object at
var featureData = JSON.parse(feature[0].dataset.options);
If you are trying to update the actual HTML you can use HTMLElement.dataset, JSON.stringify(), JSON.parse()
if (recordID == 0) {
featureData.id = 0;
featureData.selected = false
feature[0].dataset.options = JSON.stringify(featureData);
} else {
featureData.id = recordID;
featureData.selected = true;
feature[0].dataset.options = JSON.stringify(featureData);
}
Inspecting .re_highlight-feature at DevTools or Developer Tools reveals that the data-* attribute is updated at the HTML document.
var feature = document.querySelector(".re_highlight-feature");
var featureData = JSON.parse(feature.dataset.options);
console.log(featureData);
featureData.id = 1;
featureData.selected = true
feature.dataset.options = JSON.stringify(featureData);
console.log(JSON.parse(feature.dataset.options));
console.log(feature.outerHTML);
<span class="re_highlight-feature" data-toggle="tooltip" data-animation="false" data-placement="top" title="" data-options='{"id":0,"name":"Appliance","value":"Dryer","selected":false}' data-original-title="Highlight Dryer">Dryer</span>

Your code is updating the data object created with the reference of the element.
Updates are made to the object and not the actual element.
To update the element attributes use following code after you set values in featureData.
feature.attr("data-options",JSON.stringify(featureData));

Related

How can I pass an object from my view to my controller in ASP.NET MVC?

I want to download an Excel file when the user clicks on an Excel button. This is my Model and Object:
List<VMStockScreenerModel> listofStockScreener = (List<VMStockScreenerModel>)TempData["StockScreener"];
TempData["StockScreener"] = listofStockScreener;
This is the Excel button in my view:
<div class="col-md-1 padding-fx text-left" id="btn_FilterStocks">
<span onclick="DownloadFilterStocks(#listofStockScreener.ToList());" class="pull-right icon-merge" data-toggle="tooltip" title="Download">
<i class="fa fa-file-excel-o"></i>
<i class="fa fa-cloud-download"></i>
</span>
</div>
And here is my OnClick handler:
function DownloadFilterStocks() {
debugger;
var Obj = [#listofStockScreener];
Obj = JSON.stringify({ 'Obj': Obj });
var urls = '#(Html.Raw(Url.Action("Download_StockScreener","Home", new { Obj = "_Obj_"},Request.Url.Scheme)))'.replace("_Obj_", Obj);
}
Controller Code
public FileResult Download_StockScreener(VMStockScreenerModel Obj)
{
try
{
string fileName = string.Empty;
string filePath = string.Empty;
string fileName_filePath = string.Empty;
fileName_filePath = StockScreener_DownloadExcel(Obj);
if (fileName_filePath.Contains("#"))
{
filePath = fileName_filePath.Split('#')[0];
fileName = fileName_filePath.Split('#')[1];
}
if (fileName != "")
{
//return File(filePath, "text/csv", fileName);
}
else
{
return null;
}
}
catch (Exception ex)
{
Log.Logging("HomeController => Download_StockScreener", ex.Message + "\n" + ex.StackTrace);
} return null;
}
Instead of writing the whole code for you, i hope i can guide you to the answer by suggesting you the steps you need to take for making your solution work:
Instead of span, make the element an anchor a.
Render the anchor's URL server side (MVC view) without the query string part. Example: Export
In the anchor's click event, do the following:
function DownloadFilterStocks(elem) {
debugger;
var Obj = [#listofStockScreener];
var $elem = $(elem);
//this converts JS object to query string
var qParams = $.param(Obj);
//append query string to the anchor's base url
var newUrl = $elem.attr('href') + '?' + qParams;
//assign new url
$elem.attr('href', newUrl);
}
The way this will work is:
When the export link is clicked, JS code will be executed before server-side execution.
JS will update the URL/href with the query string
Server-side code will be executed with the new URL
Hope that helps you out. I ended up writing few codes anyway.
Note: My answer assumes that your server-side code is a working code.

JQuery using object literal can't using $(this) always undefine on onclick

my problem after write as object literal as Jquery guide i can't using $(this) to access self on onlick="". please help correct my mistake.
my html
<a
data-id="<?=$product_id?>"
class="compare product-<?=$product_id?>"
onclick="(function(){compareInit.comGet();})()"
></a>
my js
var compareInit = {
/* Store Item Compare */
comGet: function() {
var e = $(this);
var item_id = e.data('id');
var item_image = e.find(".compare-hidden-image").val();
var item_name = e.find(".compare-hidden-name").val();
var count_item = $(".compare-item").length;
var item_dialog = $(".compare-tray-dialog");
var compare_button = $(".compare-tray-item");
item_dialog.show();
if (count_item > 1) {
} else {
$(".product-"+ item_id).css("color", "red").attr('onclick','');
}
if (count_item === 0) {
compare_button.removeClass('activate').addClass('deactivate');
} else {
compare_button.removeClass('deactivate').addClass('activate');
}
$('.compare-remove').on("click", function() {
var rem_id = $(this).data('id');
$("." + rem_id).remove();
$(".product-" + rem_id).css("color", "#fff").attr('onclick','(function(){compareInit.comGet();})()');
compare_button.removeClass('activate').addClass('deactivate');
});
}
};
Thank in advance.
You can pass the this identifier from the onclick event and then access it under a name other than this such as elem as a parameter of your function.
var compareInit = {
/* Store Item Compare */
comGet: function(elem) {
console.log("working");
var e = $(elem);
var item_id = e.data('id');
var item_image = e.find(".compare-hidden-image").val();
var item_name = e.find(".compare-hidden-name").val();
var count_item = $(".compare-item").length;
var item_dialog = $(".compare-tray-dialog");
var compare_button = $(".compare-tray-item");
item_dialog.show();
if (count_item > 1) {} else {
$(".product-" + item_id).css("color", "red").attr('onclick', '');
}
if (count_item === 0) {
compare_button.removeClass('activate').addClass('deactivate');
} else {
compare_button.removeClass('deactivate').addClass('activate');
}
$('.compare-remove').on("click", function() {
var rem_id = $(this).data('id');
$("." + rem_id).remove();
$(".product-" + rem_id).css("color", "#fff").attr('onclick', '(function(){compareInit.comGet();})()');
compare_button.removeClass('activate').addClass('deactivate');
});
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a data-id="3636" class="compare product-3636" onclick="compareInit.comGet(this)">Testing</a>
You need to pass-on the your required DOM element's this reference as follows:
onclick="(function(){compareInit.comGet();})()"; here you are invoking an anonymous function without passing anything to it. So there inside it this reference means that anonymous function itself. To achieve your goal you need to pass DOM reference as follows:
var compareInit = {
/* Store Item Compare */
comGet: function(thisRef) {
alert($(thisRef).text());
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="mydiv" onclick="(function(thisRef){compareInit.comGet(thisRef);})(this)">Click Me!</div>
Try this: apply the this inside the onclick function .If you apply this in object function its get the data from that object only
var compareInit ={
comGet : function(that){
console.log(that.innerHTML)
}
}
<a onclick="compareInit.comGet(this)">hello</a>
Alternate:
If get the this from whole object try with return like below .its like a jquery object $(element).html()
var compareInit = function(that){
return {
comGet : function(){
console.log(that.innerHTML)
}
}
}
<a onclick="compareInit(this).comGet()">hello</a>

HTML Object is shown as undefined in Javascript when using ContentPlaceHolder

I have a COM Object whose methods i can call in a HTML page using the code .But when i use the same code in an aspx page with a Master Page and keep the object in ContentPlaceHolder tag i get the error MyObject is undefined
My Javascript is:
function setText()
{
txtIdCardNo.value = MyObject.getIdCard;
if (MyObject.getIdType() == "R") {
rdbCardType2.checked = true;
}
else {
rdbCardType.checked = true;
}
txtCardExpiryDate.value = MyObject.getCardexpirydate();
txtNameEnglish.value = MyObject.getNameEnglish();
txtNameArabic.value = MyObject.getNameArabic();
if (MyObject.getGender() == "M") {
rdbMale.checked = true;
} else {
rdbFemale.checked = true;
}
TxtDob.value = MyObject.getDob();
txtNationality.value = MyObject.getNationality();
txtSponsorName.value = MyObject.getSponsorEng();
txtSponsorNameArabic.value = MyObject.getSponsorArb();
txtBirthPlace.value=MyObject.getBirthPlace();
txtPassportExpiry.value = MyObject.getPassport();
txtPassportNo.value = MyObject.getPassportexp();
txtSmartCardId.value = MyObject.getSmartCard();
txtSamCardId.value = MyObject.getSAMCard();
}
My Html Object is
<object id="MyObject" name="MyObject"
classid="clsid:37123a95-5afb-4f68-b95b-b735c505d8d9"></object>
This is not a solution to the problem but an alternate route that is by using ActiveXObject we can access the COM Object in our javascript ,in which case we dont have to use HTML Object

How could I call a JQuery function upon a button click?

I have a JQuery function that fetches and displays a page worth of images through the use of JSON files. I want to display the next set of images upon a button click, but that requires adding on a short string to the request url, which is found and stored in a var when I first run the script. I need to call this JQuery function again and pass the string var to it (lastId in code below). I am an utter noob with JavaScript in general and don't know how to go about doing that.
Here is a full version of the code:
$(function runthis(un){
var lastId;
un = typeof un !== 'undefined' ? un : "";
$('#domainform').on('submit', function(event){
event.preventDefault();
$('#content').html('<center><img src="img/loader.gif" alt="loading..."></center>');
//var lastId;
var domain = $('#s').val();
var newdomain = domain.replace(/\//g, ''); // remove all slashes
var requrl = "http://www.reddit.com/r/";
var getmore;
getmore = "?after=t3_"+un;
var fullurlll = requrl + domain + ".json" + getmore;
$.getJSON(fullurlll, function(json){
var listing = json.data.children;
var html = '<ul class="linklist">\n';
for(var i=0, l=listing.length; i<20; i++) {
var obj = listing[i].data;
var votes = obj.score;
var title = obj.title;
var subtime = obj.created_utc;
var thumb = obj.thumbnail;
var subrdt = "/r/"+obj.subreddit;
var redditurl = "http://www.reddit.com"+obj.permalink;
var subrdturl = "http://www.reddit.com/r/"+obj.subreddit+"/";
var exturl = obj.url;
var imgr = exturl;
var imgrlnk = imgr.replace("target=%22_blank%22","");
var length = 14;
var myString = imgrlnk;
var mycon = imgrlnk;
var end = mycon.substring(0,14);
myString.slice(-4);
var test1 = myString.charAt(0);
var test2 = myString.charAt(1);
var timeago = timeSince(subtime);
if(obj.thumbnail === 'default' || obj.thumbnail === 'nsfw' || obj.thumbnail === '')
thumb = 'img/default-thumb.png';
if(end == "http://i.imgur" ){
$("#MyEdit").html(exturl);
html += '<li class="clearfix">\n';
html += '<img src="'+imgrlnk+'" style="max-width:100%; max-height:750px;">\n';
html += '</li>\n';
html += '<div class="linkdetails"><h2>'+title+'</h2>\n';
/*html += '<p class="subrdt">posted to '+subrdt+' '+timeago+'</p>'; /*'+test1+test2+'*/
html += '</div></li>\n';
}
if (listing && listing.length > 0) {
lastId = listing[listing.length - 1].data.id;
} else {
lastId = undefined;
}
} // end for{} loop
htmlOutput(html);
}); // end getJSON()
}); // end .on(submit) listener
function htmlOutput(html) {
html += '</ul>';
$('#content').html(html);
}
});
The way you currently are executing the function run this doesn't ever leave you a handle to that function. This means it only really exists in the context of document.ready (what $(function()) is a shortcut for).
What you want to do instead is to keep a reference to this function for later use.
If you want to be able to put it directly into an onclick='' you will need to put the function in global,
eg:
var myFunction = function() { /*Stuff here*/}
$(myFunction)
this declares a function called myFunction and then tells jQuery to execute it on document ready
Global is generally considered pretty naughty to edit. One slightly better option would be to assign the click to the button inside your javascript
eg:
$(function(){
var myFunction = function() { /*Stuff here*/}
myFunction(); //call it here
$('#my-button-id').click(myFunction);//attach a click event to the button
)
This means that the function myFunction only exists in the scope of your document.ready, not in global scope (and you don't need onclick='' at all)
tTo add listener on some event you can use live('click',function(){}) Like yhis:
<div id="my-button">some content</div>
<script type="text/javascript">
$('#my-button').live('click',function(){
//your code
})
</script>

How can I consolidate duplicated javascript functions?

I have a site to allow someone to place food orders. Images of potential ingredients (determined by a MySQL query) can be clicked to add or remove them, and the image will toggle on each click.
The problem I'm having is for each new item I am having to duplicate the function and just change the variable names for each new function. I'm sure there must be a way to simplify to dynamically apply to all of the ingredients without all of the redundant code.
Here is the code just for two. There are dozens. Any suggestions would be appreciated.
window.onload = function () {
var ProductElement = document.getElementById('Ketchup');
if (ProductElement != null) {
Ketchupobj = document.getElementById('Ketchup')
document.getElementById('Ketchuptogg').onclick = function () {
Ketchuptoggle();
}
}
var ProductElement = document.getElementById('Mustard');
if (ProductElement != null) {
Mustardobj = document.getElementById('Mustard')
document.getElementById('Mustardtogg').onclick = function () {
Mustardtoggle();
}
}
}
function Ketchuptoggle() {
if (Ketchuptggle == 'on') {
Ketchupobj.src = "Ketchup.jpg";
Ketchuptggle = 'off';
} else {
Ketchupobj.src = "noKetchup.jpg";
Ketchuptggle = 'on';
}
}
function Mustardtoggle() {
if (Mustardtggle == 'on') {
Mustardobj.src = "Mustard.jpg";
Mustardtggle = 'off';
} else {
Mustardobj.src = "noMustard.jpg";
Mustardtggle = 'on';
}
}
<table class="ing">
<tr>
<?php
for ($x=0; $x<5 AND $row = mysql_fetch_row($result);$x++ ) {
$caps=$row[1];
$caps=strtoupper($caps);
echo <<<image
<td><b>$caps</b><br>
<a id="$row[0]" class="toggle" href="#"><img id="$row[0]img" class="toggimg"
src="$row[0].jpg" style="border-style: none" alt=""/></a>
</td>
image;
}
echo"</tr></table>";
Implicit this is your friend:
var toggles = document.getElementsByClassName('toggle');
for (var i=0; i<toggles.length; i++) {
toggles[i].isOn = true;
toggles[i].onclick = function(ev){
var condiment = this.id;
this.isOn = !this.isOn;
document.getElementById(condiment+'img').src=(this.isOn?'':'no')+condiment+'.png';
};
}
With html you have the ability to add your property for an element, so you could do:
<button class="btnProduct" data-type="mostard"> Mostard</button>
<button class="btnProduct" data-type="ketchup"> Ketchup</button>
<button class="btnProduct" data-type="barbecue"> Barbecue</button>
Then with a help of jquery you can do:
$('btnProduct').click(function(){
//So, here you could use a switch or some logic
// to do different things for data-type
console.log($(this).attr('data-type'))
}

Categories