I am using jquery raty plugin, there is a click event which I am using to send rating data and then return new rating from database, but I cant figure out how to update returned rating, my code:
$('.starrating').raty({
number:10,
score: function() {
return $(this).attr('data-rating');
},
click: function(score, evt) {
var contentid = $(this).attr('id');
$.post('/main/rating.php',{score:score, contentid:contentid },
function(data){
//alert(data+' Score = '+score);
$(this).data('rating',2);
});
}
});
I tried with below but no success;
$(this).data('rating',2);
Thanks for any help.
Try $(this).raty({ score: 2 }); according to raty docs
P.S. if you additionaly need to set data attribute you can try this: $(this).raty({ score: 2 }).attr('data-rating', 2);
P.P.S. Little click event update for right handling multiple elements
$('.starrating').raty({
number:10,
score: function() {
return $(this).attr('data-rating');
},
click: function(score, evt) {
var target = $(this),
contentid = target.attr('id');
$.post('/main/rating.php',{score:score, contentid:contentid },
function(data){
target
.raty({
score: data.score
})
.attr('data-rating', data.score);
});
}
});
Had some trouble with this, this worked for me:
$('.rating').raty('score', score);
Based on your comments about your parameters being reset, I've added some ideas below.
//SET RATY DEFAULTS
$.fn.raty.defaults.path = 'img';
$.fn.raty.defaults.cancel = true;
//etc
In your success function, reset the rating with the new data. Only options specified will be overridden.
$(this).raty('set', { option: value });
For example, update score
$(this).raty('set', { score: 2 });
If you are having trouble with this, try the code below (based on this answer Passing variables through to AJAX)
$.fn.raty.defaults.click= function(score, evt)
{
var target = $(this),
contentid = target.attr('id');
postvalue(score,target, contentid);
}
function postvalue (score,target, contentid)
{
$.post('/main/rating.php',{score:score, contentid:contentid },
function(data)
{
target.raty({score: data.score}).attr('data-rating', data.score);
});
}
NOTE: None of this code has been tested.
Related
In one page I have three connected dropboxes with parent child relation in this order
Company->Analysis->Scenario
I also have the pair or Node dropboxes in a html table which should be repeated in each row. These dropboxes values should be changed as the parent Scenario dropbox combo value changes.
I also want them to show the relevant value as selected for each row.
This maybe straightforward for a frontend developer but I am struggling a lot.
The top dropboxes are nearly ok. For the dropboxes from the table I managed to change the first row at one point but now lost that version :(
Can you please help me to solve this. I tried nearly everything?
Kind Regards,
Sofia
enter image description here
This is the related code part
`<script charset="utf-8" type="text/javascript">
function _updateNodes() {
var source_elms = document.querySelectorAll("[id='source1']");
for(var i = 0; i < source_elms.length; i++){
source_elms[i].setAttribute('disabled', 'disabled');
if (source_elms[i].hasChildNodes()) {
source_elms[i].empty();
}
for (node in allowed_nodes){
if node[0]==edge.source_id and node[2]== scenario_id
source_elms[i].append($('<OPTION value = node[0] selected>node[1]</option>');
endif
if node[0]!=edge.source_id and node[2]== scenario_id
source_elms[i].append($('<OPTION value = node[0]>node[1]</option>');
endif;
}
}
}
// jQuery selection for the 2 select boxes
var dropdown = {
company: $('#company'),
analysis: $('#analysis'),
scenario: $('#scenario'),
source: $('#source1'),
target: $('#target1')
};
// function to call XHR and update analysis dropdown
function updateAnalysiss() {
var send = {
company_id: dropdown.company.val()
};
dropdown.analysis.attr('disabled', 'disabled');
dropdown.scenario.attr('disabled', 'disabled');
dropdown.analysis.empty();
dropdown.scenario.empty();
$.getJSON("{{ url_for('_get_analysiss') }}", send, function(data) {
data.forEach(function(item) {
dropdown.analysis.append(
$('<option>', {
value: item[0],
text: item[1]
})
);
});
dropdown.analysis.removeAttr('disabled');
dropdown.scenario.removeAttr('disabled');
updateScenarios();
_updateNodes();
});
}
function updateScenarios() {
var send = {
analysis_id: dropdown.analysis.val()
};
dropdown.scenario.attr('disabled', 'disabled');
dropdown.scenario.empty();
$.getJSON("{{ url_for('_get_scenarios') }}", send, function(data) {
data.forEach(function(item) {
dropdown.scenario.append(
$('<option>', {
value: item[0],
text: item[1]
})
);
});
dropdown.scenario.removeAttr('disabled');
});
}
var scenario_id = Null;
function updateNodes() {
scenario_id: dropdown.scenario.val()
}
// event listener to company dropdown change
dropdown.company.on('change', function() {
updateAnalysiss();
});
// event listener to analysis dropdown change
dropdown.analysis.on('change', function() {
updateScenarios();
});
// event listener to scenario dropdown change
dropdown.scenario.on('change', function() {
alert("aa");
_updateNodes();
alert("bb");
});
$('#company').change(function() {
updateAnalysiss();
});
$('#analysis').change(function() {
updateScenarios();
});
$('#scenario').change(function() {
alert("aa1");
_updateNodes();
alert("bb1");
});
// call to update on load
updateAnalysiss();
</script>
`
I am getting an id that is not addressable by jquery ("#"+id).something .
At document start I have a :
var g_justClicked = '';
$.ajaxSetup({
beforeSend:function(event){
if(g_justClicked) {
console.log('g_justClicked='+g_justClicked+' tagName='+$('#'+g_justClicked).tagName);
};
var wOffset = $('#'+g_justClicked).offset();
$('#loading').show();
},
complete:function(){
$('#loading').hide();
}
});
At document end I have another script (all elements with class spinner should set the global variable 'g_justClicked'):
$(document).ready(function () {
$('.spinner').click(function() {
g_justClicked = $(this).attr('id');
console.log('.spinner.click: g_justClicked='+g_justClicked);
});
This works fine, the variable is set and displayed correctly in ajaxSetup.
BUT: referencing it in tagName= or in wOffset = with
$('#'+g_justClicked).
results in
"TypeError: wOffset/tagName is undefined"
Note: all ids start with several characters, t.e. "boxshow12345" is a typical id.
What am I doing wrong?
I think was able to reproduce your scenario here: https://jsfiddle.net/mrlew/qvvnjjxn/3/
The undefined in your console.log is because you're accessing an inexistent jQuery property: .tagName. This property is only available to native HTML Element.
To retrieve the tag name from a jQuery Object, you should use: .prop("tagName"), or access the property accessing the native element with $('#'+g_justClicked)[0].tagName
So, if you change
console.log('g_justClicked='+g_justClicked+' tagName='+$('#'+g_justClicked).tagName);
to:
console.log('g_justClicked='+g_justClicked+' tagName='+$('#'+g_justClicked).prop("tagName"));
Will successfully log: g_justClicked=boxshow12345 tagName=BUTTON, as expected.
Note: In order to your logic work, you have to click .spinner first.
Your problem is that your ajax setup runs regardless of whatever you do in the click handler, and it runs before you even setup that handler. The initial value for g_justClicked is empty string, and this is what it tries to access in $('#'+g_justClicked), hence the error.
If you want to click the spinner and then pass the id to the beforeSend, do it like this:
$(document).ready(function() {
$('.spinner').click(function() {
var g_justClicked = this.id; //simplify this a bit
console.log('.spinner.click: g_justClicked=' + g_justClicked);
// call ajax
_setupAjax( g_justClicked );
});
});
function _setupAjax(g_justClicked) {
$.ajaxSetup({
beforeSend: function(event) {
if (g_justClicked) {
console.log('g_justClicked=' + g_justClicked + ' tagName=' + $('#' + g_justClicked).tagName);
};
var wOffset = $('#' + g_justClicked).offset();
$('#loading').show();
},
complete: function() {
$('#loading').hide();
}
});
}
UPDATE
If you don't want a separate function, just move your ajax setup into the click handler:
$(document).ready(function() {
$('.spinner').click(function() {
var g_justClicked = this.id; //simplify this a bit
console.log('.spinner.click: g_justClicked=' + g_justClicked);
// call ajax setup
$.ajaxSetup({
beforeSend: function(event) {
if (g_justClicked) {
console.log('g_justClicked=' + g_justClicked + ' tagName=' + $('#' + g_justClicked).tagName);
};
var wOffset = $('#' + g_justClicked).offset();
$('#loading').show();
},
complete: function() {
$('#loading').hide();
}
});
});
});
OK #mrlew.
Answer: I tried your .prop appoach, but still got "undefined". Now back to the roots:
The goal is to get the id of any element that was clicked to modify the busy indicators position, while ajax is running. Newly I am back to my original approach, without global variable and parameter passing:
$(document).ready(function () {
$('.spinner').click(function() {
_setupAjax();
});
});
which works, and:
function _setupAjax() {
$.ajaxSetup({
beforeSend: function() {
$('#loading').show();
wJustClicked = $(this).attr('id'); /// <- that doesnt work!
console.log("_setupAjax wJustClicked="+wJustClicked);
console.log('_setupAjax tagName=' + $('#' + wJustClicked).prop("tagName"));
....defining css based on id (no problem)..
which yields "undefined" twice. I tried so many ways to get that f.... id.
#mrlew
thanks a lot for your help. Meanwhile I found the solution. All trouble came from a timing problem. Here is what works (for all DIV, SPAN and IMG of class=spinner and having an id:
$(document).ready(function () {
_setupAjax();
$('.spinner').click(function() {
wJustClicked = $(this).attr('id');
if(wJustClicked == null) alert('Id missing on item clicked');
console.log('.spinner.click! id='+wJustClicked);
var wOffset = $('#' + wJustClicked).offset();
var xPos = Math.round(wOffset.left) + 8;
var yPos = Math.round(wOffset.top) + 4;
console.log(wJustClicked+' offset left='+wOffset.left+' top='+wOffset.top+' xPos='+xPos+' yPos='+yPos);
wDiv = 'loading';
$('#'+wDiv).css('left',xPos);
$('#'+wDiv).css('top',yPos);
});
and the js function:
function _setupAjax() {
$.ajaxSetup({
beforeSend: function() {
$('#loading').show();
},
complete: function() {
$('#loading').hide();
}
});
}
A strange thing remained (I have firebug installed), which I have solved with Math.round: the x and y position come overdetailed like 170.5134577 and 434.8768664 ?!?
I can live with that. But where does this pseudo precision come from?
Again thanks a lot to keep my hope upright.
I generate a dropdownList dynamicly with jquery Ajax , generated dropdown's id
is specificationAttribute . I want create add event for new tag was generated (specificationAttribute) , to do this I created Belowe script in window.load:
$(document).on('change', '#specificationattribute', function () {
alert("Clicked Me !");
});
but it does not work .
I try any way more like click , live but I cant any result.
jsfiddle
Code from fiddle:
$(window).load(function () {
$("#specificationCategory").change(function () {
var selected = $(this).find(":selected");
if (selected.val().trim().length == 0) {
ShowMessage('please selecet ...', 'information');
}
else {
var categoryId = selected.val();
var url = $('#url').data('loadspecificationattributes');
$.ajax({
url: url,
data: { categoryId: categoryId, controlId: 'specificationattribute' },
type: 'POST',
success: function (data) {
$('#specificationattributes').html(data);
},
error: function (response) {
alert(response.error);
}
});
}
});
$(document).on('change', '#specificationAttribute', function () {
alert("changed ");
});
}
Your fiddle has syntax errors. Since a dropdownlist generates a select, let's use one.
For my answer I used THIS HTML, more on this later: things did not match in your code
<select id="specificationAttribute" name="specificationAttribute">
</select>
Code updated: (see inline comments, some are suggestions, some errors)
$(window).on('load', function() {
$("#specificationCategory").on('change',function() {
var selected = $(this).find(":selected");
// if there is a selection, this should have a length so use that
// old: if (selected.val().trim().length == 0) {
if (!selected.length) { // new
// NO clue what this is and not on the fiddle so commented it out
// ShowMessage('please selecet ...', 'information');
alert("select something a category");// lots of ways to do this
} else {
var categoryId = selected.val();
var url = $('#url').data('loadspecificationattributes');
$.ajax({
url: url,
data: {
categoryId: categoryId,
controlId: 'specificationattribute'
},
type: 'POST',
success: function(data) {
// THIS line id does not match my choice of specificationAttribute so I changed it
$('#specificationAttribute').html(data);
},
error: function(response) {
alert(response.error);
}
});
}
});
// THIS should work with the markup I put as an example
$(document).on('change', '#specificationAttribute', function() {
alert("changed ");
});
});// THIS line was missing parts
#Uthman, it might be the case that you have given different id to select and using wrong id in onchange event as i observed in the jsfiddle link https://jsfiddle.net/a65m11b3/4/`
success: function (data) {
$('#specificationattributes').html(data);
},and $(document).on('change', '#specificationAttribute', function () {
alert("changed ");
}); $(document).on('change', '#specificationAttribute', function () {
alert("changed ");
});.
It doesnt work because at the moment of attaching event your html element doesnt existi yet.
What you need are delegated events. Basically, you attach event to parent element + you have selector for child (usually by classname or tagname). That way event fires for existing but also for elements that meet selector added in future.
Check documentation here:
https://api.jquery.com/on/#on-events-selector-data-handler
Especially part with this example:
$( "#dataTable tbody" ).on( "click", "tr",
function() {
console.log( $( this ).text() );
});
I have a script (below) that asynchronously updates markup on setInterval; markup which is generated with jQuery from XML data. This is my attempt at creating a UI in which users can view to see changes happen to the XML data in real-time. However, this is seeming like a round about way of acheiving the desired effect compared to Web Workers API; I am finding out that my AJAX script and setInterval function are unreliable; the script appears to freeze or not respond at certain initial loads and after running for long periods of time points . How can I modify my code to use workers instead of AJAX or setInterval?
setInterval(refreshXml, 1500);
function refreshXml() {
var req = $.get('Administration/data/people.xml');
req.done(function(xml) {
// Update the global XML variable used to create buttons.
window.peopleXml = xml;
// Clear existing buttons.
$('#loadMe').empty();
// Display a button for each XML person entity.
$(xml).find('fullName').each(function(index) {
var fullName = $(this).text();
$('<button>', {
'class': 'mybutton',
value: $(this).siblings('id').text(),
text: fullName
}).appendTo('#loadMe');
});
// Update any person divs that were already visible.
$('#toadMe .person').each(function() {
// Grabs the ID from data-person-id set earlier.
var id = $(this).data('person-id');
show_person(id);
});
});
}
function show_person(id) {
$('#person-detail-' + id).remove();
get_person(id).appendTo('#toadMe');
}
function get_person(id) {
var $person = $(window.peopleXml).find('id:contains(' + id + ')').parent();
var $div = $('<div>', {
'class': 'person',
'data-person-id': id,
id: 'person-detail-' + id
});
$('<h1>', { text: $person.find('firstName').text() }).appendTo($div);
$('<h1>', { text: $person.find('lastName').text() }).appendTo($div);
$('<h1>', { text: $person.find('age').text() }).appendTo($div);
$('<h1>', { text: $person.find('hometown').text() }).appendTo($div);
$('<h1>', { text: $person.find('job').text() }).appendTo($div);
return $div;
}
$(document).on('click', '.mybutton', function() {
$('#toadMe').empty();
show_person(this.value);
});
The name of the above script is home.js and here is an example of an index page (index.html) and a worker (my_task.js):
// index.html
<script>
var myWorker = new Worker("my_task.js");
myWorker.onmessage = function (oEvent) {
console.log("Worker said : " + oEvent.data);
};
myWorker.postMessage("ali");
// my_task.js
postMessage("I\'m working before postMessage(\'ali\').");
onmessage = function (oEvent) {
postMessage("Hi " + oEvent.data);
};
How can I implement home.js in a way in which index.html and my_task.js are implemented? Thanks a ton, I am really just looking for a way to get starting using workers as the next level up since I just recently learned AJAX. Also, I know this could possibly be seen as a broad question so I am willing to improve my question upon request and suggestions.
I have an HTML table which uses jQuery DataTables (https://datatables.net/). The rows are rendered with html links to delete a row. I have used the following code to handle the click event of link, delete the row on the server and then animate deletion of the row on the front end.
$(document).on("click", ".delete-operation", function (e) {
e.preventDefault();
var oTable = $('#alloperations').dataTable();
var operationId = $(this).data('id');
// Get the parent table row and mark it as having been selected
// due to the fact rowindex does not work in order in datatables
var tableRow = $(e.toElement).parents('tr').addClass('row_selected');
bootbox.confirm("Are you sure?", function (answer) {
if (answer) {
// send request to delete operation with given id.
$.ajax({
type: 'delete',
url: "/operations/" + operationId,
success: function () {
var anSelected = fnGetSelected(oTable);
//Get all the row cells and animate a deletion
tableRow.children().animate({ backgroundColor: "red", color: "black" }, 300, function() {
tableRow.fadeOut(2000, function() {
oTable.fnDeleteRow(anSelected[0]);
});
});
},
error: function(result) {
$("#messageContainer").html(result.responseJSON.ResponseView);
}
});
return true;
}
else {
// User clicked cancel
return true;
}
});
});
QUESTION: This works perfectly in Chrome but does not work at all in Firefox, does anyone know how I would get it to work in Firefox as well?
You should use the cross browser property 'target' of event object:
var tableRow = $(e.target).parents('tr').addClass('row_selected');