Event to some dynamically generated checkbox issue - javascript

My english is not good but I need help please!!!
I am dynamically adding rows to a table, add textbox and checkbox's.
In the change function I want: When the first checkbox is marked the others are disabled and the texbox change their value
The updatebox function It works perfectly for each generated row, but change function only it works with the first.
function agregar() {
var fila = $('<tr></tr>');
var columna = $('<td></td>');
var input = $('<input type="text" />').attr({
name: 'idiomas_usu[]',
id: 'list1'
});
columna.append(input);
input = $('<input type="checkbox" />').attr({
name: 'dos',
class: 'cb2',
id: 'cb2'
});
columna.append(input);
input = $('<input type="text" />').attr({
name: 'idiomas_usu[]',
id: 'list2'
});
columna.append(input);
input = $('<input type="checkbox" />').attr({
name: 'dos',
class: 'cb2',
id: 'cb3'
});
columna.append(input);
input = $('<input type="text" />').attr({
name: 'idiomas_usu[]',
id: 'list3'
});
columna.append(input);
input = $('<input type="checkbox" />').attr({
name: 'dos',
class: 'cb2',
id: 'cb4'
});
columna.append(input);
input = $('<input type="text" />').attr({
name: 'idiomas_usu[]',
id: 'list4'
});
columna.append(input);
input = $('<input type="checkbox" />').attr({
name: 'dos',
class: 'cb2',
id: 'cb5'
});
columna.append(input);
fila.append(columna);
$('#tab_logic').append(fila);
}
function updateBox(event) {
var input = $(this).prev();
if (this.checked) {
input.val("1");
} else {
input.val("");
}
}
function change(event) {
var $this = $(this);
if ($this.is("#cb2")) {
if ($("#cb2:checked").length > 0) {
$("#cb3").prop({
disabled: true,
checked: false
});
$("#cb4").prop({
disabled: true,
checked: false
});
$("#cb5").prop({
disabled: true,
checked: false
});
$("#list2").prop({
disabled: true,
value: ''
});
$("#list3").prop({
disabled: true,
value: ''
});
$("#list4").prop({
disabled: true,
value: ''
});
} else {
$("#cb3").prop("disabled", false);
$("#cb4").prop("disabled", false);
$("#cb5").prop("disabled", false);
}
}
}
$('#boton').click(agregar);
$('#tab_logic').on('click', '.cb2', updateBox);
$('#tab_logic').on('click', '.cb2', change);
Here's the code running: JSfiddle
Please help me!!!!

You have all the same IDs so its grabbing the first occurrence. One option is to give your rows an ID and use that in your jQuery selector to target the correct items, like this: https://jsfiddle.net/rko41z88/8/
Below is a snippet of the fiddle, go to the fiddle to see the whole thing in action.
Give your rows an ID in your agregar() function like this...
window.myRowCnt = window.myRowCnt+1;
var fila = $('<tr id="row'+window.myRowCnt+'"></tr>');
Then use that row ID to target the correct items like this...
function change(event){
var $this = $(this);
var rowId = $this.closest('tr')[0].id;
if ($this.is("#cb2")) {
if ($("#"+rowId+" #cb2:checked").length > 0) {
$("#"+rowId+" #cb3").prop({ disabled: true, checked: false });
$("#"+rowId+" #cb4").prop({ disabled: true, checked: false });
$("#"+rowId+" #cb5").prop({ disabled: true, checked: false });
$("#"+rowId+" #list2").prop({ disabled: true, value: '' });
$("#"+rowId+" #list3").prop({ disabled: true, value: '' });
$("#"+rowId+" #list4").prop({ disabled: true, value: '' });
} else {
$("#"+rowId+" #cb3").prop("disabled", false);
$("#"+rowId+" #cb4").prop("disabled", false);
$("#"+rowId+" #cb5").prop("disabled", false);
}
}
}

This might not be the best answer for you, but I recommend to use React.js framework. It's best for dynamic web applications.

Related

The kendoTreeView is not getting re-rendered after node removal upon adding new node

There are two event handlers: one adds a node to the tree, the other one - removes it. And it works fine as expected until the node gets removed by calling "check" event.
here is a tree (upon node check - it gets removed):
$('#folderAttributeTree').kendoTreeView({
dataSource: this.attributeTree,
dataRole: "treeview",
dataTextField: "name",
checkboxes: true,
loadOnDemand: true,
check: function(e) {
var treeView = e.sender,
checkedNode = e.node;
treeView.remove(checkedNode);
},
dataBound: function(e) {
if (!this.dataSource.data().length) {
this.element.append("<li class='no-items'>No items yet.</li>");
} else {
this.element.find(".no-items").remove();
}
}
}).data("kendoTreeView");
here is the add node method (it creates always nested elements):
addLabel: function(e) {
e.preventDefault();
var label = this.get('folder_label'),
folderAttributeTree = $("#folderAttributeTree").data("kendoTreeView"),
attributeTree = this.get('attributeTree')
data = [];
if (label !== null && label !== '') {
if (attributeTree.length) {
data = attributeTree;
var i = 0;
while (data.length) {
data = data[0].items;
i++;
}
data.push({
name: label,
type: 'folder',
expanded: true,
id: i,
items: [],
hasChildren: true,
itemIndex: 0
});
} else {
this.set('attributeTree', [{
name: label,
type: 'folder',
expanded: true,
id: 0,
items: [],
hasChildren: true,
itemIndex: 0
}]);
}
}
this.set('folder_label', '');
folderAttributeTree.setDataSource(this.attributeTree);
}
The problem is, when I try adding a node after its removal - a treeview is no more re-rendering (however if I check the console.log the data is getting added to the object as it should).
I'm new to kendo-ui. Please help me solving this.
Thank you in advance!
After submitting my question to teleriks support they answered with a pretty useful hint, that tended me to found a solution.
For those, who has similar problem, here is the solution:
addLabel: function(e) {
e.preventDefault();
var label = this.get('folder_label'),
folderAttributeTree = $("#folderAttributeTree").data("kendoTreeView"),
attributeTree = this.get('attributeTree');
if (label !== null && label !== '') {
if (attributeTree.length) {
var deepest = this.findDeepest(this.attributeTree[0]);
folderAttributeTree.append({
name: label,
type: 'folder',
expanded: true,
id: deepest.id + 1,
items: [],
hasChildren: true
}, $("#folderAttributeTree .k-item:last"));
} else {
this.set('attributeTree', kendo.observableHierarchy([{
name: label,
type: 'folder',
expanded: true,
id: 0,
items: [],
hasChildren: true
}]));
}
}
this.set('folder_label', '');
folderAttributeTree.setDataSource(viewModel.attributeTree);
}
The helpful hint was laying in using .append method instead of .push
I didn't notice the append method had the second (optional) parameter called parentNode which apparently was so helpful in my case.

Getting corresponding values in list box by clicking on specific value in dropdown

I am getting values in dropdown form my json and I am trying when I click on one value from dropdown then list box shud get populated. for example,
As below you can see my json file as now i m getting values in 1st dropdown as obs, hid I want.. say if i click on obs in list box i want to get brs1,crs1,drs1.
[{
"name": "obs",
"date": "1458834026000",
"attr001": "brs1",
"attr002": "crs1",
"attr003": "drs1",
}, {
"name": "hid",
"date": "1458774000000",
"attr001": "ffrs1",
"attr002": "grrs1",
"attr003": "mno1",
}, {
"name": "qwe",
"date": "1425744000000",
"attr001": "klm1",
"attr002": "wer1",
"attr003": "iop1",
}, {
"name": "rty",
"date": "1458774000000",
"attr001": "yrs1",
"attr002": "qws1",
"attr003": "prs1"
}]
My javascript file is like
$(document).ready(function () {
$.getJSON("data.json",function(obj) {
var jsObject = $.parseJSON(obj);
var usedNames = [];
$.each(obj, function(key, value) {
if (usedNames.indexOf(value.name) == -1) {
$("#dropdown1").append("<option value=" + key + ">" + value.name + "</option>");
usedNames.push(value.name);
}
$('<option>', {
text: 'Select your Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#dropdown1');
$.each(jsObject, function (index, value) {
$('<option>', {
text: value['name'],
value: index
}).appendTo('#dropdown1');
});
$('<option>', {
text: 'Select your List Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#listbox');
$('#dropdown1').change(function () {
$('#listbox').empty();
$('<option>', {
text: 'Select your List Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#listbox');
var selection = $('#dropdown1 :selected').text();
$.each(jsObject, function (index, value) {
if (value['name'] === selection) {
$('<option>', {
text: value['attr001'],
value: 'attr001'
}).appendTo('#listbox');
$('<option>', {
text: value['attr002'],
value: 'attr002'
}).appendTo('#listbox');
$('<option>', {
text: value['attr003'],
value: 'attr003'
}).appendTo('#listbox');
}
});
});
});
My html
<form name="myform" id="myForm">
<select id="dropdown1"></select>
<select id="listbox"></select>
<br>
Please suggest something.. Thank you..
Try this
$.getJSON("data.json",function(obj) {
var json_string = '[{"name":"obs","date":"1458834026000","attr001":"brs1","attr002":"crs1","attr003":"drs1"},{"name":"hid","date":"1458774000000","attr001":"ffrs1","attr002":"grrs1","attr003":"mno1"},{"name":"qwe","date":"1425744000000","attr001":"klm1","attr002":"wer1","attr003":"iop1"},{"name":"rty","date":"1458774000000","attr001":"yrs1","attr002":"qws1","attr003":"prs1"}]';
var jsObject = $.parseJSON(json_string);
// var jsObject = $.parseJSON(obj); // Assuming yout obj contains the JSON Stirng
$('<option>', {
text: 'Select your Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#dropdown1');
$.each(jsObject, function (index, value) {
$('<option>', {
text: value['name'],
value: index
}).appendTo('#dropdown1');
});
$('<option>', {
text: 'Select your List Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#listbox');
$('#dropdown1').change(function () {
$('#listbox').empty();
$('<option>', {
text: 'Select your List Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#listbox');
var selection = $('#dropdown1 :selected').text();
$.each(jsObject, function (index, value) {
if (value['name'] === selection) {
$('<option>', {
text: value['attr001'],
value: 'attr001'
}).appendTo('#listbox');
$('<option>', {
text: value['attr002'],
value: 'attr002'
}).appendTo('#listbox');
$('<option>', {
text: value['attr003'],
value: 'attr003'
}).appendTo('#listbox');
}
});
});
}
Here is Fiddle
Use Id and class too when you are creating HTML
$("#dropdown1").append("<option id=" + value.name + " class="dropdown" value=" + key + ">" + value.name + "</option>");
Than make a selector based on click on class like
$('.dropdown').on('change', function(){
ele = $(this).attr('id');
})
Now you will have the name of selected element in ele than parse your json to get all attribute value for than name and populate listbox by that data

When I add jquery validate function my other functions stop working

I have a form where I have several javascript/jquery functions that are working fine. As soon as I add a validate function they all stop working. I am using the plugin from http://jqueryvalidation.org/ and have all my functions in one js file. Again all these functions work fine until I add the validation function. Here is the js file.
$(function(){
$(".timeinput").timepicker({
step: 5
});
});
$(function(){
$(".datepick").datepicker({
changeYear: true,
changeMonth: true
});
});
$(function(){
$("#incimechtype").change(function(){
var dropdown = $(this).val();
$.ajax({
url:"getinjuryjson.php",
dataType: "json"
}).done( function(data){
$("#incimech").find("option").remove();
if(dropdown !== ""){
$("#incimech").append($('<option/>'));
}
switch(dropdown){
case "Mechanism":
$.each(data, function(key,value){
if(value.injmech==='Mechanism'){
$("#incimech").append($('<option/>',{
value: value.injmechid,
text: value.injmechdescrip
}));
}
});
break;
case "Other":
$.each(data, function(key,value){
if(value.injmech==='Other'){
$("#incimech").append($('<option/>',{
value: value.injmechid,
text: value.injmechdescrip
}));
}
});
break;
case "Object":
$.each(data, function(key,value){
if(value.injmech==='Object'){
$("#incimech").append($('<option/>',{
value: value.injmechid,
text: value.injmechdescrip
}));
}
});
break;
}
}
)
}
)
}
);
$("#referto").change(function(){
var rechange = false;
$('#referto option:selected').each(function(){
if($(this).text()=="Other"){
rechange =true;
}
});
if(rechange){
var textarea = "<textarea name='referother' id='referother' />";
$("#referto").after(textarea);
}
else
{
$("#referother").remove();
}
});
$(function(){
$("#classcase").change(function(){
var dropdown = $(this).val();
$.ajax({
url:"getoshaclassson.php",
dataType: "json"
}).done( function(data){
$("#otherrecord").find("option").remove();
if(dropdown !== ""){
$("#otherrecord").append($('<option/>'));
}
if(dropdown ==="Other Recordable"){
$.each(data, function(key,value){
if(value.oshaclassid > 3){
$("#otherrecord").append($('<option/>',{
value: value.oshaclassid,
text: value.oshaclass
}));
}
});
}
}
)
}
)
}
);
$(function(){
$("#addlostdays").click(function(){
$("#oshadataarea").find("label").remove();
$("#oshadataarea").find("input").remove();
$("#oshadataarea").find("textarea").remove();
$("#oshadataarea").find("br").remove();
$("#oshadataarea").append($('<label/>',{
text:"Begin Lost Date",
for: "newloststartdate",
class: "eighth"})).append($('<input/>',{
type: "text",
id: "newloststartdate",
name: "newloststartdate",
class:"datepick"
})).append($('<label/>',{
text:"End Lost Date",
for: "newlostenddate",
class: "eighth"})).append($('<input/>',{
type: "text",
id: "newlostenddate",
name: "newlostenddate",
class:"datepick"
}))
});
$('form').on('focus',".datepick", function(){
$(this).datepicker({
changeMonth: true,
changeYear: true
});
});
});
$(function(){
$("#addjobtrans").click(function(){
$("#oshadataarea").find("label").remove();
$("#oshadataarea").find("input").remove();
$("#oshadataarea").find("textarea").remove();
$("#oshadataarea").find("br").remove();
$("#oshadataarea").append($('<label/>',{
text:"Begin Light Duty",
for: "newlightstartdate",
class: "eighth"})).append($('<input/>',{
type: "text",
id: "newlightstartdate",
name: "newlightstartdate",
class:"datepick"
})).append($('<label/>',{
text:"End Light Duty",
for: "newlightenddate",
class: "eighth"})).append($('<input/>',{
type: "text",
id: "newlightenddate",
name: "newlightenddate",
class:"datepick"
}))
});
$('form').on('focus',".datepick", function(){
$(this).datepicker({
changeMonth: true,
changeYear: true
});
});
});
$(function(){
$("#addemphealthcomments").click(function(){
$("#oshadataarea").find("label").remove();
$("#oshadataarea").find("input").remove();
$("#oshadataarea").find("textarea").remove();
$("#oshadataarea").find("br").remove();
$("#oshadataarea").append($('<label/>',{
text:"Employee Comment Date",
for: "newemplcomdate",
class: "eighth"})).append($('<input/>',{
type: "text",
id: "newemplcomdate",
name: "newemplcomdate",
class:"datepick"
})).append($('<br />')).append($('<label/>',{
text:"Employee Comments",
for: "newemplincidomments",
class: "eighth"})).append($('<textarea/>',{
cols: "50",
rows: "5",
id: "newemplincidomments",
name: "newemplincidomments"
}))
});
});
As soon as I add this below function every other function stops working.
$function(){
$("#incidentform").validate({
rules: {
incidate: "required"
},
messages: {
incidate: "Please enter the incident date."
}
})
}
I must be doing something wrong. I am pretty much a neophyte when it comes to jquery as I have only been using it for a month. Hope someone can help.
$(function(){
$("#incidentform").validate({
rules: {
incidate: "required"
},
messages: {
incidate: "Please enter the incident date."
}
})
});
Missing brackets around it.

How to change display message in an ExtJs Combobox?

I have an ExtJs Combobox with multiple true and I want to show "X values selected" on the input field instead of "Value 1, Value 2, Value 3". I tried with select listener but when I set the value to the input field and then you call multicombo.getValue() it takes the value from the input field. I would need something like take the value from the valueField (a hidden input).
My code:
var multiCombo = Ext.create('Ext.form.field.ComboBox', {
renderTo: item.id,
multiSelect: true,
displayField: 'name',
editable: false,
valueField: 'id',
emptyText: 'Select',
hiddenName: 'data[Model][' + item.getAttribute('question-id') + '][value]',
submitValue: true,
inputType: 'hidden',
value: selectedOptions,
width: 300,
store: store,
queryMode: 'local',
listeners: {
expand: function (combo) {
var values = Ext.get(combo.hiddenDataEl.dom.lastChild).dom.value;
values = values.split(",");
Ext.each(values, function (value, i) {
values[i] = parseInt(value);
});
combo.setValue(values);
Ext.get(combo.getInputId()).dom.value = values.length + ' selected';
},
select: function (combo, values) {
if (values[values.length - 1].data.id === parseInt(item.getAttribute('not-applicable'))) {
combo.setValue(parseInt(item.getAttribute('not-applicable')));
} else {
var notApplicable = -1;
var newValues = combo.getValue();
if ((notApplicable = combo.getValue().indexOf(parseInt(item.getAttribute('not-applicable')))) != -1) {
newValues.splice(notApplicable, 1);
}
combo.setValue(newValues);
}
Ext.get(combo.hiddenDataEl.dom.lastChild).dom.value = combo.getValue().join(',');
optionsSelected = combo.getValue();
Ext.get(combo.getInputId()).dom.value = optionsSelected.length + ' selected';
},
change: function (combo) {
if (item.getAttribute('required') == 'true') {
if (combo.getValue().length == 0) {
question.findParentNode('li', 1, true).addCls("is_required");
} else {
question.findParentNode('li', 1, true).removeCls("is_required");
}
//There is no ExtJs equivalent for this
$('#' + combo.getInputId()).keyup();
}
}
}
});
I'm not sure that I follow what is going on with all of the event handlers (so I may be missing something), but the simplest way to achieve what you described in your first sentence above is to provide your own implementation for the combo's getDisplayValue method. Here it is in the docs.
Just set it up to return a count of how many values are selected. Here's an example:
var multiCombo = Ext.create('Ext.form.field.ComboBox', {
renderTo: item.id,
multiSelect: true,
displayField: 'name',
// your own getDisplayValue implementation
getDisplayValue: function() {
return multiCombo.value.length + ' values selected';
},
editable: false,
valueField: 'id',
emptyText: 'Select',
hiddenName: 'data[Model][' + item.getAttribute('question-id') + '][value]',
submitValue: true,
inputType: 'hidden',
value: selectedOptions,
width: 300,
store: store,
queryMode: 'local',
});
Also this may help:
getDisplayValue: function() {
return (this.displayTplData.length > 1) ? this.displayTplData.length + ' selected' : this.displayTplData[0].name;
},

jQuery Create element inside an element

I've seen many guides online for create a new element in jQuery such as the following code
var input = $('<input>', {
id: 'FormUsername',
name: 'username',
type: 'text',
value: 'Enter your username...',
focusin: function() {
$(this).val('');
}
}).appendTo(someElement);
This creates one input element and appends it. I want to create a div element and add this input element to it and then append it. How would i go about doing that?
Thanks,
Alex
You can use .wrap() to wrap your element into another one before appending it:
var input = $('<input>', {
id: 'FormUsername',
name: 'username',
type: 'text',
value: 'Enter your username...',
focusin: function() {
$(this).val('');
}
}).wrap('<div/>').parent().appendTo(someElement);
Note: you'd have to call .parent() because .wrap() does not return the wrapping element
DEMO
You could also do it in several steps if you need to add attributes to the wrapping div, syntax is similar:
var input = $('<input>', { ... });
// create a div element with an ID=wrapper
$('<div/>', { id: 'wrapper' })
// append the input to it
.append(input)
// append the div to "someElement"
.appendTo(someElement);
DEMO
Same syntax, really:
var input = $('<input>', {
id: 'FormUsername',
name: 'username',
type: 'text',
value: 'Enter your username...',
focusin: function() {
$(this).val('');
}
});
var div = $('<div>', {
id: 'SomeWrapperDiv'
}).append(input);
div.appendTo(someElement);
This maybe help you:
http://jsfiddle.net/Eek7N/1/
var div = $("<div>");
var input = $('<input>', {
id: 'FormUsername',
name: 'username',
type: 'text',
value: 'Enter your username...',
focusin: function() {
$(this).val('');
}
});
div.html("I'm the div");
div.append(input);
$("body").append(div);​
And another way:
$('#someElement').append($('<span></span>').append(input));
http://jsfiddle.net/xcZjt/
You can try this.
var input = $('<input>', {
id: 'FormUsername',
name: 'username',
type: 'text',
value: 'Enter your username...',
focusin: function() {
$(this).val('');
}
})
$('<div>', {
id: 'divId',
class: 'className'
})
.append(input)
.appendTo(someElement);
Use the wrap function:
var input = $('<input>', {
id: 'FormUsername',
name: 'username',
type: 'text',
value: 'Enter your username...',
focusin: function() {
$(this).val('');
}
}).wrap('<div></div>').parent().appendTo(someElement);
wrap docs:
Description: Wrap an HTML structure around each element in the set of matched elements.

Categories