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>
`
Related
I save some data in my MYSQL database, after saving I wan't to show a text in my div with id #msg. Can somebody help me.
<script>
$(document).ready(function () {
$("#btnAdd").click(function (e) {
/* Retrieving value from textboxes */
var besproken = $('#besproken').val();
var afspraken = $('#afspraken').val();
var coachings_id = $('#coachings_id').val();
var verlengen = $('#verlengen').val();
$.post("save_coaching.php", {
besproken: besproken,
afspraken: afspraken,
coachings_id: coachings_id,
verlengen: verlengen
}, function (data) {
$("form")[0].reset();
});
return false;
});
});
</script>
Just use the .html( ) method on your #msg div:
$.post("save_coaching.php", {
besproken: besproken,
afspraken: afspraken,
coachings_id: coachings_id,
verlengen: verlengen
}, function (data) {
$( "#msg" ).html( data );
$("form")[0].reset();
});
This is assuming the data variable is a simple string. If it's JSON you'll want to use JSON.parse( data ) to convert it back to an object, and then print out the properties you need.
You have few options todo this, for example You can control visibility by CSS.
$.post("save_coaching.php", {
besproken: besproken,
afspraken: afspraken,
coachings_id: coachings_id,
verlengen: verlengen
}, function (data) {
// place code here to manipulate showing the notification div
});
For manipulate code, You can write:
document.getElementById('#msg').style.visibility = 'visible' or 'hidden'
visible or hidden is depend on what You want todo with your #msg element.
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 got an asp.net mvc project, but actually most of functions i achieved via javascript, below screenshot is the part which makes me frustrating, here you can see i use a date picker to define time slot then filter content for next dropdown button with related contents.
$('.input-daterange').datepicker({
format: "yyyymm",
minViewMode: 1,
language: "zh-CN",
beforeShowMonth: function (date) {
switch (date.getMonth()) {
case 0:
return false;
case 1:
return false;
case 2:
return false;
case 3:
return false;
case 4:
return false;
}
}
}).on('changeDate', function (e) {
var from = $('#from-date').val();
var to = $('#to-date').val();
if (from !== to) {
$.ajax({
type: "GET",
url: "DataChanged?fromDate=" + $('#from-date').val() + "&toDate=" + $('#to-date').val(),
dataType: "json"
})
.done(function (data) {
//var legth = data.chart.length;
$('#brandtable').empty();
var contents = $.parseJSON(data);
$.each(contents, function (key, values) {
$.each(values, function (k, v) {
$('#brandtable').append("<td><button class='btn btn-default' id=" + v.ID + ">" + v.BrandName + "</button></td>");
if (k % 9 === 0) {
if (k !==0) {
$('#brandtable').append("<tr></tr>");
}
}
});
});
});
};
});
});
Ok now, everything is fine, content was added successfully with button tag, but now i want click on button to get data from server just like above action, it is very strange that click event doesn't work, i don't know why? i did it in this way,
#foreach (var item in Model)
{
<text>
$("##item.ID").click(function () {
$.getJSON("#Url.Action("ReturnContentForSrpead", new { #ID = item.ID })", function (msg) {
var tags = BID.getParams.C32().tags;
var data = (msg.data || {}).wordgraph || [{ key: tags[0] }, { key: tags[1] }, { key: tags[2] }, { key: tags[3] }, { key: tags[4] }];
iDemand.drawBg().setData(data[lastTab]).drawCircle(BID.getColor(lastTab)).wordgraph = data;
});
});
</text>
}
i passed all instances from controller when i render page at very beginning, so that means all content already got, but only use jquery ajax to achieve kind of asynchronous. if you confuse with why i used Razor to render scripts, ok, i tried javascript as well, but got same result.
but one thing makes me shake was, when i run below code from console, it works fine.
$("##item.ID").click(function () {
console.log('clicked');
});
Do not render inline scripts like that. Include one script and add a class name to the dynamically added elements and store the items ID as a data- attribute, then use event delegation to handle the click event
In the datepickers .on function
var table = $('#brandtable'); // cache it
$.each(values, function (k, v) {
// Give each cell a class name and add the items ID as a data attribute
table .append("<td><button class='btn btn-default brand' data-id="v.ID>" + v.BrandName + "</button></td>");
Then use event delegation to handle the click event.
var url = '#Url.Action("ReturnContentForSrpead")';
table.on('click', '.brand', function() {
// Get the ID
var id = $(this).data('id');
$.getJSON(url, { ID: id }, function (msg) {
....
});
});
Side note: Its not clear what your nested .each() loops are trying to do and you are creating invalid html by adding <td> elements direct to the table. Best guess is that you want to add a new rows with 9 cells (and then start a new row) in which case it needs to be something like
$.each(values, function (k, v) {
if (k % 9 === 0) {
var row = $('</tr>');
table.append(row);
}
var button = $('</button>').addClass('btn btn-default brand').data('id', v.ID).text(v.BrandName);
var cell = $('</td>').append(button);
row.append(cell);
})
Recommend also that you change
url: "DataChanged?fromDate=" + $('#from-date').val() + "&toDate=" + $('#to-date').val(),
to
url: '#Url.Action("DataChanged")',
data: { fromDate: from, toDate: to }, // you already have the values - no need to traverse the DOM again
You are binding click event on every item ID but the way you are getting id is not right. This $("##item.ID") will not find any element because this will bind click to an element whose id is #item.ID and there is no such element will this id. You need to change it like below. Concatenate "#" with each item id.
$("#"+#item.ID).click(function () {
//your code
})
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');
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.