DOJO error Id is already registered - javascript

Hi I'm new bee to dojo and stuck into a simple problem. I'm getting an error
Tried to register widget with id==listGrid but that id is already registered. Let me share a piiece of my code with you
I have Three radio button and onclick on any of the radio button will result in grid. I'm using same div for all three radio button. First time the grid will come for first radio button but second time I get an above error. I'm calling this function on click of radio button
_showList:function()
{
var item = this.gc.getSelectedItem()
var id=item.id;
var cont = 'zone';
var action='getCityListById';
var controller='network';
this.cityGc = new GridViewControl({columns:
[
{action:action, controllerName:controller,parameters: {id:item.id, cont: cont}},
{name:"City Name", field:"name", width: "200px", editable: false}
], diff:220
},this.zoneListGrid);
}
zoneListGrid is a dojo attach point which is same for all three radio buttons. please suggest something through which I can work out. Thanks in advance

Since every click on a radio button will trigger this piece of code, dojo will try to create another grid component on the second click. Because there is already a widget present on that attach point, the error is thrown.
Either you re-use the grid that is already present (do a === null check on this.cityGc) or you destroy the existing grid first (this.cityGc.destroy()).

Related

How to find radio group checked property

Here, I've three radio group in a single page. But in the entire page I want to select only one radio option. Like if I'm selecting Monday then Tuesday selection should be unchecked automatically. How can I proceed with the logic, below logic is not working as expected.
sample JSON :
{
report:[
{
day:'Monday',
slot:[
'9-10am',
'10-11am',
'11-12am'
]
},{
day:'Tuesday',
slot:[
'9-10am',
'10-11am',
'11-12am'
]
},{
day:'Wednesday',
slot:[
'9-10am',
'10-11am',
'11-12am'
]
}
]}
JS code
for(var I=0; I<reports.length; I++){
var radios = document.getElementsByTagName('input')
if(radios[I].type === 'radio' && radios[I].checked){
document.getElementById(radios[I].id).checked = false
}
If you're able to create radio buttons in SurveyJS, you should be able to give the button group a name, so there would be no need for any additional JavaScript. Check out their documentation for an example.
Looks like the sort of nested structure you have for the buttons could be achieved with something like a dynamic panel or cascading conditions in SurveyJS. You should be able to render the available time slots dynamically with "visibleIf" based on the selected day.
I would definitely dig around the documentation of SurveyJS to find a solution there rather than hacking your way around it. But solely as an exercise, the problem in your current code could be that you're selecting a button by ID, which will not work correctly if you have tried to give the same ID to multiple buttons. After all, you already have the target button as radios[I], so you could just use radios[I].checked = false. Or the issue could be that you're unchecking the selected button AFTER the new selection has been made, which might actually uncheck the button you just clicked. Hard to say without additional information, but in any case, looping your inputs based on a value that might be something else than the actual number of inputs (you're using reports.length) is probably not the best idea, since that value might be different from the number of inputs in your form, which would mean that not all of them are included in the loop. Here are a couple of examples of what you could do instead:
// Get all radio buttons
const radioButtons = document.querySelectorAll('input[type="radio"]')
// If you need to uncheck the previously selected one (don't do this if you can avoid it!)
radioButtons.forEach(radioButton => {
// Use a mousedown event instead of click
// This gives you time to uncheck the previous one before the new one gets checked
radioButton.addEventListener('mousedown', () => {
// Get the currently selected button and uncheck it
const currentlySelected = document.querySelector('input[type="radio"]:checked')
if (currentlySelected) currentlySelected.checked = false
})
})
// You can add further options to the querySelector, such as [name]
// This gets the currently selected button in the specified group
const checkedRadioButton = document.querySelector('input[type="radio"][name="group-name"]:checked')
Here's a fiddle demonstrating this sort of "fake" radio button functionality (without a "name" attribute).
You can give all these radio buttons the same name, then one radio only will be checked.

Get Parent Table name using Text present in td

I am developing an MVC app in which I have created two tables in view dynamically. In each table first column contains ID and last column contains save button. On click of save button I'm passing this ID to my function. Now I want to check the button was clicked from which table so that I can perform operations. I have tried many solutions but did not work. Can anybody help?
function SaveDocument(_param) {
//alert(_param + "Add");
return;
var tableRow = $("td").filter(function () {
return $(this).text() == String(_param);
}).parent('tr');
tableRow.parent().attr('uid');
}
and I have also tried links like this but none of these work.
Edit : -
I have created fiddle for this here
You mentioned that you're creating tables dynamically, so I'm assuming your click event won't fire unless you delegate it.
Try adding a class say .save to the buttons and run the below code.
$(document).on('click', '.save', function(){
console.log($(this).closest('table'));
});

Pass information to bootstrap modal from Angular.js controller

Simplified problem
I have a store. For a product to be included in the store there needs to be a shelf for it. So, to add a new product to the store the workflow is:
Add a shelf
Add product to that shelf
(The workflow can not be changed)
Realization
The shelf is realized by a row in a table, which in turn is controlled by an Angular.js controller (each shelf is an object in an array). To add an product the user selects "create product" in a drop-down menu that is present on each row. This will show an bootstrap modal where I have from a controller added a tab for each product that is possible to add (since each product needs configuration :) ) , then when the user presses a "create" button in the modal a JavaScript method is called interfacing a REST interface to add the product (the UI is updated by a Socket.io event send from the server when the product has been added successfully.
Problem
The JavaScript method (CreateProduct) needs to now what row (R) was affected as well as what tab (T) was selected so that the "onclick" method for the button is CreateProduct(R, T);
My current solution is pretty ugly imho, I have two global variables for R and T, then I use jQuery to capture show event and tab event from the modal, the link in the dropdown has a field "data-row-id" that is identifying the row
HTML (Jade) snippet from dropdown menu:
a(data-toggle="modal", href="#createProduct", data-row-id="{{row.RowID}}") Create Product
JavaScript:
var R = null;
$('#productModal').on('show.bs.modal', function(e) {
R = $(e.relatedTarget).data('row-id');
});
var T = null;
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
T = e.target.text;
});
I hope there is a better solution to this, I probably am just thinking a bit upsidedown due to inexperience with Angular.js , perhaps there is a way to pass these through the model? Perhaps add these to the modal controller, but then, how to pass the row? My dream would be something like this on the button code
button(type="button", class="btn btn-default", data-dismiss="modal", ng-click="storeCtrl.CreateProduct({{modalCtrl.shelf, modalCtrl.Product)") Create Product
I found a better way (at least I don't need to use jQuery) using ModalService
I created a CreateProductModalController having a variable selectedProduct, this is set on a ng-click event in the tab
ul(class="nav nav-pills", id="tabContent")
li(ng-repeat="prod in products", ng-class="{active: $index == 0}", ng-click="activateTab(prod.name)")
a(href="#{{prod.name}}", data-toggle="tab") {{prod.name}}
The ModalService is called with the rowID that was clicked.
The only problem I have now is that all must be in $scope, I want it to be more encapsulated

jQuery UI checkboxes misbehaving when cloned

I'm trying to create a table of inputs that automatically adds a new row when you enter text in one of the inputs on the bottom line. For the most part, it works fine. However, I'm having some trouble with jQuery UI checkbox buttons.
The checkbox buttons are supposed to change their icon when clicked. This works fine for the original buttons, but the cloned button that appears when you add a new row doesn't work properly.
You can see it in jsfiddle here. To replicate the issue, put some text in the third input down. You'll see that a fourth row appears. If you press the fourth checkbox, you'll see the third checkbox is the one whose icon changes. The wrong button also gets ui-state-focus but doesn't actually get focus, which really baffles me, though the correct button does get ui-state-active and seems, as far as I can tell, to evaluate as having been checked properly.
To be clear, the two checkboxes do not have the same ID, and their labels are for the right checkbox - the createNewRow() function takes care of that. If you comment out the line that turns the checkboxes into jQuery UI checkboxes, you'll see everything works fine. If you console.log the value of $(this).attr('id') in the buttonSwitchCheck function, you'll see that it has the right ID there too - if you click the fourth button, it'll tell you that the id of $(this) is "test4", but it's "test3" (the third button) that gets the icon change.
I'm going mad staring at this and I'd appreciate any help people can give. Here's the code:
// Turns on and off an icon as the checkbox changes from checked to unchecked.
function buttonSwitchCheck() {
if ($(this).prop('checked') === true) {
$(this).button("option", "icons", {
primary: "ui-icon-circle-check"
});
} else {
$(this).button("option", "icons", {
primary: "ui-icon-circle-close"
});
}
}
// Add a new row at the bottom once the user starts filling out the bottom blank row.
function createNewRow() {
// Identify the row and clone it, including the bound events.
var row = $(this).closest("tr");
var table = row.closest("table");
var newRow = row.clone(true);
// Set all values (except for buttons) to blank for the new row.
newRow.find('.ssheet').not('.button').val('');
// Find elements that require an ID (mostly elements with labels like checkboxes) and increment the ID.
newRow.find('.ssheetRowId').each(function () {
var idArr = $(this).attr('id').match(/^(.*?)([0-9]*)$/);
var idNum = idArr[2] - 0 + 1;
var newId = idArr[1] + idNum;
$(this).attr('id', newId);
$(this).siblings('label.ssheetGetRowId').attr('for', newId);
});
// Add the row to the table.
newRow.appendTo(table);
// Remove the old row's ability to create a new row.
row.removeClass('ssheetNewRow');
row.find(".ssheet").unbind('change', createNewRow);
}
$(document).ready(function () {
// Activate jQuery UI checkboxes.
$(".checkButton").button().bind('change', buttonSwitchCheck).each(buttonSwitchCheck);
// When text is entered on the bottom row, add a new row.
$(".ssheetNewRow").find(".ssheet").not('.checkButton').bind('change', createNewRow);
});
EDIT: I was able to find a solution, which I'll share with the ages. Thanks to "Funky Dude" below, who inspired me to start thinking along the right track.
The trick is to destroy the jQuery UI button in the original row before the clone, then reinitializing it immediately afterwards for both the original row and the copy. You don't need to unbind and rebind the change event - it's just the jQuery UI buttons which have trouble. In the createNewRow function:
row.find('.checkButton').button('destroy');
var newRow = row.clone(true);
row.find('.checkButton').add(newRow.find('.checkButton')).button().each(buttonSwitchCheck);
Try using the newer method .on, that allows for delegation, which should help with the dynamic changes to your DOM:
$(".checkButton").button().each(buttonSwitchCheck);
$("table").on("change", ".checkButton", buttonSwitchCheck);
I'm not sure, but it might help with not having to worry about binding events to specific elements.
Also, you could use it for the textbox change event:
$("table").on("change", ".ssheetNewRow .ssheet:not(.checkButton)", createNewRow);
Here's your fiddle with my changes: http://jsfiddle.net/Cugb6/3/
It doesn't function any different, but to me, it's a little cleaner. I thought it would've fixed your problem, but obviously hasn't, due to problems with the button widget.
And funny enough, it doesn't seem they "support" cloning: http://bugs.jqueryui.com/ticket/7959
i think you are using deep clone, which also clones the event handler. in your create new row function, try unbinding the change event then rebind on the clone.

jQuery buttonset refresh not working as I'd expected

OK - I have a function which I call to dynamically add a radio button as per this question. This is the full function:
// function used to create a new radio button
function createNewRadioButton(
selector,
newRadioBtnId,
newRadioBtnName,
newRadioBtnText){
// create a new radio button using supplied parameters
var newRadioBtn = $('<input />').attr({
type: "radio", id: newRadioBtnId, name: newRadioBtnName
});
// create a new label and append the new radio button
var newLabel = $('<label />').append(newRadioBtn).append(newRadioBtnText);
// add the new radio button and refresh the buttonset
$(selector).append(newLabel).append('<br />').buttonset("refresh");
}
So if I were to call the above function with the following code I would expect another radio button to be added underneath the radio buttons already contained in the div '#radioX' (assuming there is a div with id radioX containing radio buttons):
// create a new radio button using the info returned from server
createNewRadioButton(
'#radioX', // Radio button div id
product.Id, // Id
product.Id, // Name
product.Name // Label Text
);
Given that on document ready, I tell jQuery to create me a buttonset out of the radio buttons contained in #radioX like so: $( "#radioX" ).buttonset();, why doesn't the call to $("#radioX").buttonset("refresh") in the function createNewRadioButton refresh the list of radio buttons?
The result that I see after a call to createNewRadioButton is made is a new label with the desired text is added but no new radio button. So instead of a nice new jQuery radio button sitting underneath whatever was already there, I see just a new label with text equivelant to product.Name (in the given example).
I've also noticed this warning output in firebug after a call is made to createNewRadioButton - could this have anything to do with it?
reference to undefined property $(this).button("widget")[0]
EDIT
Here's a screenshot of what I expected to happen:
Here's a screenshot of what happens
My mistake. Actually the refresh method is taking good care of added radio elements at runtime.
The markup you are generating in createNewRadioButton() is I think not compatible with what the plugin expects.
You create:
<label><input /></label>
And the plugin expects:
<input /><label for=''></label>
Here is the modified function:
function createNewRadioButton(
selector,
newRadioBtnId,
newRadioBtnName,
newRadioBtnText){
// create a new radio button using supplied parameters
var newRadioBtn = $('<input />').attr({
type: "radio", id: newRadioBtnId, name: newRadioBtnName
});
// create a new label and append the new radio button
var newLabel = $('<label />').attr('for', newRadioBtnId).text(newRadioBtnText);
// add the input then the label (and forget about the <br/>
$(selector).append(newRadioBtn).append(newLabel).buttonset("refresh");
}
Don't forget to initiliaze the plugin, even if the container '#radioX' is empty:
$('#radioX').buttonset();
I have made a jsfiddle for you to see a working example.
It must be a bug. Change jQuery version from 1.7.1 to 1.8.3, choose UI in jsfiddle1 and you will see that it is now working as expected.
code here

Categories

Resources