JavaScript checkbox Tree - children automatic checked - javascript

folks!
I've a litte problem, this is the situation:
Tree View
I let the tree on basis of the "lvl" create. That means, Bereich ABC is lvl1, Test1.docx is lvl4 and so on. So it's a "fake" Tree. But i have just this lvl information for every object.
I have to check the checkbox if the parent is clicked. that means, if lvl3 is clicked (for example "Originale") the lvl4 and lvl5 have to be checked also.
Do you understand what i mean? I hope so. But i can't make it working. Do you have any ideas?
$('[class^=lvl]').click(function(){
var keepChecking = true;
var currentElement = $(this);
var clickedLevel = getLevel(currentElement);
var checkValue = currentElement.is(':checked');
while (keepChecking) {
currentElement.attr('checked' , checkValue);
// get next element
currentElement = getNextCheckbox(currentElement);
var currentLevel = getLevel(currentElement);
keepChecking = (currentLevel > clickedLevel);
}
});
function getNextCheckbox(checkbox) {
return checkbox.parent().parent().next().children(":first").children(":first");
}
function getLevel(checkbox) {
var currentClass = checkbox.attr('class');
var currentLvl = currentClass.substring(3, currentClass.length);
return parseInt(currentLvl);
}
<TD class="center">
<INPUT TYPE="checkbox" NAME="" class="lvl[LL_REPTAG=PFADLEVEL /] docCheck" VALUE="[LL_REPTAG=DataId /]">
</TD>

I changed your javascript code to this:
function getNextCheckbox(checkbox) {
return checkbox.parent().parent().next().children(":first").children(":first");
}
function getLevel(checkbox) {
var currentClass = checkbox.attr('class');
if (currentClass){
var currentLvl = currentClass.substring(3, currentClass.length);
return parseInt(currentLvl);
}else{
return false;
}
}
$('[class^=lvl]').click(function(){
var currentElement = $(this);
var clickedLevel = getLevel(currentElement);
var checkValue = currentElement.is(':checked');
nextElement = getNextCheckbox(currentElement);
while ( getLevel(nextElement)>clickedLevel) {
currentElement=nextElement;
currentElement.prop('checked' , checkValue);
nextElement = getNextCheckbox(currentElement);
}
});
You can also play with it here: https://jsfiddle.net/1r73vy7z/1/
Enjoy :)

Related

How can I add validation to an Input field? Binding JSON model doesn't work

I try to learn SAPUI5 with Samples frpm Demo kit Input - Checked. I get an error message: oInput.getBinding is not a function
I have a simple input field xml:
<Label text="Name" required="false" width="60%" visible="true"/>
<Input id="nameInput" type="Text" enabled="true" visible="true" valueHelpOnly="false" required="true" width="60%" valueStateText="Name must not be empty." maxLength="0" value="{previewModel>/name}" change= "onChange"/>
and my controller:
_validateInput: function(oInput) {
var oView = this.getView().byId("nameInput");
oView.setModel(this.getView().getModel("previewModel"));
var oBinding = oInput.getBinding("value");
var sValueState = "None";
var bValidationError = false;
try {
oBinding.getType().validateValue(oInput.getValue());
} catch (oException) {
sValueState = "Error";
bValidationError = true;
}
oInput.setValueState(sValueState);
return bValidationError;
},
/**
* Event handler for the continue button
*/
onContinue : function () {
// collect input controls
var that = this;
var oView = this.getView();
var aInputs =oView.byId("nameInput");
var bValidationError = false;
// check that inputs are not empty
// this does not happen during data binding as this is only triggered by changes
jQuery.each(aInputs, function (i, oInput) {
bValidationError = that._validateInput(oInput) || bValidationError;
});
// output result
if (!bValidationError) {
MessageToast.show("The input is validated. You could now continue to the next screen");
} else {
MessageBox.alert("A validation error has occured. Complete your input first");
}
},
// onChange update valueState of input
onChange: function(oEvent) {
var oInput = oEvent.getSource();
this._validateInput(oInput);
},
Can someone explain to me how I can set the Model?
Your model is fine and correctly binded.
The problem in your code is here, in the onContinue function
jQuery.each(aInputs, function (i, oInput) {
bValidationError = that._validateInput(oInput) || bValidationError;
});
aInput is not an array, so your code is not iterating on an array element.
To quickly fix this, you can put parentheses around the declaration like this:
var aInputs = [
oView.byId("nameInput")
];
Also, you could remove the first two lines of the _validateInput method since they are useless...
Usually, we set the model once the view is loaded, not when the value is changed. For example, if you would like to set a JSONModel with the name "previewModel", you can do as mentioned below.
Note that onInit is called when the controller is initialized. If you bind the model properly as follows, then the oEvent.getSource().getBinding("value") will return the expected value.
onInit: function(){
var oView = this.getView().byId("nameInput");
oView.setModel(new sap.ui.model.json.JSONModel({
name : "HELLO"
}), "previewModel");
},
onChange: function(oEvent) {
var oInput = oEvent.getSource();
this._validateInput(oInput);
},
...
Also, for validating the input text, you can do the following:
_validateInput: function(oInput) {
var oBinding = oInput.getBinding("value");
var sValueState = "None";
var sValueStateText = "";
var bValidationError = false;
if(oBinding.getValue().length === 0){
sValueState = "Error";
sValueStateText = "Custom Error"
}
oInput.setValueState(sValueState);
if(sValueState === "Error"){
oInput.setValueStateText(sValueStateText);
}
return bValidationError;
},
Please note that the code above is not high quality and production ready as it's a quick response to this post :)

Pass input text value to javascript not working

Good day. I have read and done almost all of the solution in the questions but cant seem to solve my problem. As written in my question, in mvc, i am passing a value from controller to view a string and then get by javascript to run a modal if ever a certain condition is met. please help. thanks.
here is the code in my controller:
public ActionResult Series()
{
List<sample> series = db.samples.Where(x => x.status == "False").ToList();
if ( series.Count == 0)
{
ViewBag.Info = "None";
}
else {
ViewBag.Series = series;
ViewBag.Info = "Have";
}
return View();
}
My View:
<input type="text" value="#ViewBag.Info" id="info" name="info" />
My Javascript:
#section Scripts{
<script>
$(window).on('load', function () {
var modelll = document.getElementById("#(ViewBag.Info)").value;
var s_end = document.getElementById("myNumber2").value;
var s_current = document.getElementById("myNumber3").value;
var s_status1 = document.getElementById("status").value;
var s_id1 = parseInt(document.getElementById("myNumber").value);
var s_end2 = parseInt(s_end, 10);
var s_current2 = parseInt(s_current, 10);
var x = parseInt(s_current, 10) + 1;
document.getElementById("item1").value = s_id1;
document.getElementById("item2").value = s_end;
document.getElementById("item3").value = x;
document.getElementById("status2").value = s_status1;
if (modelll === 'Have')
{
if ((s_current2 > s_end2) && (s_current2 != s_end2)) {
$('#myModal').modal({ backdrop: 'static', keyboard: false });
$('#myModal').modal('show');
}
}
else
{
$('#myModal').modal({ backdrop: 'static', keyboard:false });
$('#myModal').modal('show');
}
});
</script>
}
getElementById need an ID but you are passing #ViewBag.Info. change it to :
var modelll = document.getElementById("info").value;
also you are making many extra variables which are not really needed. for example to get what you have in s_current2, you can use
var s_current = parseInt(document.getElementById("myNumber3").value, 10);
no need to create another variable to convert it to integer.
To get the value from textbox
var modelll = document.getElementById("info");
To set the value to textbox
document.getElementById("info").value = var modelll;
you are using #ViewBag.Info instead of element id.
Following line is causing the problem in your code :
var modelll = document.getElementById("#(ViewBag.Info)").value;
// document.getElementById needs Id but you are passing #(ViewBag.Info) which is wrong
var modelll = document.getElementById("info").value; //info id of your textbox
// now check
if (modelll === 'Have')
{ }
else
{ }

How to know which tables's checkbox is selected?

This is a function
function collect_users_and_groups() {
var tos = [];
$('#mytable12 input:checked, #groupsTable1 input:checked').each(function(i, elt) {
//alert("to groups");
var dataids = $(this).parent().attr("data-selected").split(",");
alert("dataids "+dataids);
var name = $.trim($(this).parent().next().text());
tos.push(name);
});
return tos.join(', ');
}
which is called when I select check boxes
Actually groupsTable1 has data-selected attribute but mytable12 does not have.
I want to call this var dataids = $(this).parent().attr("data-selected").split(",");
when checkbox of groupsTable1 is clicked
Please tell me how to do?
This is the full fiddle,the above js codes can be found in between 22-33 in the js section
You can use .is() to check table is groupsTable1.
function collect_users_and_groups() {
var tos = [];
$('#mytable12 input:checked, #groupsTable1 input:checked').each(function(i, elt) {
//Check table is groupsTable1
if($(this).closest('table').is("#groupsTable1")){
//alert("to groups");
var dataids = $(this).parent().attr("data-selected").split(",");
alert("dataids "+dataids);
var name = $.trim($(this).parent().next().text());
tos.push(name);
}
});
return tos.join(', ');
}
OR
Simply use
$('#mytable12 input:checked, #groupsTable1 input:checked').each(function(i, elt) {
instead of
$('#groupsTable1 input:checked').each(function(i, elt) {

Cannot get values of all my checkboxes on a click event in Javascript

I have a list of checkbox as below :
The code for that list is :
#foreach (extranetClient.Models.Classes.FonctionContact fonction in ViewBag.Fonctions)
{
string coche = "";
if ((#Model.ListeFonctions).Any(c => c.IdFonction == fonction.IdFonction))
{
coche = "checked";
}
<input type="checkbox" #coche id="checkbox" value="#fonction.IdFonction" />#fonction.LibelleFonction <br />
}
So now I would like to get the values of all the ckeckboxes which are checked in the list everytime I check one of them. So I've tried that :
$("#checkbox").click(function () {
var TabIdFonctions = new Array();
var compteur = 1;
$("input[type='checkbox']:checked").each(
function () {
TabIdFonctions[compteur] = $(this).val();
compteur++;
});
});
But it doesn't work and I don't really know why. Hope somebody has an idea.
In javascript arrays are 0 indexed. But you could use the .push method instead. Also you should use a class selector, not an id selector because you can have only one element with a given id:
$('.checkbox').click(function () {
var TabIdFonctions = new Array();
$('.checkbox:checked').each(function () {
TabIdFonctions.push($(this).val());
});
});
Also don't forget to give your checkboxes a class, not id:
<input type="checkbox" #coche class="checkbox" value="#fonction.IdFonction" />
javascript code
var els = document.getElementsByTagName('input');
for (var i = 0; i < els.length; i++) {
var el = els[i];
if (el.checked == true) {
TabIdFonctions.push(el.value);
}
}

Javascript: Problem regarding creating a dropdown list using javascript?

I'm trying to create a dropdown list from an array on my overlay (div element) using javascript.
In this example,
spcodelist = [u'CA125', u'HCM112', u'HCM147', u'HCM97', u'HKI128', u'HKI158', u'HKS161', u'HKS231', u'TKA230']
Here are related lines of code:
var pcode_form = document.createElement('form');
div.appendChild(pcode_form);
var pcode_select = document.createElement('select');
pcode_form.appendChild(pcode_select);
var i = 0;
var spcodelist = document.getElementById('spcodelist').value;
spcodelist = spcodelist.replace("[","");
spcodelist = spcodelist.replace("]","");
var spcodearr = new Array();
spcodearr = spcodelist.split(', ');
for (i=0;i<=spcodearr.length;i++){
spcodearr[i] = spcodearr[i].replace(/u'/g,"");
spcodearr[i] = spcodearr[i].replace(/'/g,"");
var pcode_option = document.createElement('option');
pcode_option.text = spcodearr[i];
pcode_option.value = spcodearr[i];
pcode_select.appendChild(pcode_option);
}
With this code, the dropdown list works fine but code after it will not work any more. I don't know what's the problem? How can I solve it? Or is there any better solution? Thank you very much.
I don't know what you are doing wrong, but the following works fine and should work in any browser. I've added a remove button so you can add and remove the select as often as you like.
<script type="text/javascript">
function addSelect(id) {
var div = document.getElementById(id);
var pcode_form = document.createElement('form');
pcode_form.id = 'f0';
div.appendChild(pcode_form);
var pcode_select = document.createElement('select');
pcode_form.appendChild(pcode_select);
var spcodelist = document.getElementById('spcodelist').value;
// Do replaces in one go
spcodelist = spcodelist.replace(/[\[\]\'u ]/g,'');
var spcodearr = spcodelist.split(',');
for (var i=0, iLen=spcodearr.length; i<iLen; i++) {
pcode_select.options[i] = new Option(spcodearr[i],spcodearr[i]);
}
}
</script>
<button onclick="addSelect('d0');">Add select</button>
<button onclick="
var el = document.getElementById('f0');
el.parentNode.removeChild(el);
">Remove form</button>
<div id="d0"></div>
<textarea id="spcodelist" style="display:none">[u'CA125', u'HCM112', u'HCM147', u'HCM97', u'HKI128', u'HKI158', u'HKS161', u'HKS231', u'TKA230']</textarea>

Categories

Resources