B4J Code Snippet [BANano]: Sharing the goodness

Ola

Thought I should create my own easy reference list of stuff I've posted here about BANano.

Tutorials
BANano for Dummies by Example
BANanoJSONQuery to the rescue: The case of the survey app.
Client Side Excel Report Generation [BANanoOXML]
Exploring BANanoEvents [BANano]
Sending Contact Us Form contents to an email with inline PHP [BANano]
Understanding CRUD logic with ExecuteCallBack [BANanoSQL]
Sharing the goodness [BANano]


Libraries
An Object Oriented UX library for BANano [BANanoWebix]
Got it! - Easy Hints [BANano]
A treeview you might use [BANano]
ChartJS charts with 1 line of code using UOECharts [BANano]
Implementing Collaboration with TogetherJS [BANano]
Implementing LiveHelp for your WebApp [ABMaterial]
Create your UX with MaterializaCSS using UOEBANano
UOEGrid: An interesting grid that you might like [BANano]
UOEGridTable Conditional Value Display Formatting [BANano]
UOEGridTable IconRenderer [BANano]
UOEGrid Column Renderer - Let's display images etc [BANano]
Creating Connected Grid Tables with UOEGridTable [BANano]
Creating Master Details Grid with UOEGridTable [BANano]


BackEnd

A BANanoSQL helper class for CRUD functionality [BANanoSQLUtils]
An inline PHP class for your MySQLI CRUD functionality [BANanoMySQL]
BANanoSQL CRUD-ing around with BANanoSQLUtils [BANano]
Exploring Using PHP & SQLite for your WebApp [BANano]
MySQL CRUD with PHP - Part 1 [BANano]
MySQL CRUD with PHP - Part 2 [BANano]
MySQL CRUD with PHP - Part 3.1 [A look an inline PHP] [BANano]
PDO CRUD Class for MSSQL [BANanoMSSQL]
SQLiteDB PHP CRUD Class for BANano [BANanoSQLite]

Experiments

A Material Design Lite framework for Website / WebApp Creation [BANanoReactMDL]
Beginning 3D with Three.JS [BANano3D]
Beginning HTML5 games with CreateJS [BANanoCreateJS]
Building WebApps/Websites with VueJS [BANanoVue]
15 Mockup Elements for your Prototypes [BANAnoWired]
Create reactive, state based components & UI [BANanoReef]
Creating a CRUD app with LocalStorage Backend [BANano]
Creating a hotel reservation app with BANanoJQM
Creating the PhotoNinja Website with UOE [Websites]
CRUD with grid & modal using UOENow [BANanoSQL]
Distributing and accessing an existing SQLite Databases - Part 1 [BANano]
A tabbed dialog to Login, Register, Forgot Password & Reset Password [BANano]
Let's please build a Community Project [BANanoReact]
Executing code without using BANano.Eval [BANano]


Questions
Question:
[SOLVED] Extending Event Driven BANanoSQL with own CallBacks?
Question: [SOLVED] How to maintain element events?
Question: [SOLVED] How to set BANanoEvent Bubbling Off?
Question: [SOLVED] BANanoMaterial Error Fix
Question: [SOLVED] How can I run a JavaScript Method and wait for it to finish?
Question: [SOLVED] Returning all list items in For Each
Question: [SOLVED] How does one use Header.AddMeta?
Question: [SOLVED] How to turn minify off/on
Question: [SOLVED] Empty string passed to getElementID('')
Question: [SOLVED] How to find element existence
Question: [SOLVED] How to CallSub inside #If JavaScript
Question: [SOLVED] Library Compilation FileNotFound Exception
Question: [SOLVED] Map.Initialize inclusion of map keys
Question: [SOLVED] How to transvese elements by name and return attributes
Question: [SOLVED] How to call different subs for different elements
Question: [SOLVED] RangeError: Maximum Stacktrace exceeded
Question: [SOLVED] How do I refresh a page
Question: [SOLVED] FloatingActionButton iif method not defined
Question: [SOLVED] Enumeration Initialization Assignments
Question: [SOLVED] Else If Transpiling Error
Question: [SOLVED] Map Object Enhancements
Question: [SOLVED] Support for String()
Question: [SOLVED] Using / Converting Own B4J Classes
Question: [SOLVED] Ajax Calls: How to convert B4J Http Calls

To relook at these *unresolved

Question:
How to embed & read a json file / rather use BANanoSQL to load it?
Question: How can I upload a file using Php?
Question: CRUD bug using wait
Question: Using MySQL / MSSQL with PHP
Question: How to add dynamic css / injectcss to my app
Question: How to AddJavascriptFile and AddCSSFile on demand

Now for some code snippets...

Removing Attributes

One of the elusive attributes is the 'disabled' attributes for elements. Apparently whether you set this to true/false to enable your element, the status quo stays the same. It seems the only way to toggle this is to remove it to enable your element.

The code snippet here is to remove attributes from elements.

B4X:
'remove an attribute
Sub removeAttr(elID As String, attrName As String)
    elID = elID.tolowercase
    Dim jQ As BANanoObject
    jQ.Initialize("$")
    jQ.Selector($"#${elID}"$).RunMethod("removeAttr", Array(attrName))
End Sub

#Tested

Update: 30 Jan 2019

A new method to remove attribute has been added as BANano.BANanoElement.RemoveAttr
 
Last edited:

Kiffi

Well-Known Member
Licensed User
Longtime User
I know you're already using jQuery in your current project. However, the recommended way for users who can't or don't want to use jQuery is to use the built-in Umbrella.js in BANano.

B4X:
Sub removeAttr(elID As String, attrName As String)
    BANano.GetElement(elID.ToLowerCase).SetAttr(attrName, Null)
End Sub
 

Mashiane

Expert
Licensed User
Longtime User
I know you're already using jQuery in your current project. However, the recommended way for users who can't or don't want to use jQuery is to use the built-in Umbrella.js in BANano.

B4X:
Sub removeAttr(elID As String, attrName As String)
    BANano.GetElement(elID.ToLowerCase).SetAttr(attrName, Null)
End Sub
Thanks Kiffi. Setting the disabled attribute however does not enable my button and I also don't want to use JQuery for such a mandane task.
 

alwaysbusy

Expert
Licensed User
Longtime User
@Kiffi solution is the correct one for non-boolean attributes. The build-in Umbrella.js (4kb) does 95% of what jQuery does (250Kb). This can highly affect the speed of your website/webapp especially on mobile devices so avoid (if possible).

However in this case of disabled, this is one of those weird boolean attributes that cannot be assigned with true or false (go figure!) and do effectively need to be removed to have any effect. In the next version, I will make a RemoveAttr on BANanoElement
 
Last edited:

Mashiane

Expert
Licensed User
Longtime User
Calling B4J methods directly

There are more than one ways to skin a cat, it is said, so yesterday I made an assumption and it turned out to be true. I needed to call a b4j method that was no linked to an event handler in my class module, turns out, I can.

Application Name: ATM
B4J Class Name: pgIndex
B4J Method To Call: DeleteMember
Problem Statement: This does not have an event handler
My Scenario: When I click a delete button, the user should be prompted with a confirm dialog (this uses sweet dialog), when the user selects Yes, a B4J method should be fired to actually delete the record else No. The generated Yes / No button for the sweetmodal are automatically generated and they dont have IDs to I cannot assign an event handler, however you can pass javascript to execute onYes and onNo. So I need a B4J method to be executed and not javascript, this B4J method anyway will be transpiled to BANano javascript subroutine.

The aha moment!

Solution: pass _banano_atm_pgindex.deletemember(); to the Yes script of sweetmodal. Yes, you can define your own buttons for the sweetmodal but I didnt want to add buttons, yet.

Below is my DeleteMember sub routine in B4J in my pgIndex class, this class is like a 'page' for my BANano project.

B4X:
user clicked yes on confirmation, process the deletion
Sub DeleteMember
    'get the memberid to delete
    Dim memberid As String = Page.GetLocalStorage("memberid")
    'get the existing members
    Dim strMembers As String = Page.GetLocalStorage("members")
    If strMembers = "" Then
    Else
        'this will store all unmatching records
        Dim nList As List
        nList.Initialize
        'convert existing members to a list
        Dim lstM As List = App.Json2List(strMembers)
        'each member is a json string
        Dim mTot As Int = lstM.Size - 1
        Dim mCnt As Int
        For mCnt = 0 To mTot
            Dim strMember As String = lstM.Get(mCnt)
            Dim memberM As Map = App.Json2Map(strMember)
            'the id number is the key
            Dim sidnumber As String = memberM.Get("idnumber")
            If sidnumber <> memberid Then
                nList.Add(strMember)
            End If
        Next
        'convert the list and save it back
        strMembers = App.List2Json(nList)
        Page.setlocalstorage("members", strMembers)
        'create the table
        CreateTable
    End If
End Sub

This code below, which traps the eventid, when a deleterow_ linked element is clicked, a sweetmodal prompt is displayed for the user to confirm, when they click 'Yes', the code to delete the member is executed.

B4X:
Case "deleterow"
            Dim rowPos As String = App.mvfield(thisEvent,2,"_")
            Dim rowKey As String = App.MvField(thisEvent,3,"_")
            'ask the user
            'save this memberid for later retrieval
            Page.SetLocalStorage("memberid", rowKey)     'BANano.setLocalStorage
            'save the table row for later retrieval
            Page.SetLocalStorage("index", rowPos)
            'call a method existing in this application
            '_banano_atm_pgindex.deletemember();
            Dim onYes As String = Page.CallMethod(App.AppName,moduleName,"deletemember();")
            'code to generate the sweet modal confirm script (this returns javascript code only)
            Dim msg As String = Page.SweetModalConfirm($"Confirm Delete: ${rowKey}"$, _
            "Are you sure that you want to delete this record? You will not be able to undo your changes.", "_banano_atm_pgindex.deletemember();", "")
'same as banano.eval(javascript)
            Page.Execute(msg)

confirmdialog.png


#ExploringBANano

Update: 30 Jan 2019

A new method has been added to BANano as BANano.CallSub
 
Last edited:

Mashiane

Expert
Licensed User
Longtime User
Problem Statement

1. Publish to XAMPP and open the webapp in release mode
2. Publish to DirApp and open webapp in debug mode

I'm realizing that I have not been productive with my code, so I try out something that is working for me. On App_Start, i detect if I am in release or debug mode.
If release mode i build my app to the XAMPP folder and if in debug mode I build my my to File.DirApp. I want to open the webapp irrespective on the default browser

In Process_Globals...

B4X:
Private jx As JFX

Somewhere in App_Start of my app after I have added css and js files I have...

B4X:
Dim url As String
    #if release
        'save to xampp folder
        BANano.Build("C:\xampp\htdocs")
        url = $"http://127.0.0.1/${AppName}/index.html"$
    #else
        BANano.build(File.dirapp)
        Dim appPath As String = File.Combine(File.DirApp,AppName)
        url = File.GetUri(appPath,"index.html")
    #end if
    jx.ShowExternalDocument(url)
ExitApplication

This way either way of publishing works just like I want it. AppName is the 'short name' of my app.

Ta!
 

Mashiane

Expert
Licensed User
Longtime User
A collection of some of my quick methods to set/get element stuff on a banano project. This is specific to using the ID of an element.

B4X:
'change the image that shows to another using data url
Sub ChangeImage(imgid As String, dataurl As String)
    SetAttr(imgid,"src",dataurl)
End Sub

'banano empty call
Sub Empty(elID As String)
    elID = elID.tolowercase
    BANano.GetElement($"#${elID}"$).Empty
End Sub

'banano append call
Sub Append(elID As String, elContent As String)
    elID = elID.tolowercase
    BANano.GetElement($"#${elID}"$).Append(elContent)
End Sub

'banano settext call
Sub SetText(elID As String, elContent As String)
    elID = elID.tolowercase
    BANano.GetElement($"#${elID}"$).SetText(elContent)
End Sub

B4X:
'banano get the checked value
Sub GetChecked(elID As String) As Boolean
    elID = elID.tolowercase
    Return BANano.GetElement($"#${elID}"$).GetChecked
End Sub

'banano set the checked value
Sub SetChecked(elID As String, value As Boolean)
    elID = elID.ToLowerCase
    BANano.GetElement($"#${elID}"$).SetChecked(value)
End Sub

'banano setvalue call
Sub SetValue(elID As String, elContent As String)
    elID = elID.tolowercase
    BANano.GetElement($"#${elID}"$).SetValue(elContent)
End Sub

'banano get value call
Sub GetValue(elID As String) As String
    elID = elID.tolowercase
    Dim sValue As String = BANano.GetElement($"#${elID}"$).GetValue
    Return sValue
End Sub

'banano getstyle
Sub SetStyle(elID As String, elContent As String)
    elID = elID.tolowercase
    BANano.GetElement($"#${elID}"$).SetStyle(elContent)
End Sub

'banano addclass
Sub AddClass(elID As String, elContent As String)
    elID = elID.tolowercase
    BANano.GetElement($"#${elID}"$).AddClass(elContent)
End Sub

'banano set attribute
Sub SetAttr(elID As String, elProp As String, elContent As String)
    elID = elID.tolowercase
    BANano.GetElement($"#${elID}"$).SetAttr(elProp,elContent)
End Sub

B4X:
'get text value
Sub GetText(elID As String) As String
    elID = elID.tolowercase
    Dim elKey As String = $"#${elID}"$
    Dim sText As String = BANano.GetElement(elKey).GetText
    sText = sText.trim
    Return sText
End Sub

B4X:
'set values from elements and save as map
Sub SetValues(record As Map)
    For Each strfld As String In record.keys
        Dim strv As String = record.Get(strfld)
        BANano.GetElement($"#${strfld}"$).SetValue(strv)
    Next
End Sub

'set values to zero
Sub SetValuesToZero(flds As List)
    For Each strfld As String In flds
        BANano.GetElement($"#${strfld}"$).SetValue("0")
    Next
End Sub

'clear text fields
Sub ClearValues(flds As List)
    For Each strfld As String In flds
        BANano.GetElement($"#${strfld}"$).SetValue("")
    Next
End Sub


'get values from elements and save as map
Sub GetValues(flds As List) As Map
    Dim rec As Map
    rec.Initialize
    For Each strfld As String In flds
        Dim strv As String = BANano.GetElement($"#${strfld}"$).GetValue
        rec.Put(strfld,strv)
    Next
    Return rec
End Sub

B4X:
'get text value
Sub GetTextBox(elID As String) As String
    elID = elID.tolowercase
    Dim elKey As String = $"#${elID}"$
    Dim sText As String = BANano.GetElement(elKey).GetValue
    sText = sText.trim
    Return sText
End Sub

'set the text
Sub SetTextBox(elID As String, txtValue As String)
    elID = elID.ToLowerCase
    elID = $"#${elID}"$
    Dim el As BANanoElement = BANano.GetElement(elID)
    el.SetValue(txtValue)
End Sub

''set radiovalue by name
Sub SetRadio(elID As String,elValue As String)
    BANano.RunJavascriptMethod("setRadio",Array As String(elID,elValue))
End Sub

'get element by name
Sub GetElementByName(elID As String) As BANanoElement
    Dim el As BANanoElement = BANano.GetElement($"[name='${elID}']"$)
    Return el
End Sub

'get radiovalue by name
Sub GetRadio(elID As String) As String
    elID = elID.tolowercase
    Dim sValue As String  
    sValue = BANano.RunJavascriptMethod("getRadio",Array As String(elID))
    Return sValue
End Sub

B4X:
#If JavaScript
function setRadio(vRadioObj, vValue) {
    var radios = document.getElementsByName(vRadioObj);
    for (var j = 0; j < radios.length; j++) {
        if (radios[j].value == vValue) {
            radios[j].checked = true;
            break;
        }
    }
}

function getRadio(vRadioObj) {
    var radios = document.getElementsByName(vRadioObj);
    for (var j = 0; j < radios.length; j++) {
        if (radios[j].checked) {
            return radios[j].value;
        }

    }
    return "";
}
#End If

The code above for the radio boxes works based on the 'name' of the radio controls which could be multiple for the same name, so for radio controls the name is used and not the id. This is useful for radiogroup controls etc. One can also just write the javascript code above in BANano however at the end it will achieve the same result.

Ta!
 
Last edited:

Mashiane

Expert
Licensed User
Longtime User
The SetStyle method for BANano expects a JSON string. You can however have a wrapper for this that you can pass a map to and then it generates the required JSON string for SetStyle. Well, I find it easier to use.

First we need a method that one can pass a map and it generates a JSON string.

B4X:
'convert a map to a json string
Sub Map2Json(mp As Map) As String
    Dim JSON As BANanoJSONGenerator
    JSON.Initialize(mp)
    Return JSON.ToString
End Sub

So that we can then write our SetStyle method that we can use to set our element styles using a map.

B4X:
Sub SetStyle(elID As String, styleMap As Map)
    Dim strStyle As String = Map2Json(styleMap)
    banano.GetElement(elID).SetStyle(strStyle)
End Sub

Then we can use this as:

B4X:
SetStyle("th",CreateMap("font-weight": "bold", "background-color": "#acf",    "border-bottom": "1px solid #cef"))
    SetStyle("td,th", CreateMap("padding": "4px 5px"))

Works like a charm!

Ta!
 

Mashiane

Expert
Licensed User
Longtime User
You have created a form element with other input controls inside. This piece of code will serialize your form to an object i.e. Map

NB: Each element on the form MUST HAVE a name property.

B4X:
#if javascript
function Form2Json(form) {
    // convert form name value attributes to json
    var array = $(form).serializeArray();
    var json = {};
    $.each(array, function () {
        if (typeof json[this.name] == 'undefined') {
            json[this.name] = this.value || '';
        } else {
            json[this.name] += "," + this.value;
        }
    });
    return json;
}
#End If

Lets define the method to get the Form data and save it to a map variable.

B4X:
get the form data
Sub GetForm(frmName As String) As Map
    frmName = frmName.tolowercase
    Dim frmKey As String = $"#${frmName}"$
    Dim bo As BANanoObject = BANano.RunJavascriptMethod("Form2Json", Array(frmKey))
    Dim res As Map = bo.Result
    Return res
End Sub

Usage

B4X:
Dim fd As Map = GetForm("registerform")
log(fd)
 

Mashiane

Expert
Licensed User
Longtime User
BANanoSQL: Query an object / map based list

I had created a CRUD app before that was using localstorage as backend. The data was saved as a JSON structured list. This can be easily converted into a b4j list and then looped as demoed in the example contained here.

With this snippet example, one is able to query a map based b4j list using normal sql commands. The assumption is that you use a database in your app.

1. Define the database variable in process globals.

B4X:
Public abSQL As BANanoSQL

2. Open the database

B4X:
Sub BANano_Ready()
    'open db and create the tables
    abSQL.Open("abSQL", "testdb")
End Sub

3. When the database is opened, execute the code to query your list

B4X:
' database opening code should be after its opened
Sub abSQL_SQLOpened()
    Dim data As List
    data.Initialize
    data.Add(CreateMap("a":0))
    data.Add(CreateMap("a":1))
    data.Add(CreateMap("a":2))
    data.Add(CreateMap("a":3))
    data.Add(CreateMap("a":4))
    abSQL.ExecuteCallback("select * from ? where a >= ?",Array(data,2),Me,"test_list")
    End Sub

4. Trap the result..

B4X:
Sub test_list(success As Boolean, Result As List, Reason As String) 'ignore
    Log(success)
    Log(Result)
    Log(Reason)
End Sub

Output on the console.log of your browser

QueryList.png


Ta!
 

Mashiane

Expert
Licensed User
Longtime User
BANanoSQL: INSERT multiple records using a list

As per example in post #11, this snippet allows one to add multiple records on the table using a list.

Assumption: You have opened your database as per example above and then will create your table..

1. Open the database and trap the database open operation
B4X:
Sub abSQL_SQLOpened()
    Dim sql As String = "CREATE TABLE IF NOT EXISTS [appliance] ([name] STRING PRIMARY KEY, [type] STRING, [department] INT)"
    abSQL.ExecuteWait(sql,Null)
'build list of appliances to insert
    Dim appliances As List
    appliances.Initialize
    appliances.Add(CreateMap("name": "A", "type": "Fast"))
    appliances.Add(CreateMap("name": "B", "type": "Medium"))
    appliances.Add(CreateMap("name": "C", "type": "Slow"))
    Dim sql As String = "SELECT * INTO [appliance] FROM ?"
    abSQL.ExecuteCallback(sql,Array(appliances),Me,"multiple_inserts")

2. The callback..

B4X:
Sub multiple_inserts(success As Boolean, Result As List, Reason As String) 'ignore
    Log(success)
    Log(Result)
    Log(Reason)
End Sub

The Result variable in this case will return the "number" of affected records, in this case 3.

Ta!
 

Mashiane

Expert
Licensed User
Longtime User
Saving Text Content Generated from client side to a file.

Download Blob.js (this is for old browsers not having Blob, adding just in case)
Download FileSaver.js

This has the effect of the generated content to be automatically downloaded.

On AppStart

B4X:
BANano.Headers.AddJavaScriptFile("Blob.js")
BANano.Headers.AddJavaScriptFile("FileSaver.js")

In your button click code..

B4X:
Dim fc As List
fc.Initialize
fc.Add("Anele Mashy Mbanga")
Dim blob As BANanoObject
    Dim opt As Map = CreateMap("type": "text/plain;charset=utf-8")
    blob.Initialize2("Blob",Array(fc, opt))
    banano.RunJavascriptMethod("saveAs",Array(blob,ActiveTable & ".txt"))

Another option is just to run the javascript internally..

On button click..
B4X:
banano.RunInlineJavascriptMethod("saveTextFile",Array(fc,ActiveTable & ".txt"))

B4X:
#if javascript
    function saveTextFile(content, fileName) {
        var blob = new Blob(content, {type: "text/plain;charset=utf-8"});
        saveAs(blob, fileName);
    }
#End If

Ta!
 
Last edited:

Mashiane

Expert
Licensed User
Longtime User
BANanoSQL: Dropping An Existing Table

The tables i'm creating for my app can change their structure, so I need to DROP and recreate my tables.

We define the database for BANanoSQL...

B4X:
Public abSQL As BANanoSQL

Sub BANano_Ready()
    'open db and create the tables
    abSQL.Open("abSQL", "testdb")
End Sub

Then we need a way to check the table so we can drop it..

B4X:
'get the list of tables
    res = abSQL.ExecuteWait("SHOW TABLES",Null)
    Dim tblF As Int = res.IndexOf("mytable")
    If tblF >= 0 Then
        'delete the table first
        Dim sql As String = "DROP TABLE mytable"
        abSQL.ExecuteWait(sql,Null)
    End If
 

Mashiane

Expert
Licensed User
Longtime User
Inline PHP: Getting File Contents

Define the settings in AppStart..

B4X:
BANano.PHP_NAME = "myapp.php"
    BANano.PHPHost = "http://localhost/" & ShortName & "/"
    BANano.PHPAddHeader("Access-Control-Allow-Origin: *")

Add the function to read the file contents

B4X:
#if PHP
function GetFile($fileName) {
    echo file_get_contents($fileName);
}
#End if

Usage

B4X:
Dim result As String = banano.CallInlinePHPWait("GetFile",CreateMap("fileName":"./assets/appstart.txt"))
    Log(result)

Ta!
 

Mashiane

Expert
Licensed User
Longtime User
RadioGroup Manipulations

I have created a radio group, this shares the same name attribute, meaning that I can filter them, bind events to them, uncheck them etc.

First, we get an array of the radio elements by name using a filter...

B4X:
'get element by name
Sub GetElementsByName(elID As String) As BANanoElement()
    Dim el() As BANanoElement = BANano.GetElements($"[name='${elID}']"$)
    Return el
End Sub

You can also get a single element by name...

B4X:
Sub GetElementByName(elID As String) As BANanoElement
    Dim el As BANanoElement = BANano.GetElement($"[name='${elID}']"$)
    Return el
End Sub

So to uncheck all of them, i'm running..

B4X:
Sub CheckRadio(elementID As String, bStatus As Boolean)
    Dim els() As BANanoElement = GetElementsByName(elementID)
    For Each bo As BANanoElement In els
        bo.SetChecked(bStatus)
    Next
End Sub

To check the radio group by name and value

B4X:
''set radiovalue by name
Sub SetRadio(elID As String,elValue As String)
    Dim els() As BANanoElement = GetElementsByName(elID)
    For Each bo As BANanoElement In els
        Dim evalue As String = bo.GetValue
        If evalue.EqualsIgnoreCase(elValue) Then
            bo.SetChecked(True)
        End If
    Next
End Sub

And then to get the radio..

B4X:
'get radiovalue by name
Sub GetRadio(elID As String) As String
    Dim evalue As String = ""
    elID = elID.tolowercase
    Dim els() As BANanoElement = GetElementsByName(elID)
    For Each bo As BANanoElement In els
        Dim bChecked As Boolean = bo.GetChecked
        If bChecked Then
            evalue = bo.GetValue
            Exit
        End If   
    Next
    Return evalue
End Sub

The original javascript that was re-wrtten in BANano Syntax is..

B4X:
#if javascript
function setRadio(vRadioObj, vValue) {
    var radios = document.getElementsByName(vRadioObj);
    for (var j = 0; j < radios.length; j++) {
        if (radios[j].value == vValue) {
            radios[j].checked = true;
            break;
        }
    }
}

function getRadio(vRadioObj) {
    var radios = document.getElementsByName(vRadioObj);
    for (var j = 0; j < radios.length; j++) {
        if (radios[j].checked) {
            return radios[j].value;
        }

    }
    return "";
}
#End If

Ta!
 

Mashiane

Expert
Licensed User
Longtime User
Description: Scroll to a particular div on your page (animated)

I have a very long form thats broken into sections. I want when the user saves the content that the page is scrolled to the top of the page to a particular element.
As sections of my form are required, on validation, the page should scroll to that section too.

B4X:
'Scroll to a particular element on your page
'<code>
'ScrollToElement("txtName")
'</code>
Sub ScrollToElement(elID As String)
    elID = elID.ToLowerCase
    BANano.RunJavascriptMethod("scrollTo",Array(elID))
End Sub

#if javascript
    function scrollTo(elID){
        $('html, body').animate({
            scrollTop: $('#' + elID).offset().top - 100
        }, 500);
    }
#End If
 

Mashiane

Expert
Licensed User
Longtime User
GUID Generator & Test

I recently came across this javascript script because I need a way to have some UUID for my app.

Add the js to banano headers, i.e. uuid-random.min.js

B4X:
'generate guid
Sub GUID As String
    Dim res As String = BANano.RunJavascriptMethod("uuid",Null)
    Return res
End Sub

'test GUID
Sub IsGUID(res As String) As Boolean
    Dim bres As Boolean = BANano.RunJavascriptMethod("uuid.test",Array(res))
    Return bres
End Sub

So far so good!
 

Mashiane

Expert
Licensed User
Longtime User
Just for me to remember..

This will work perfectly..

B4X:
'exists
Sub Exists(tblName As String, primaryKey As String, primaryValue As String) As String
    Dim qw As Map = CreateMap()
    qw.Put(primaryKey, primaryValue)
    Dim qry As String = SelectWhere(tblName, Array(primaryKey), qw,Array(primaryKey))
    Return qry
End Sub

This wont, its better to explode maps where keys are variable names

B4X:
'exists
Sub Exists(tblName As String, primaryKey As String, primaryValue As String) As String
    Dim qry As String = SelectWhere(tblName, Array(primaryKey), createmap(primaryKey:primaryValue),Array(primaryKey))
    Return qry
End Sub

B4X:
'return a sql to select record of table where one exists
Sub SelectWhere(tblName As String, tblfields As List, tblWhere As Map, orderBy As List) As String
    Dim listOfTypes As List = GetMapTypes(tblWhere)
    Dim listOfValues As List = GetMapValues(tblWhere)
    'are we selecting all fields or just some
    Dim fld1 As String = tblfields.Get(0)
    Dim selFIelds As String = ""
    Select Case fld1
        Case "*"
            selFIelds = "*"
        Case Else
            selFIelds = JoinFields(",", tblfields)
    End Select
    Dim sb As StringBuilder
    sb.Initialize
    sb.Append($"SELECT ${selFIelds} FROM ${EscapeField(tblName)} WHERE "$)
    Dim i As Int
    Dim iWhere As Int = tblWhere.Size - 1
    For i = 0 To iWhere
        If i > 0 Then
            sb.Append(" AND ")
        End If
        Dim col As String = tblWhere.GetKeyAt(i)
        sb.Append(col)
        sb.Append(" = ?")
    Next
    If orderBy <> Null Then
        'order by
        Dim stro As String = JoinFields(",", orderBy)
        If stro.Length > 0 Then
            sb.Append(" ORDER BY ").Append(stro)
        End If
    End If
    Dim m As Map
    m.Initialize
    m.Put("sql", sb.tostring)
    m.Put("args", listOfValues)
    m.Put("types", listOfTypes)
    m.Put("command", "selectwhere")
    Dim res As String = Map2Json(m)
    Return res
End Sub
 

Mashiane

Expert
Licensed User
Longtime User
How to return the ID of the current currentTarget of the BANanoEvent

The currentTarget is defined as : Get the element whose event listeners triggered a specific event:

When clicked, the e BANanoEvent returns the currentTarget which is a string. If this has an ID that you want to read, you can retrieve that id by using another method. You need to use the otherfield property of the event. This sub helps in just doing that.

B4X:
Sub GetIDFromEvent(e As BANanoEvent) As String
    Dim curEve As BANanoElement = BANAno.ToElement(e.OtherField("currentTarget"))
    Dim id As String = curEve.GetField("id").Result
    Return id
End Sub

Ta!
 
Top