samedi 31 août 2019

Selenium Python 3.7.4 - Series of Checkboxes can't be found by xpath on type and name

I'm trying to develop a bot that automatically handles the deletion of various posts from a website. I have stumbled across a major problem which does not allow me to proceed any further.

The page I've achieved to open presents various checkboxes with the following input:

<input type="checkbox" name="ids[]" value="305664759" onclick="toggleDeleteButtons()">


What I have to do is check simultaneously each checkbox and then click on delete button. Then a popup will appear, where I have to click "Delete" with the following input:

<input id="btnDelAds" class="button" href="javascript:void(0)" onclick="document.manageads.cmd.value='del';if (submit_batch_delete()){document.manageads.submit();}else{closeDialogDelete();}">


And then another popup will appear for confirming, but that's another problem. In fact, the troubles come when I try to find the checkboxes.

This is the code for handling the first part of the site, and findind the checkboxes:

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys

#HANDLING ACCESS
email = "somemail"
password = "somepass"
driver = webdriver.Firefox()
driver.get("https://www.somesite.it/account/manageads")
login_field = driver.find_element_by_id("login_email")
login_field.clear()
login_field.send_keys(email)
login_field = driver.find_element_by_id("login_passwd")
login_field.clear()
login_field.send_keys(password)
login_field.send_keys(Keys.ENTER)

#HANDLING DELETE OF POSTS
while True:
    try:
        elem = driver.find_element_by_xpath("//input[@type='checkbox' and contains(@name, 'id')")
        print("Found")
    except NoSuchElementException:
        print("End")
        break
    elem.click()

(I've censored site url and credentials)

print("Found") clause is obviously not executed. The idea was to check consecutively every checkbox, probably I've done this in the wrong way.

What I get instead is "END" in console. Any help will be strongly appreciated. Thanks in advance.




Select all checkbox only works some of the time

I have a form with checkboxes, along with a hidden select all button inside the form. I use jquery to listen for a button click outside the form, and then "click" the hidden button element to select all. Sometimes the page loads up and I click the button and it works perfectly. You can click it multiple times and they all check and uncheck as intended. The form submits perfectly.

Other times, however, the page will load up and I click the button and nothing happens. They don't check no matter how many times I click. I've found this happens a lot if the page sits for more than maybe 10 seconds without me doing anything. But it also can happen on page load. I can't understand why. Is there an error in my code somewhere that I'm just not seeing?

<button id="selectAll" class="btn btn-secondary my-2 my-sm-0"
                type="button" name="selectAll">Select All</button>


<form>
<input type="checkbox" id="1"><label for="1" class="choice">ABC</label>
<input type="checkbox" id="2"><label for="2" class="choice">DEF</label>
  (....etc.....)

<input type="checkbox" id="select-all" style="display: none;">
            <input type="submit" style="display: none;">

        </form>


$(document).ready(function(){
    $('#select-all').click(function(event) {
        if(this.checked) {
            // Iterate each checkbox
            $(':checkbox').each(function() {
                this.checked = true;
                $('label.choice').toggleClass("choice-text-color");
            });
        } else {
            $(':checkbox').each(function() {
                this.checked = false;
                $('label.choice').toggleClass("choice-text-color");
            });
        }
     });

    $("#selectAll").click(function() {
            $('#select-all').click()
    });
});





StateListAnimator not working on checkbox

I am following the article given here

I am trying to create a "like" button animation and need help since my animator does not seem to be doing anything

I have created the required animator file, created the stateListDrawable file and set it as the background to the CheckBox The animator file uses a set of objectAnimator tags which animate the scaleX, scaleY and translationZ properties.

This is my layout file "activity_main.xml"

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout    
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:background="@android:color/white"
android:layout_height="match_parent"
tools:context=".MainActivity">

<CheckBox
    android:id="@+id/checkbox"
    android:button="@null"
    android:checked="false"
    android:background="@drawable/like_icon"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:stateListAnimator="@animator/scale2"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout> 

This is the stateListDrawable "like_icon.xml"

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/ic_thumb_up_red_24dp" 
android:state_checked="true" />

<item android:drawable="@drawable/ic_thumb_up_black_24dp" />
</selector>

This is my animator named "scale.xml". It is placed correctly in the "res/animator/" folder

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

<objectAnimator
    android:duration="@android:integer/config_longAnimTime"
    android:propertyName="scaleX"
    android:valueTo="1.525"
    android:valueType="floatType" />

<objectAnimator
    android:duration="@android:integer/config_longAnimTime"
    android:propertyName="scaleY"
    android:valueTo="1.525"
    android:valueType="floatType" />

<objectAnimator
    android:duration="@android:integer/config_longAnimTime"
    android:propertyName="translationZ"
    android:valueTo="4dp"
    android:valueType="floatType" />

<objectAnimator
    android:duration="@android:integer/config_longAnimTime"
    android:propertyName="scaleX"
    android:valueTo="1.0"
    android:startOffset="@android:integer/config_longAnimTime"
    android:valueType="floatType" />

<objectAnimator
    android:duration="@android:integer/config_longAnimTime"
    android:propertyName="scaleY"
    android:startOffset="@android:integer/config_longAnimTime"
    android:valueTo="1.0"
    android:valueType="floatType" />

<objectAnimator
    android:duration="@android:integer/config_longAnimTime"
    android:propertyName="translationZ"
    android:startOffset="@android:integer/config_longAnimTime"
    android:valueTo="0dp"
    android:valueType="floatType" />

</set>




vendredi 30 août 2019

How to check and unchecked all checkbox using header checkbox?

I am trying to check and unchecked all my checkbox using a single check box in my header, this works fine on the first round but stops working afterword

I have tried the following code including .each() function

<input type="checkbox" id="allcenter"><label for="allcenter">All</label>

<input type="checkbox" class="dassoc_cen" value="1" id="dassoc_cen1">                                   
<label for="dassoc_cen1">Cen 1</label>

<input type="checkbox" class="dassoc_cen" value="1" id="dassoc_cen1">                                   
<label for="dassoc_cen1">Cen 1</label>

<input type="checkbox" class="dassoc_cen" value="3" id="dassoc_cen3">                                   
<label for="dassoc_cen3">Cen 3</label>

<script>
    $('#allcenter').on('click',function(){
        if($(this).is(':checked')){
            $('.dassoc_cen').attr("checked",true);
        }else{
            $('.dassoc_cen').attr("checked",false);
        }
    })
</script>

If i check and uncheck the header checkbox for the first time the system works fine but after first round the html attribute "checked" of other checkbox becomes "checked" but it does not reflect it self in browser




Angular checkbox state check fires too often

In my UI, I have too many checkboxes arranged in the form of a grid. Their checked status should be determined from the one time logic which is present in the component. Once updated their status are never going to get changed.

I have updated the checked status by calling a function as below.

[checked]="getCheckedStatus()"

Simplified problem is present in this stackblitz - https://stackblitz.com/edit/angular-o622bw?embed=1&file=src/app/app.component.html

Problem - console.log() (or say getCheckedStatus()) gets fired too often whenever Update button is clicked which is slowing down the performance.




Check box binds correctly but can't check or uncheck

In my custom Kendo grid popup editor, the check box binds correctly but can’t be checked or unchecked.

I could not find any posts relating to this issue. I have tried the Keno check box (remarked out) and plain html. I also tried to toggle the checkbox with an onclick JavaScript function, but that did not work either. When you hover over the check box or label the cursor does change to a hand which indicates that it should allow me to click it. The check box in my model is defined as public bool Active { get; set; }

I have the same issue when I use the default Kendo popup editor

@model Durendal.Core.ViewModels.Entities.Sku.SkuViewModel

<div class="row">
    <div class="col">
        <input asp-for="Id" type="hidden" />
        <div class="md-form md-bg">
            <input asp-for="BusinessLineName" class="form-control" />
            <label for="BusinessLineName" class="active">Business Line</label>
        </div>
        <div class="md-form md-bg">
            <input asp-for="Number" class="form-control" />
            <label for="Number" class="active">Number</label>
        </div>
        <div class="md-form md-bg">
            <input asp-for="Name" class="form-control" />
            <label for="Name" class="active">Name</label>
        </div>
        <div class="md-form md-bg">
            <input asp-for="Upc" class="form-control" />
            <label for="Upc" class="active">Upc</label>
        </div>

        @*<div class="editor-label">
                @Html.LabelFor(model => model.Active)
            </div>
            <div class="editor-field">
                @(Html.Kendo().CheckBox().Name("Active"))
            </div>*@

        <div class="form-check">
            <input type="checkbox" class="form-check-input" name="Active" id="Active" value="true">
            <label class="form-check-label" for="Active">Active?</label>
        </div>


    </div>
</div>

@(Html.Kendo()
            .Grid<Durendal.Core.ViewModels.Entities.Sku.SkuViewModel>()
            .Name("grid")
            .Columns(columns =>
            {
                columns.Bound(s => s.BusinessLineName).Width(60);
                columns.Bound(s => s.Number).Width(50);
                columns.Bound(s => s.Name).Width(140);
                columns.Bound(s => s.Upc).Width(70);
                columns.Bound(s => s.Active).Width(30)
                .ClientGroupHeaderTemplate("# if (value == true) {# Active #} else {# Inactive #} # (Count: #= count#)");
                columns.Command(command => { command.Edit(); command.Destroy(); }).Width(90);
            })
            .ToolBar(toolbar => toolbar.Create())
            .Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("_Sku"))
            .Pageable()
            .Sortable()
            .Scrollable()
            .HtmlAttributes(new { style = "height:430px;" })
            .DataSource(dataSource => dataSource
                .Ajax()
                .PageSize(40)
                .Aggregates(aggregates =>
                {
                    aggregates.Add(s => s.Active).Count();
                })
                .Group(groups => groups.AddDescending(s => s.Active))
                .Sort(sort =>
                {
                    sort.Add("Number").Ascending();
                })
                .Events(events => events.Error("error_handler"))
                .Model(model => model.Id(s => s.Id))
                .Create(update => update.Action("EditingPopup_Create", "Grid"))
                .Read(read => read.Action("SkuGrid_Read", "Customer", new { Id = Model }))
                .Update(update => update.Action("SkuGrid_Update", "Customer"))
                .Destroy(update => update.Action("SkuGrid_Destroy", "Customer"))
            )
)




Parsing a string array from a JSON file into global variable, but when using it the array content is null

I have a JSON file with different Strings I want to create an altert dialog, but my String array is not working

I created a private String category. Into the category String I parse my String values with a for loop, in the method getJobArray. There the LogCat output tells me that the array gets filled with the String values. However, when I use the category String array in the onCreateDialog it tells me that the values are all null. I cannot even print the length to the LogCat

public class MultipleChoiceDialogFragment extends DialogFragment {

    private RequestQueue mRQ;
    private Context mContext;
    private RequestQueue mRequestQ;
    private static String TAG = "xd";
    private String[] category;


    public interface onMultiChoiceListener{
        void onPositiveClicked(String[] list,ArrayList<String> selectedItemList);
        void onNegativeButtonClicked();
    }

    onMultiChoiceListener mListener;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        mRequestQ = Volley.newRequestQueue(context);
        getJobArray();

        try {
            mListener = (onMultiChoiceListener) context;
        }catch (Exception e){
            throw  new ClassCastException(getActivity() + "onMultiChoice not working error");
        }
    }



    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        final ArrayList<String> selectedItemList = new ArrayList<>();



        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());



        //not working don't understand why... here category is null
        final String[] list = category;

        builder.setTitle("Select one")
                .setMultiChoiceItems(list, null, new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i, boolean b) {
                        if(b){
                            selectedItemList.add(list[i]);
                        }else{
                            selectedItemList.remove(list[i]);
                        }
                    }
                })
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mListener.onPositiveClicked(list,selectedItemList);

                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mListener.onNegativeButtonClicked();
                    }
                });

        return builder.create();
    }



    private void getJobArray(){
        //todo here I can get array from json array

        String url = "http://api_staging.jab.poweredby.cnddts.at/mobile/metadata/categories?portal=1";
        JsonObjectRequest request = new JsonObjectRequest(com.android.volley.Request.Method.GET, url, null,
                new com.android.volley.Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        try {
                            JSONArray jsonArray = response.getJSONArray("categories");

                            category = new String[jsonArray.length()];

                            Log.d(TAG, "onResponse: is getting array ready right now");
                            Log.d(TAG, "onResponse: jsonArray length" + jsonArray.length());
                            for(int i = 0; i < jsonArray.length(); i++){
                                JSONObject categories = jsonArray.getJSONObject(i);

                                category[i] = categories.getString("name");

                                Log.d(TAG, "onResponse: array input " + category[i]);

                            }


                        } catch (JSONException e) {
                            e.printStackTrace();
                            Log.d(TAG, "onResponse: catch caught...");
                        }

                    }
                }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        mRequestQ.add(request);
    }
}




jeudi 29 août 2019

How to disable checkbox of a row in kendo grid using javascript function

I have a kendo grid where columns are defined and 2 columns are checkbox type. based on some validation in the comments row data, I want to disable the checkbox of that particular row in the grid. I have a separate javascript function that I am using for validation but I am not able to disable the checkbox of that row. I am adding both the kendo grid code and the javascript function.



 createGrid: function (data) {
            $("#ProductGrid").kendoGrid({
                dataSource: {
                    data: tableData
                },
                columns: [        

                    { field: "Accept", tilte: commonLib.readMessageByUserLanguage(COLUMNTITLENAME.Accept), "template": "<input type=\"checkbox\" />" },
                    { field: "Decline", tilte: commonLib.readMessageByUserLanguage(COLUMNTITLENAME.Decline), "template": "<input type=\"checkbox\" />" },
                    { field: "Item", tilte: commonLib.readMessageByUserLanguage(COLUMNTITLENAME.Item) },
                    { field: "PartID", title: commonLib.readMessageByUserLanguage(COLUMNTITLENAME.PartID) },
                    { field: "Description", title: commonLib.readMessageByUserLanguage(COLUMNTITLENAME.Description), width:'300px' },
                    { field: "SubPart", title: commonLib.readMessageByUserLanguage(COLUMNTITLENAME.SubPart) },
                    { field: "SubPartDescription", title: commonLib.readMessageByUserLanguage(COLUMNTITLENAME.SubPartDescription) },
                    { field: "BusinessPartner", title: commonLib.readMessageByUserLanguage(COLUMNTITLENAME.BusinessPartner) },
                    { field: "ReqDelTM", title: commonLib.readMessageByUserLanguage(COLUMNTITLENAME.ReqDelTM) },
                    { field: "EarDelTM", title: commonLib.readMessageByUserLanguage(COLUMNTITLENAME.EarDelTM) },
                    { field: "EarDelDate", title: "Ear Del Date", hidden: true },
                    { field: "Comments", title: commonLib.readMessageByUserLanguage(COLUMNTITLENAME.Comments) },

                ]
            });
        },



    checkComments: function () {
var productGrid = $("#ProductGrid").data("kendoGrid");
        var productGridData = productGrid.dataSource;
        var noofproduct = productGridData.data().length;
        var dataList = productGridData.data();  

            for (var i = 0; i < noofproduct; i++)
            {

                if (dataList[i].Comments == "Date not met")
                {
                    (dataList[i].Accept.enable(false));                     

                }
            }
}




How can i add multiple expand tile with checkbox list tile using Json in flutter

this json has two data first only name and second is inside there also name which is service name. ex 'Travel and Stay' and 'Religious' is main name which has to be displayed in expansion tile name and The 'Church/ Baptism' and 'Hindu Temples' is a subitem which is displayed inside checkbox list tile. Hope you understand :slightly_smiling_face: Please Help me

class _MyHomePageState extends State<MyHomePage> {
  var lovCountryServices = [
    {
      "services": [
        {
          "service_group_id": 22,
          "service_category": "B",
          "name": "Air Tickets",
          "id": 228
        },
        {
          "service_group_id": 22,
          "service_category": "W",
          "name": "Boys Hostel",
          "id": 229
        },
      ],
      "name": "Travel and Stay",
      "is_active": true,
      "id": 22
    },
    {
      "services": [
        {
          "service_group_id": 19,
          "service_category": "B",
          "name": "Church/ Baptism",
          "id": 193
        },
        {
          "service_group_id": 19,
          "service_category": "B",
          "name": "Hindu Temples",
          "id": 194
        }
      ],
      "name": "Religious",
      "is_active": true,
      "id": 19
    }
  ];
  List<_Result> _results = [];

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
          child: Column(
        children: <Widget>[
          ListView.builder(
            shrinkWrap: true,
            padding: const EdgeInsets.all(8.0),
            itemCount: lovCountryServices.length,
            itemBuilder: (BuildContext context, int index) {
              var item = lovCountryServices[index];
              var items= lovCountryServices[index]['services'];
              return ExpansionTile(
                title: Text(item['name']),
                children: <Widget>[
                  CheckboxListTile(
                    title: Text("temp"),
                    value: item['is_active'],
                    onChanged: (val) {
                      setState(() {
                        item['is_active'] = val;
                      });
                    },
                  ),
                ],
              );
            },
          ),
          RaisedButton(
            onPressed: () => print("sending to backend"),
            child: Text("SEND"),
          )
        ],
      )),
    );
  }
}

I want thw data in checkbox list tile right there is dummy data called TEMP and i want the data from json right now in json there is 'Boys Hostel' this data needs to comes inside the checkbox listtile. Hope you undestand please help me




In my Angular 7 application, using reactive forms..Change this checkbox value to '1' if checked, change value to null if unchecked

I need to change this checkbox value to '1' if it is checked and null if it is unchecked

<div class="form-check col-md-12">

  <input 
    class="form-check-input" 
    formControlName="parentsSsi" 
    id="parentsSsi" 
    type="checkbox" 
    value="1" 
    (change)="unselectNoneOfTheAbove(); 
    checkedBoxValueIsOne()"
   >

</div>

In my TS file:

  unselectNoneOfTheAbove() {
    this.pfinancialSectionSix.patchValue({
      parentsNoneOfTheAbove: null
    });
  }

  // change value of checked check box to '1' if checked
  checkedBoxValueIsOne() {
    if(this.pfinancialSectionSix.controls.parentsSsi.value === null || 
    !this.pfinancialSectionSix.controls.parentsSsi.value){
      this.pfinancialSectionSix.patchValue({
      parentsSsi: '1'
    })
  }
    if(this.pfinancialSectionSix.controls.parentsSsi.value || 
      this.pfinancialSectionSix.controls.parentsSsi.value !== null) {
        this.pfinancialSectionSix.patchValue({
        parentsSsi: null
      })
    }
    console.log('checkbox value: ', this.pfinancialSectionSix.controls.parentsSsi.value)
  }

Currently, it only stays as null, but should toggle between '1' and null if it is checked or unchecked.




Selecting an input within a label in CSS?

I have a problem selecting input element when it's inside a label usually something like this:

<label>
    <input type="checkbox" />
</label>

When i try to do something like that in CSS:

input: checked ~ ul {
    #Some styling here
}

it doesn't work, im new to this and i hope u could help me!




Excel VBA check multiple checkboxes

I have 2 checkboxes within my Excel sheet; option1 and option2. I am wishing to run a macro to check if option1 is selected, option2 is selected, or neither of them is selected.

Once I have checked if the checkboxes are selected I will then do the following:

  • 'option1' - Dispay message relating to option 1

  • 'option2' - Display message relating to option 2

  • neither selected - display a message that neither was selected

These will then be sent out as an email with the text corresponding to option 1 or option 2.

-

-

Here is an attempt of code I made, but not complete

If Sheet1.CheckBox1.Value = True Then

SEND OPTION1 RELATED CONTENT

    ElseIf
    Sheet1.CheckBox2.Value = True Then

SEND OPTION2 RELATED CONTENT

Else **neither option1 or option2 selected --not sure on this**
    Sub MsgBoxCriticalIcon()
    MsgBox "You must select an option", vbCritical
    End Sub
End If

Here is my working code without my attempts inserted..

Sub Email_VBA()


    Dim OlApp As Object
    Dim NewMail As Object
    Dim TempFilePath As String
    Dim FileExt As String
    Dim TempFileName As String
    Dim FileFullPath As String
    Dim MyWb As Workbook


    Set MyWb = ThisWorkbook

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    'Save your workbook in your temp folder of your system
    'below code gets the full path of the temporary folder
    'in your system

    TempFilePath = Environ$("temp") & "\"
    'Now get the extension of the file
    'below line will return the extension
    'of the file
    FileExt = "." & LCase(Right(MyWb.Name, Len(MyWb.Name) - InStrRev(MyWb.Name, ".", , 1)))
    'Now append a date and time stamp
    'in your new file

    TempFileName = MyWb.Name & "-" & Format(Now, "dd-mmm-yy h-mm-ss")

    'Complete path of the file where it is saved
    FileFullPath = TempFilePath & TempFileName & FileExt

    'Now save your currect workbook at the above path
    MyWb.SaveCopyAs FileFullPath

    'Now open a new mail

    Set OlApp = CreateObject("Outlook.Application")
    Set NewMail = OlApp.CreateItem(0)




    On Error Resume Next
    With NewMail
        .To = "ashley@hotmail.com"
        .CC = ""
        .BCC = ""
        .Subject = "NEW Type your Subject here"
        .Body = "NEW Type the Body of your mail"
        .Attachments.Add FileFullPath '--- full path of the temp file where it is saved
        .Display   'or use .Display to show you the email before sending it.
    End With
    On Error GoTo 0

    'Since mail has been sent with the attachment
    'Now delete the temp file from the temp folder

    Kill FileFullPath

    'set nothing to the objects created
    Set NewMail = Nothing
    Set OlApp = Nothing

    'Now set the application properties back to true
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With


End Sub

The end result being both checkboxes are checked and a message being sent in Outlook related to the option chosen. Or if neither are chosen the user is prompted to choose an option.

Feel free to ask any questions & thanks for your help

Kind regards




Shortest way to count the checked attributes

I have a list of checkbox in AEM When we hit the checkbox the checked attribute will be placed on the parent element, not in the input box. I want the count how many are checked

$('.isCorrectanswer').attr('checked').length;
<coral-checkbox class="isCorrectanswer" checked>
    <input type="checkbox" name="./checkboxone" />
    <label>checkbox</label>
  </coral-checkbox>
  <coral-checkbox class="isCorrectanswer" checked>
    <input type="checkbox" name="./checkboxtwo" />
    <label>checkbox</label>
  </coral-checkbox>
  <coral-checkbox class="isCorrectanswer">
    <input type="checkbox" name="./checkboxthree" />
    <label>checkbox</label>
  </coral-checkbox>
  <coral-checkbox class="isCorrectanswer">
    <input type="checkbox" name="./checkboxfour" />
    <label>checkbox</label>
  </coral-checkbox>
  <coral-checkbox class="isCorrectanswer">
    <input type="checkbox" name="./checkboxfive" />
    <label>checkbox</label>
  </coral-checkbox>

This is not working for me...




mercredi 28 août 2019

Validate time in relation to a checkbox is checked or not?

I have 3 input fields (reservationdate, starttime, endtime) and 1 checkbox (holeday). If the checkbox clicked I do not need starttime and endtime. On the other hand starttime and endtime is required. What can I do to solve this task?

I tried in Laravel the required_if validation-function. But I'm certainly using it wrong

ReservationController store:

    $data = $request->validate([
            'userid' => 'required|numeric',
            'vehicleid' => 'required|numeric',
            'budgetid' => 'required|numeric',
            'reservationdate' => 'required|date',
            'starttime' => 'required_if:holeday,on|date_format:H:i|before_or_equal:endtime',
            'endtime' => 'date_format:H:i',
            'holeday' => 'boolean'
        ]);


index.blade.php (only the checkbox)
            <div class="input-field col s2">
                <label>
                    <input type="checkbox" name="holeday" class="filled-in"  />
                    <span>Hole Day</span>
                  </label>
             </div>

If the checkbox is checked I get the error-message "The starttime field is required when holeday is on." but in this case I need no error. Hey user it is OK. I don´t need a starttime or endtime. Your clicked the holeday.




How to add List view with dynamic selection checkbox inside expansion tile in flutter

I am facing problem to add listview with checkbox inside multiple ExpansionTile. Also, a checkbox has to be dynamically selection.

In this images I've created one expansion tile and inside I had put list tile with checkbox but when I am adding multiple expansion tile all are either selected or not selected based on value but i want to select user wanted value it means it should be dynamically

body: ExpansionTile(
      title: Text("Expansion"),
      children: _listViewData
          .map((data) => CheckboxListTile(
                title: Text(data),
                value: _isChecked,
                onChanged: (val) {
                  setState(() {
                    _isChecked = val;
                  });
                },
              ))
          .toList(),
    ));

Here is the image




How to uncheck a checked asp:CheckBox when another is checked in an asp:GridView

I have an asp:CheckBox column in an asp:GridView. I am trying to uncheck previously checked CheckBox when another one is checked using javascript. I have seen code dealing with 2 checkboxes but not in an asp:gridview. I am new to javascript so any help would be appreciated.

Here is the HTML code:

<asp:GridView ID="GridViewGroups" runat="server" >
   <Columns>
       <asp:TemplateField>
          <ItemTemplate>
            <asp:CheckBox ID="chkRow2" class="icheckbox" runat="server" />                                                                                                                                 
           </ItemTemplate>
        </asp:TemplateField>
    </Columns>                                                                                
</asp:GridView>   




How to prevent an asp:CheckBox control in an asp:GridView from causing postback when checked

I have an asp:CheckBox in an asp:GridView that causes postback when checked. I'd like to prevent postback. I'd also like to know why the same control doesn't cause postback when it's in an asp:Panel(ModalPopExtender)

<asp:GridView ID="GridViewGroups" runat="server" class="table table-striped table-bordered sourced-data dataTable "OnRowDataBound="GridViewGroups_RowDataBound" >
   <Columns>
     <asp:TemplateField>
      <ItemTemplate>
        <asp:CheckBox ID="chkRow2" class="icheckbox_polaris" runat="server" AutoPostBack="false" />
          </ItemTemplate>
       </asp:TemplateField>
     </Columns>                                                                                
</asp:GridView> 




mardi 27 août 2019

bootstrap data-toggle checkbox on datatable

I have an issue with bootstrap data-toggle checkbox on data table .In data tables first page it's working fine , but in next page or any other page except first page it is seeing like normal checkbox .

this is my code for data-toggle checkbox,

                                    <input type="checkbox" name="offer_status" data-toggle="toggle" data-on="Active" data-off="Hidden" data-onstyle="success" data-offstyle="danger" class="stat" value="<?php echo $row->status; ?>" onchange="getid(<?php echo $row->id; ?>)">




Why isn't checkbox B enabled when I check checkbox A?

I have two checkboxes, A and B. They should behave according to the following rules:

  1. A should always be enabled.
  2. B should only be enabled when A is checked
  3. If A and B is checked, and A is later un-checked, B should be un-checked and disabled automatically.

I have this code so far:

HTML

<input type="checkbox" id="A" />A
<input type="checkbox" id="B" />B

jQuery

$('#A').change(function () {
    if ($(this).attr("checked")) {
        $('#B').attr('disabled', false)
    } else {
        $('#B')
            .attr('disabled', true)
            .attr('checked', false);
    }
}).change();

Fiddle here.




Semantic ui react get multiple checked values from checkbox

Im trying to allow user to checked all values from checkbox in react with semantic-ui-react and Im new in react. Here's my code

class ListHandOver extends React.Component {
   state = {
     data: {}
   }

   handleChange = (e, data) => {
      console.log(data);
      this.setState({ data });
   }

   render(){
       const { listdata } = this.props;
       return(
         <div>
            { listdata.map(order => 
                <Checkbox
                   slider
                   id={order.orderid}
                   checked = { this.state.data.id === order.orderid }
                   onChange={this.handleChange}
                /> 
            )}
         </div>
       );
   }
}

ListHandOver.propTypes = {
   listdata: PropTypes.array.isRequired
}

export default ListHandOver;


But I only can check one values not multiple. How to allow user to check multiple checkbox?


Thanks




Change the size of angular material checkbox (mat-checkbox)

I'm trying increase the size of the material checkbox.

Transform seems to increase the size of the material checkbox. However, I'm not sure if this is a correct way to achieve that?

CSS

::ng-deep .mat-checkbox .mat-checkbox-frame {
    transform: scale(2);
}

::ng-deep .mat-checkbox-checked .mat-checkbox-background {
    transform: scale(2);
}




Correct binding CheckBox binding MVVM

I'm very new to the WPF world, and have noticed that I have big problems binding a CheckBox in the MVVM pattern.

I know questions about binding CheckBox have been asked here very often, but I can't find a correct solution for binding CheckBox.

Can anyone show me a good example?




Save multiple checkbox values to sql database

I have a html form, and i have also checkboxes in it. Values of checkboxes is coming from SQL-database via Web Api.

         $(document).ready(function () {
        var $MaterialName = $('#materiallist');  

        function addMaterials(material) {
            $MaterialName.append('<input type="checkbox" >' + material.MaterialName + ' </input>');
        }

       <div class="form-group">
        <label for="material" class="col-xs-3 control-label 
                      header">Käytetyt materiaalit</label>
         <div class="col-xs-7">
           <div class="checkbox" id="materiallist"></div>
         </div>
       </div>

I want to save those checked values to another SQL-database (named Form), along with the other input values in that form.

I haven't found a solution where all the other input fields also needs to be saved as well, only solutions where is only checkboxes and button. And also that my values are coming from database, not "hard-code" options. I tried this:

   function getCheckedMaterials() {
            var materialArray = [];
            $("#materiallist input:checked").each(function () {
                materialArray.push($(this).val());
            });
            var selected;
            selected = materialArray.join(',');
            alert("You have selected " + selected);
        }

But it doesn't work as i need, because i can't get values..

All these values from another input fields goes to Form-database when i press button #tallenna. I need checked values to be saved in MaterialName-column as text.

     $('#tallenna').click(function () {
                var form = {
                    FormFiller: $FormFiller.val(),
                    CustomerContact: $CustomerContact.val(),
                    ReadyToDate: $ReadyToDate.val(),
                    Instructions: $Instructions.val(),
                    Amount: $Amount.val(),
                    PcsAmount: $PcsAmount.val(),
                    ChargeFull: $ChargeFull.val(),
                    ChargeByPcs: $ChargeByPcs.val(),
                    FreightCost: $FreightCost.val(),
                    CustomerName: $CustomerName.val(),
                    WorkName: $WorkName.val(),
                    MaterialName: getCheckedMaterials // ???? 
                };




jQuery DataTables checkboxes extension can not retrive selected data correctly at IE browser

I use jQuery datatables checkboxes extention to give my talbe multi select function. when any row's checkbox clicked, I retieve all selected row's first cell's data send to server.

the code work at Chrome browser, but not work at IE browser.

   $(document).ready(function () {      
        var table = $('#tbl_inv').DataTable({
            "paging": false,
            //"ordering": false,
            "info": false,
            "searching": false,
            'columnDefs': [
                {
                    'targets': 0,
                    'checkboxes': {
                        'selectRow': true
                    }
                }
            ],
            'select': {
                'style': 'multi'
            },
            'order': [[1, 'asc']]
        });


        $('#tbl_inv input[type="checkbox"]').on('change', function () {
            $.ajax({
                url: '/Invoices/Pickup?handler=CalcTotaltoPay',
                data: {
                    invIds: $('#tbl_inv').DataTable().column(0).checkboxes.selected().join(),
                    clientId:1234
                }
            })
                .done(function (result) {
                    freshResult(result);
                });

            // Iterate over all selected checkboxes
            //$.each(table.column(0).checkboxes.selected(), function (index, rowId) {
            //    console.log(index + '---' + rowId)
            //    console.log(table.cell(index, 5).data())
            //});
        });
});


when use IE browser, .column(0).checkboxes.selected() return a list, this list not include current clicked checkbox state change. meaning, when checkbox checked, .column(0).checkboxes.selected() return a list not include current checkbox's data. when checkbox unchecked, .column(0).checkboxes.selected() return a list still include this checkbox's data.




Update status in database using checkbox - Laravel

The project can have different statuses. With the checkbox, I am trying to switch the status of the project from requested (1) to accepted (2). If the checkbox is unchecked the status is 1, checked it's 2.

When I check the checkbox I got a 419 but this is normally related to the token but I added a @csfr field. Why is the status not changed in the database? Thanks for any help.

index.blade.php (summary of all the projects)

 @foreach ($projects as $project)

        <tbody>
            <tr>
                <form action="/projects/plan" method="post" id="statusForm">
                 @csrf
                    <input name="id" type="hidden" value="">
                    <td>
                        <input type="hidden" value="" name="status"> 
                        <input  
                                value="" type="checkbox" name="status" 
                                onchange="document.getElementById('statusForm').submit()"
                        >
                    </td>
                </form>
                <td></td>
                <td></td>
                <td><a href="/events//edit" class="btn btn-secondary btn-sm" role="button">Project Details</a></td>
            </tr>
        </tbody>

    @endforeach

Project.php (functions to update status)

    const STATUS_requested  = 1;
    const STATUS_ACCEPTED   = 2;

    public function updateStatus( $status )
    {
        $this->update([
            'status'    => $status
        ]);
        $this->refresh();
        return $this;
    }

    public function projectAccept()   { 

        return $this->updateStatus( self::STATUS_ACCEPTED );   

    }

ProjectsController.php (dd('hello') is not printed it seems like data is not sent to this resource)

    public function plan(Request $request)
    {
        dd('hello');
        Event::find($request->id)->projectAccept();
        return Project::STATUS_ACCEPTED;
    }

web.php

// Update status project
Route::post('/projects/plan',                 'ProjectsController@plan');




Checkbox don't show checked

I'm working with checkbox input. When I click on checbox, checkbox don't show checked but checkbox's value I still get. I use React JS

Simple checkbox

import React from 'react';
import callApi from './../../utils/apiCaller'
import { Link } from 'react-router-dom'


class ProductActionPage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            id: '',
            productStatus: ''
        }
    }

    onChange = (e) => {
        var target = e.target;
        var name = target.name;
        var value = target.type === 'checkbox' ? target.checked : target.value;
        this.setState({
            [name]: value
        });
    }

    render() {
        var statusCheckbox = this.state.productStatus === 'true' ? true : false;
        return (
            <div className="row">
                <div className="col-xs-6 col-sm-6 col-md-6 col-lg-6">
                        <div className="form-group">
                            <label>Trang thai: </label>
                        </div>
                        <div className="checkbox">
                            <label>
                                <input type="checkbox" checked={statusCheckbox} name="productStatus" onChange={this.onChange} />
                                Con hang
                            </label>
                        </div>
                        <button type="submit" className="btn btn-primary">Luu lai</button>
                        <Link to="/product/list" className="btn btn-danger ml-5">Huy bo</Link>
                </div>
            </div>
        );
    }

}

How can I show checked checkbox?




lundi 26 août 2019

Problem centering text in the middle of the checkbox

I'm trying to center text in the middle of the checkbox, but the text is on top.

I will leave the full code here

<!DOCTYPE html>
<html>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

<head>
    <style>
        input {
            display: inline-block;
            vertical-align: top;
            padding-left: 25px;
            position: relative;
        }
        
        input {
            position: absolute;
            left: 0;
            top: 0;
        }
    </style>
</head>

<body>

    <input class="w3-check" type="checkbox"><span>text</span></input>
</body>

</html>

As you can see, the text is not centered, what can I do?




How to use UserForm CheckBox to change Control Content CheckBox in Word Document?

I created an UserForm with a checkbox 'cbxYes' and a Content Control checkbox 'docCbx' in the Word document. I want to be to check off the checkbox 'cbxYes' in UserForm that then changes the Content Control checkbox in the Word document. So the input is from the UserForm checkbox and the output is the Content Control checkbox.

I have tried multiple searches on how to do this, but I could not find exactly what I needed. Most of the searches were related to Excel. And honestly, I don't know what I'm doing. Please. The correct help is greatly appreciated.

Private Sub cbxYes_Click()

Dim oCC As ContentControl

If cbxYes.value = True Then
   cbxYes.value = "True"
   ActiveDocument.docCbx_Yes.value = True
Else
   cbxYes.value = "False"
   ActiveDocument.docCbx_Yes.value = False
End If

End Sub

The error I got was run-time error '438': Object doesn't support this property or method.




What is the best way to design and manage/save state for a widget with many checkboxes?

I'm creating a Flutter app to store progress for board game characters, I want to allow a user to check up to 18 checkboxes, where the checkboxes are grouped in threes:

https://imgur.com/a/jOiQfrX for a picture, as I can't embed it.

My first approach was to code this widget such that I have as little code reused as possible.

CheckboxGroup is a Row widget with a checkmark icon, ":", and three checkboxes as children. CheckboxGridRow is a Row widget with two CheckboxGroups as children. CheckboxGrid is a Column widget with three CheckboxGridRows as children.

-> CheckboxGrid
  -> CheckboxGridRow
    -> CheckboxGroup
    -> CheckboxGroup
  -> CheckboxGridRow
    -> CheckboxGroup
    -> CheckboxGroup
  -> CheckboxGridRow
    -> CheckboxGroup
    -> CheckboxGroup

This works fine for UI purposes, but I'm struggling to wrap my head around how to manage/store state for it. I expect that I will use a List<bool> to store true/false for state, but where should the state change and database logic be for this setup?




Returning a string of selected values from a checkbox collection

I am building a C# MVC view that includes a field with a series of 4 checkboxes. I can populate the list with the values and return individual values just fine, so the basics of the form appear to work. Here is how the options get populated on the view:

    @for (int i = 0; i < Model.QuesOptions.Count; i++)
                        {
                            <div>
                                @Html.HiddenFor(x => x.QuesOptions[i].Name)
                                @Html.CheckBoxFor(x => x.QuesOptions[i].Checked)
                                @Html.LabelFor(x => x.QuesOptions[i].Checked, Model.QuesOptions[i].Name)
                            </div>}

The ultimate goal is to return a single list of values (ideally comma delimited) of the values of each item checked at at the time of posting. So when the user clicks "submit" on the form, it would be great if a single field on the view model (called "UserAnswer") would populate with a comma delimited string. Is this even possible right on the view model?

I had hopes, probably empty ones, that some variation of this would work: @Html.HiddenFor(model=>model.Ques.UserAnswer, new { Value= Model.QuesOptions.Where(x=>x.Checked).Select(x=>x.Name) })

Or would this be a job for some kind of extension method or HTML helper?

Thank you!




Check with jQuery if not checked any checkbox by class

I have 4 checkboxes: one "All" and three different element. The different elements has a class, the "All" checkbox has an id. I want to make checked the "All" checkbox if not checked any other elements. I made this code but not working (Mind means All)

          <label><input type="checkbox" id="check-nemek-mind" rel="nemek-mind" checked /><strong>Mind</strong></label>
        </div>
        <div class="checkbox">
          <label><input type="checkbox" class="check-nemek" rel="nemek-noi"/>Női divat</label>
        </div>
        <div class="checkbox">
          <label><input type="checkbox" class="check-nemek" rel="nemek-ferfi"/>Férfi divat</label>
        </div>
        <div class="checkbox">
          <label><input type="checkbox" class="check-nemek" rel="nemek-gyerek"/>Gyerek divat</label>
        </div>

<script>
$(document).ready(function(){
  $('#check-nemek-mind').click(function() {
    $('.check-nemek').prop('checked', false);
    $('#check-nemek-mind').prop('checked', true);
  });
  $('.check-nemek').click(function() {
    $('#check-nemek-mind').prop('checked', false);
    if(document.getElementByClass('check-nemek').checked) {} else {$('#check-nemek-mind').prop('checked', true);} 
  });
});
</script>




dimanche 25 août 2019

Check box insertion into different columns,without implode function

i want to insert check box values into database table,i had done it using implode function,all the checked values are inserted into same column,but i want to insert values into different coloumn is it possible to insert such a way,thank you.




How to update checkbox values into html?

I want to update my checkbox value .I have the update command successfully running .I can get the values but I am unable to check the appropriate checkboxes in the edit form.Plzz try to help me .Thanks in advance

<?php

.....

$id = isset($_GET['id']) ? $_GET['id'] : '';
$s = "SELECT * from newform WHERE id='$id'";
$result = mysqli_query($connect,$s);
$num = mysqli_num_rows($result);
if($num > 0){
    $row = $result->fetch_array();
    $yr_revision = $row['yr_revision'];
    $b = explode(",",$yr_revision);

.....

?>


 4.2 Mention the  years ?
....
    <input type="checkbox" name="yr_revision[]" value="13-14" 
    <?php echo (in_array("13-14",$b)) ? 'checked' : '' ; ?>>
    2013-2014
    <input type="checkbox" name="yr_revision[]" value="14-15"
    <?php echo (in_array("14-15",$b)) ? 'checked' : '' ; ?>>
    2014-2015

I tried using terminal statements 

.......
    <input type="checkbox" name="yr_revision[]" value="15-16"
    <?php if(in_array("15-16",$b)){echo "checked";}?>>
    2015-2016
    <input type="checkbox" name="yr_revision[]" value="16-17"
    <?php if(in_array("15-16",$b)){echo "checked";}?>>
    2016-2017

......

`````


And I tried using if statements but nothing actually worked

Only the 1st checkbox gets checked each and everytime  others don't
But when I print the $b values as string it displays all checked values

How to update them in html using php?




How to retrieve data from database and set into the check-boxes

I have a form in a c# application in which I am saving values from checkboxes to database. Now what I need to do is that to retrieve the saved values on same form for updating and editing purpose.

For example I have used this query to retrieve the data:

     "Select * from tblComplaints where ID = txtID.Text"

Here I want to know that How can I set the !null values on check-boxes?




samedi 24 août 2019

insert checkbox value into mysql database

i want to enrol the student and insert the student id into mysql database after i check and submit the checkbox value, but i already try so many ways but still cannot...

This is the php code <?php if (isset($_POST['submitxd'])) { foreach ($_POST['enrol'] as $items) { $insert = $link->query("INSERT INTO student_course(studentID) values ('$items')");} } ?>

This is the html code $result = $link->query("SELECT * FROM student WHERE programmeName = '$programme' AND intake = '$intake'"); `while ($row = mysqli_fetch_array($result)) {

echo "<tr>
                  <td>".$row['studentID']."</td>
                  <td>".$row['studentName']."</td>
                  <td>".$row['studentGender']."</td>
                  <td>".$row['studentContact']."</td>
                  <td>
                  <input type='checkbox' name='enrol[]' value='".$row['studentID']."'>
                  </td>                      
                  </tr>";
        }




Setting Visibility on HTML Page Load

I have created an HTML page that has some code in it that hides all the rows in a table except for the header row based on a checkbox status. (only showing one table in code example) There are multiple tables all controlled by their own checkbox. If the checkbox is checked then the table's rows are visible, if it is not checked, the table's row are hidden.

What I would like to have happen is when the page loads if the checkboxes are unchecked (which is typical) then I would like the rows of the corresponding tables to be hidden.

Currently when the page loads the boxes are generally unchecked, but the rows are still visible. Clicking and un-clicking the checkbox hides the rows.

I am guessing (emphasis on guessing) that this issue is related the script code that uses the .change function of the checkbox and at page load that event is not fired.

Is there a way to capture the checkbox status at page load and apply the correct visibility to the rows pertaining to that checkbox? Is there an elegant solution to look at all checkboxes as the page load occurs? I spent quite a bit of time looking for this on SO but with not luck.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>
    <!-- HIDES/SHOWS SUPPLIERS & MATERIAL SECTION OF THE ECN-->
    $(document).ready(function() {
      $('#HideAllSupplierRows').change(function() {
        if (!this.checked)
          $('.AllSupplierRows').fadeOut(300);
        else
          $('.AllSupplierRows').fadeIn(300);
      });
     });
      </script>

    <table border="1" style="width: 900px; height: 40px;">
    <tbody>
    <tr style="height: 23px;">
    <td style="height: 23px; background-color: #11d6d0;" width: 478px; colspan="2"><span style="color: #000000;"> <strong> Suppliers &amp; Material</strong></span></td>
    <td style="width: 257px; background-color: #11d6d0; text-align: center;"><input type="checkbox" id="HideAllSupplierRows" /></td>
    </tr>
    <tr style="height: 22px;" class="AllSupplierRows">
    <td style="width: 40px; vertical-align: top; height: 22px;" td="">&nbsp; <input name="DV" type="checkbox" /></td>
    <td style="width: 695px; height: 21px;" colspan="2">&nbsp;Lead Times / Material Planning</td>
    </tr>
    <tr style="height: 22px;" class="AllSupplierRows">
    <td style="width: 40px; vertical-align: top; height: 22px;" td="">&nbsp; <input name="DV" type="checkbox" /></td>
    <td style="width: 695px; height: 21px;" colspan="2">&nbsp;Order Parts</td>
    </tr>
    <tr style="height: 22px;" class="AllSupplierRows">
    <td style="width: 40px; vertical-align: top; height: 22px;" td="">&nbsp; <input name="DV" type="checkbox" /></td>
    <td style="width: 695px; height: 21px;" colspan="2">&nbsp;Supplier Qualifications</td>
    </tr>
    </table>
    <p></p>




c# I have CheckBoxes and when i run and click them they don't appear with a check mark, even though if they are enabled

Basically I made a simple schedule for grade 7 so I be sure that I completed every task so I made checkboxes, and then I ran it and the checkboxes where not getting checked, and yes, they where enabled

private void CheckBox16_CheckedChanged(object sender, EventArgs e) {

            button1.Enabled = true;

    }




vendredi 23 août 2019

Iterating throught checkboxes of Expandable List

I'm new in android development. I have created a expandable listview which have checkboxes.I'm finding diffculty in iterating through the checkboxes and getting the text of the checkboxes that user have selected.I've used a array string to store the checked value of checkbox but this method doesn't seem to work.The toast displays the text of some other checkbox rather than the selected.

@Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        final String childText =(String) getChild(groupPosition,childPosition);
        if(convertView == null){
            LayoutInflater layoutInflater=(LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView=layoutInflater.inflate(R.layout.expand,null);
        }

 cBox=convertView.findViewById(R.id.chkbx);
cBox.setText(childText);
cValues=new ArrayList<>();
for(int i=0;i<_listDataChild.size();i++) {
            cBox.setOnCheckedChangeListener(
                    new CompoundButton.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                            if (cBox.isChecked()) {
                                Toast.makeText(context, "" + cBox.getText().toString(), Toast.LENGTH_SHORT).show();
                                cValues.add(cBox.getText().toString());

                            }
                        }
                    }
            );
        }

        return  convertView;
    }

}




jeudi 22 août 2019

How to make checkbox checked from the query parameters?

I want to bind my checkboxes to query parameters. For example: I have:

http://localhost:4200/products?pageNumber=1&pageSize=16&lenscolor=1&lenscolor=2

And after page loading, my colors checkboxes with appropriate id (1 and 2) must be checked. I guess, that the best way is via [checked], but don't know how it implement correctly.

.html

<div *ngFor="let lensColor of lensColors; let i = index">
        <input id="lensColor" type="checkbox" name="lensColor" (change)="doLensColorsFilter($event, lensColor.id)">
        <label></label>
      </div>

.ts

export class SidebarComponent implements OnInit {
  lensColors: Color[];
  searchedLensColors = new Array<number>();

constructor(private router: Router,
              private route: ActivatedRoute,
              private productsService: ProductsService) {
    this.routeSubscription = route.params.subscribe(params => this.category = params.category);
    this.querySubscription = route.queryParams.subscribe(
      (queryParam: any) => {
        this.searchedLensColors = queryParam.lenscolor;
      }
    );
  }

  ngOnInit() {
    this.loadLensColors();

}

private loadLensColors() {
    this.productsService.getLensColors().subscribe((data: Color[]) => {
      this.lensColors = data;
    });
  }

private doLensColorsFilter(event, lensColorId) {
    const isChecked = event.target.checked;
    if (isChecked) {
      this.searchedLensColors.push(lensColorId);
    } else {
      const index = this.searchedLensColors.findIndex(el => el === lensColorId);
      this.searchedLensColors.splice(index, 1);
    }
    this.router.navigate(['/products'], {queryParams: {lenscolor: this.searchedLensColors}, queryParamsHandling: 'merge'});

  }

}

my lensColors:

[
 {id: 1, name: "black", uaName: "Чорний"}
 {id: 2, name: "white", uaName: "Білий"}
 {id: 3, name: "yellow", uaName: "Жовтий"}
]




mercredi 21 août 2019

How to keep checkbox array checked after submission

I have the following codes to show dynamic checkboxes.

echo '<input class="checkBoxes" type="checkbox" name="checkBoxArray[]" value="'.$oaName.'" style="float:left;"'; ?> <?php if(isset($_POST['checkBoxArray'])) echo "checked='checked'"; ?> <?php echo '>'; ?>

But after submission, all checkboxes are showing checked. Does anyone know what am i doing wrong here?

Edit 1 checkBoxArray[] are checkboxes names which are getting from database




Selecting a checkbox with selenium doesn't always register

I am clicking on a checkbox using Selenide and I can see that a check is present following the click, however, sometimes when I move onto the next page with the selected checkboxes, it acts as if they are not in-fact checked.

What I am thinking the problem is that sometimes selenide completes the click operation before the page is fully loaded, and with that it shows the checkmark in the checkbox, but it isn't actually checked.

I have tried putting a sleep before the click to wait for the page to load, WebDriverWait's wait.until(ExpectedConditions.visibilityof(element)), Selenide's element.waitUntil(visible, 5000), while(element.getAttribute("checked) == null).

So I don't know how to deal with it when I am seeing the checkmark, but it doesn't actually select.




RShiny: checkboxInput numeric conversion not working in scoring methodology

I'm wanting to use checkboxInput to indicate which variables need to go into a scoring methodology (i.e., have the ability to leave some variables out if desired). I want the checkboxInput to be converted to a 0 or 1, and this number will be used in a scoring algorithm.

I know the scoring methodology is working because it will work when I have default variables chosen which ignore the checkboxInput, but not with these manual check boxes.

I'd greatly appreciate any help. Below isn't an exact replica of code; just a simplified version to make this easier for readers. If this way too simplified, let me know; the actual code is pretty complicated but I want to highlight the simple issue that's causing me such a headache for an unknown reason. Thank you!

I've tried making the checkboxInput a reactive variable(s), I've turned them into integers, etc. I feel like there's something obvious I'm missing.

Here is the code:

ui:

    (
        uiOutput('variable1selected'),  
        uiOutput('variable2selected'), 
        uiOutput("variable3selected")
    )

server:

    output$variable1selected = renderUI({
        checkboxInput("variable1selected",
            "Include Variable 1 in Analysis",
             value=TRUE)
    })
    output$variable2selected = renderUI({
        checkboxInput("variable2selected",
            "Include Variable 2 in Analysis",
            value=TRUE)
    })
    output$variable3selected = renderUI({
        checkboxInput("variable3selected",
        "Include Variable 3 in Analysis",
        value=TRUE)
    })

    variable1selected = reactive({as.integer(input$variable1selected)})
    variable2selected = reactive({as.integer(input$variable2selected)})
    variable3selected = reactive({as.integer(input$variable3selected)})

    Score = variable1selected()*10 + variable2selected()*20 + 
        variable3selected()*30

There aren't any error messages, it's just not scoring at all when the checkboxInput is selected. I'm expecting a score for each row, and then I sort the table by that score. What's actually being produced is an unsorted table because there is no score present to sort (the "Score" variable is NA for each row).




React (Reakit): How to ask for confirmation, when toggling a checkbox?

I'm wondering, if there's a way to ask for confirmation with Reakit's checkbox. I'm using Reakit, since I found a quick way to get it to read database's boolean information, but I welcome other methods too!

I'm used to doing confirmations with buttons with async and window.confirm:

<button onClick={async hiStackOverflow => {
  if (window.confirm("Want to do this?")) {
    // saving to database here 
  }
}}>

But I didn't figure out how to do it with a checkbox. In short, I want for the page to confirm (and then save to database), when the user toggles on/off the checkbox.

// personData = database table, with boolean "recurring"
// row = which entity in a table we are talking about

function CheckboxThing ({ row, personData }) {

  const checkbox = useCheckboxState({state: personData[row].recurring});

  return (
    <div className="checkbox-admin-other">
      <Checkbox 
        {...checkbox} 
        // what here?? onClick or something?
      />
    </div>
  );
}




Find and replace key from array in react native

I am trying to implement checked and unchecked box in a flatlist.

I have taken a keyword checked. On the basis of this keyword I want to show the checkbox (checked or unchecked)

I am trying to update the checked key on selection and deselection.

But getting errors.

Can anyone tell me what is wrong here?

Here is my code:

updateItem(item) {
    this.setState({
      array :  ! this.array.findIndex(item => item.title === item.title).checked
    })
    this.setState({ array: [...this.array] });

}

My array is:

(this.array = [{title: "Option 1",checked:"false"},
      { title: "Option 2" ,checked:"false"},
      { title: "Option 3",checked:"false"},
      { title: "Option 4",checked:"false" },
      { title: "Option 5",checked:"false"}
    ])

Thanks!




Magento2 display All the categories in layer navigation (category page) with checkbox

Iam using magento-2.2.5

Iam trying to display all categories in category page and sub category page under layer-navigation need to add checkbox functionality for all main and sub categories .

Please help me out on this

Thanks in advance




custom checkbox hide background and border

checkbox problem gif
When I mark the lower checkboxes then the upper one above them and hover the lower checked checkboxes ones, then they hidden border and background, better watch gif. I don't understand what i'm doing wrong with selectors. Added codepen.
codepen




How to arrange form:checkbox list in tabular format in Spring MVC?

I have a list of products (40 numbers) and I need to arrange those all in checkboxes in a tabular format along with other form elements

I tried with regular syntax which takes list of String and show checkboxes. But those are showing the checkboxes in horizontal lines one after another. This is ugly representation

<td><form:label path="productlist">Products</form:label></td>
<td><form:checkboxes items="${productStringList}"                               path="productlist" /></td> 

Actual result is list of checkboxes in horizontal line. My expected result is to get the checkboxes in a tabular format, say 4 products in every row




mardi 20 août 2019

How can filter datatable values by jquery

Hi Guys i have two checkbox and i want when check the first checkbox hide include span class = mm--x in datatable or when i check other checkbox hide include span class = mm--y in datatable. is it possible ? or the other method like include "ss" in rows' Column 5.

here is my code:

$("#checkbox1").click(function () {               
                    $(".myTable span." + 'mm--x').hide(); 
                }
            });

$("#checkbox2").click(function () {               
                    $(".myTable span." + 'mm--y').hide(); 
                }
            });




Inserting checkbox value into Mongodb using Springboot

Hi I am new to springboot, I have a requirement of inserting a checkbox value(frontend) into mongodb using springboot(backend). Can any one suggest me how to do .

Thanks in advance




Checked parent checkbox if all child checkboxes are checked

I am trying to check parent node if all child node are checked. I have found some solutions on this particular topic as well. But, may be because of different nesting levels I am unable to achieve this.

Upto this point, I am able to check / uncheck child node according to the parent node. However, reverse is not working i.e, checking parent node if all child nodes are checked.

My Html

<ul class="treeview">
   <li id="li_1" class="contains-items">
      <div class="checkbox">
         <input id="1" type="checkbox" value="1" name="categories[]">
         <label for="1">
         Floor
         </label>
      </div>
      <ul style="display: none;">
         <li class="li_1">
            <div class="checkbox">
               <input id="4" type="checkbox" value="4" name="categories[]">
               <label for="4">
               1st Floor
               </label>
            </div>
         </li>
         <li class="li_1">
            <div class="checkbox">
               <input id="5" type="checkbox" value="5" name="categories[]">
               <label for="5">
               2nd Floor
               </label>
            </div>
         </li>
         <li class="li_1">
            <div class="checkbox">
               <input id="6" type="checkbox" value="6" name="categories[]">
               <label for="6">
               3rd Floor
               </label>
            </div>
         </li>
      </ul>
   </li>
   <li id="li_2">
      <div class="checkbox">
         <input id="2" type="checkbox" value="2" name="categories[]">
         <label for="2">
         Rent
         </label>
      </div>
   </li>
   <li id="li_3" class="contains-items">
      <div class="checkbox">
         <input id="3" type="checkbox" value="3" name="categories[]">
         <label for="3">
         View
         </label>
      </div>
      <ul style="display: none;">
         <li class="li_3">
            <div class="checkbox">
               <input id="7" type="checkbox" value="7" name="categories[]">
               <label for="7">
               Pool View
               </label>
            </div>
         </li>
         <li class="li_3">
            <div class="checkbox">
               <input id="8" type="checkbox" value="8" name="categories[]">
               <label for="8">
               Mountain View
               </label>
            </div>
         </li>
         <li class="li_3">
            <div class="checkbox">
               <input id="9" type="checkbox" value="9" name="categories[]">
               <label for="9">
               Courtyard
               </label>
            </div>
         </li>
      </ul>
   </li>
</ul>

Jquery

 $('input[type=checkbox]').change(function(){
            // if is checked
            if($(this).is(':checked')){

                // check all children
                $(this).parent().siblings().find('li input[type=checkbox]').prop('checked', true);

                //if all siblings are checked, check its parent checkbox
                if($(this).parent().siblings('li input[type=checkbox]').is(":checked")) {  
                    console.log('all siblings checked');
                    //check its parent checkbox
                }else{
                    console.log('not all siblings checked');
                }

            } else {

                // uncheck all children
                $(this).parent().siblings().find('li input[type=checkbox]').prop('checked', false);

            }

        });

However, even doing this it is always consoling not all sibilings checked even if all are checked.




How to remove main checkmark when all the checkboxes are unchecked in ng2 smart table

I am trying to find a solution to remove the select all checkmark when all the present arrays are unchecked. Please find the screenshot for reference]1

I expect to remove checkmark from selectall when all the checkboxes are unselected




lundi 19 août 2019

Kendo grid header template check box ng-click is not firing

I am adding checkbox in header template its getting added and check box getting checked unchecked but ng-click event is not firing can someone please look into this i am new to kendo ui

I have tried

ng-change 
ng-click = 'grid.appScope.toggleSelectAll($event)'

/.............................../enter code here

 $scope[$attrs.paiCheckColumns].unshift({
                template:
                    "<input type='checkbox' ng-model='dataItem.checked' ng-click='toggleSelectRow($event,dataItem)' />",
                headerTemplate:
                    "<input type='checkbox' title='Select all' ng-hide='_chk.singular' ng-model='_chk.all' ng-click='toggleSelectAll($event)' />",
                title: 'Select Items',
                width: '30px',
                isCheckBox: true
            });


$scope.toggleSelectAll = function(ev) {
        if (!isValid) {
            return;
        }

        var newState;
        var gridData = $scope._chk.mainData;
        var i, j, data, detIdx;

        if (ev === true) {
            //if this method is called programmatically
            newState = true;
            $scope._chk.all = true;
        } else {
            //ev is an event, so "all" is already changed via ng-model
            newState = ev.target.checked;
        }

        // empty ids in checked sets
        $scope._chk.items.splice(0, $scope._chk.items.length);
        if ($scope._chk.details) {
            $scope._chk.details.splice(0, $scope._chk.details.length);
        }
        // check all main rows
        if (gridData) {
            for (i = 0; i < gridData.length; i++) {
                gridData[i].checked = newState;
                if (newState) {
                    //add id to checked set
                    $scope._chk.items.push(gridData[i].id);
                }
                // check all sub-rows
                if (gridData[i].childDS) {
                    data = gridData[i].childDS.data();
                    for (j = 0; j < data.length; j++) {
                        data[j].checked = newState;
                        if (newState) {
                            //add id to checked set if not there
                            detIdx = $scope._chk.details.indexOf(data[j].id);
                            if (detIdx < 0) {
                                $scope._chk.details.push(data[j].id);
                            }
                        }
                    }
                }
            }
        }
    };

its not throwing any error




Need to code the three buttons in the treeview

I need to code for the three buttons in the window. One for selecting all, one for deleting all selections and the other for storing selections in the database.




How to get the value associated with checkbox present in data template of listview?

I am trying to get the values/contents of the "selected" check-boxes so that i can use it to get data from sqlite database in the back-end . But I am unable to get the value of the checkbox from the listview.

This is the listview -

<ListView x:Name="listview" Background="Azure" SelectionMode="Multiple"
         ItemsSource="{Binding Strings}" RenderTransformOrigin="0.5,0.5" Width="343">
            <ListView.ItemTemplate>
                <DataTemplate x:Name="datatemplate">
                    <CheckBox x:Name="CheckBoxZone" IsChecked="{Binding RelativeSource={RelativeSource AncestorType=ListViewItem},Path=IsSelected}"
                              Content="{Binding que_text}" Margin="0,5,0,0"/>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <Button  Style="{StaticResource ResourceKey=button_style }" x:Name="addToSurvey" Content="Add" Click="AddToSurvey_Click" />

this is the function-

private void AddToSurvey_Click(object sender, RoutedEventArgs e)
        {

            //foreach (var item in listview.SelectedItems)
            for (int i=0;i< listview.SelectedItems.Count;i++)
            {
                string que = listview.Items[i].ToString(); //did not work

            }

        }

this is the Questions class -

 public class Questions
    {
        public int que_id { get; set; }
        public string que_text { get; set; }
    }

the checkbox hold the que_text value which i need to retrieve for getting the que_id from the database. Please help me out !




php update single checkbox

I have a form (using bootstrap) with 10 checkbox input filed with different name. In this case I want get value from database and check (if = Y) or uncheck (if = N) the checkbox.

I try with a SQL query to:

SELECT 
bk_history
FROM BOOKS_TBL

Get value from database

<input type="checkbox" value="<?=$books['bk_history']; ?>"  name="bk_history" style="display: none;" />

When click and check, get update field with Y, when is uncheck update field with N value.

Now, when i check, do not get update

How to resolve this problem?

Thanks




Unable to close the modal when an angular check box is checked

I am using angular step forms. In one of the form, i have few items with checkboxes. When i check the checkbox the Modal window is opening, but i am unable to close the window when close button on the modal window is clicked.

HTML

<div class = "pop">
 <p><input type="checkbox" name="v" value="B" [checked] = "t1()">test</p>
<div>

<div id="myModal" class="modal">
 <!-- Modal content -->
    <div class="modal-content">
        <span class="close" (click) = "close()">&times;</span>
       <h2>Kasse</h2>   
    </div>

  </div>

ts

close(){
  document.getElementById("myModal").style.display = "none";
}
t1(){
  document.getElementById("myModal").style.display = "block"; 
}

Please guide me through this problem.




How to use observeEvent with a checkbox event Shiny

How do I trigger an action (in this case updateSelectInput) with observeEvent based on a TRUE/FALSE checkbox event?

For example I would like to update result when test is TRUE:

library(shiny)
ui<-fluidPage(
  checkboxInput("test","Test",value=FALSE),
  selectInput("result","Result",choices=c("1","2","3"),selected="1")
)

server<-function(input, output){
  observeEvent(input$test{
    updateSelectInput(session,"result",choices=c("1","2","3","4","5"),selected="1")
  })
}


shinyApp(ui=ui,server=server)




dimanche 18 août 2019

How do you permanently store the state of check mark in the checkbox within the app?

Now I know this question has been answered before, but in my case it is a bit different. I built the check boxes within the listview as shown and the onClick call can only be specific to one of these boxes as far as I can tell.

The sharedpreference would only manage to save the biggest one in terms of the index.

          for(int i = 0; i < l.size(); i++) {
            int check = preferences.getInt(Integer.toString(i), -1);

            checkBox = new CheckBox(getContext());

            checkBox.setText(l.get(i));
            checkBox.setId(i);
            listView.addFooterView(checkBox);
            if(i == check) {
                checkBox.post(new Runnable() {
                    @Override
                    public void run() {
                        checkBox.setChecked(true);
                    }
                });
            }
            checkBox.setOnCheckedChangeListener(new 
                CompoundButton.OnCheckedChangeListener() {
                @Override
  public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
           if (checkBox.isChecked()) {

           preferences.edit().putInt(Integer.toString(checkBox.getId()), 
           checkBox.getId()).apply();
           System.out.println("ID:" + checkBox.getId());
                    }
                }
            });
        }




How to use javascript to replace true/false value in html table with a checkbox

I have an array of javascript objects, that I'm using to dynamically populate an html table. I iterate through each object and all is good. However, one of the keys has a value of true/false, and I need to replace the value with a checkbox for each object in the array. How can I do that?

The checkbox needs to be ticked for false and not ticked for true, also the checkboxes need to be disabled, as we don't want a user interaction.

// Draw table from 'products' array of objects 
function drawTable(tbody) {
  var tr, td;
  tbody = document.getElementById(tbody);
  for (var i = 0; i < products.length; i++) // loop through data source
  {
    tr = tbody.insertRow(tbody.rows.length);
    td = tr.insertCell(tr.cells.length);
    td.innerHTML = products[i].ProductName;
    td = tr.insertCell(tr.cells.length);
    td.innerHTML = products[i].UnitsInStock;
    td = tr.insertCell(tr.cells.length);
    td.innerHTML = products[i].UnitPrice;
    td = tr.insertCell(tr.cells.length);
    td.innerHTML = products[i].Discontinued;
    td = tr.insertCell(tr.cells.length);
    td.innerHTML = document.createElement('button');
  }
}

drawTable('table-data')
<h2>Products</h2>

<div class="table-wrapper">
  <table id="display-table" class="fl-table">
    <thead>
      <tr>
        <th>Product Name</th>
        <th>Units In Stock</th>
        <th>Unit Price</th>
        <th>Discontinued</th>
      </tr>
    </thead>
    <tbody id="table-data">

    </tbody>
  </table>
</div>



Auto Break between Checkbox and Text in C#

I hope you can help me with my problem.

I want to automatically generate a Word checklist with a C# program.

But I can't get it to put the text behind the checkbox. The text always lands in a new line under the checkbox.

How can I solve this problem?

You know some other functions?

    public void createChecklist()
    {
        Application app = new Application();
        app.Visible = true;
        Document doc = app.Documents.Add();
        Paragraph para = doc.Paragraphs.Add();

        ContentControl checkbox = para.Range.ContentControls.Add(WdContentControlType.wdContentControlCheckBox);
        para.Range.InsertAfter("sdjsakd");

        doc.SaveAs2("C:\\tmp\\checklist.docx");
        app.Quit();

    }

Word




vendredi 16 août 2019

How to setstate for the dynamic checkboxes in a loop in react?

I am loading checkboxes in a loop. I have difficulties in setting the states for the dynamic checkboxes.

I am loading checkboxes in a loop. I need to set the state of the checkboxes to make them work. when I set the state every checkbox gets checked so please give me a solution

Component Initialization

const ChildComponent = props =>
           <div key={"comp"+props.number} className="relay-team-list">
               <div className="read-more">
                   <a href="#">Team {props.number} - Click to Rename</a>
               </div>
               {
                   members_arr.length > 0 ?(
                       members_arr.map((member,i)=>
                           member.position===props.number?(
                               <div key={"members"+i} className="columns is-mobile list-item" id={"member" + props.number}>
                                   <div className="column is-one-third">
                                       <img src={require('../images/user.png')}/>
                                   </div>
                                   <div className="column txt-mid-grey relay-team-list-text">
                                       <p>{member.members_arr.member_name}</p>
                                       <p></p>
                                       <span className="check-icon"><input type="checkbox" value="checkedB"
                                                                           checked = {this.state.enabledCheckBox+i}
                                                                           label=
                                                                           onChange={this.passMemberID}
                                       /></span>

                                   </div>
                               </div>
                           ):''
                       )
                   ):''
               }
           </div>;

The Function

  passMemberID=()=>{
        this.setState((prevState, props) => ({
            enabledCheckBox : !prevState.enabledCheckBox
        }), () => console.log(this.state.enabledCheckBox))
    }

Constructor



 constructor(props) {
        super(props);
 this.state = {

            enabledCheckBox: false,



        }
}

I need to have different states to every checkbox so I can click them one by one now all are getting checked at once




How to pass Array of checkbox data attributes as IEnumeration of Model from jQuery Ajax to the MVC 5 Action?

Long time developer new to JQuery, MVC, & C#

I have a list of a Model (RZRCheckBoxModel) that include values to be displayed as check boxes.

I need to retrieve all the checkboxes regardless of checked state and update a database based on the data- attributes and checked state of the the check boxes

For reasons I won't go into I can't submit the form to retrieve the Model

I am able to retrieve all the checkboxes from the View in JQuery and format them as an array of the Model. However, the ajax call to the control never reaches the action and I don't receive an error

I've been all over Stack Overflow and the internet in general with no luck. I feel like I'm close, I just can't quite put my finger on what needs to be done.

MODEL

public class RZRCheckBoxListModel
    {
        public List<RZRCheckBoxModel> CheckBoxList { get; set; } = new List<RZRCheckBoxModel>();

        public List<RZRCheckBoxModel> JQueryList { get; set; } = new List<RZRCheckBoxModel>();
    }

public class RZRCheckBoxModel
    {
        public int Id { get; set; }

        [Display(Name = "Check Box Name")]
        [Required(ErrorMessage = "Enter a {0}")]
        public string Name { get; set; } = "";

        [Display(Name = "Is Checked")]
        public bool IsChecked { get; set; } = false;
    }

DISPLAY VIEW

This view displays the check boxes on load of the website

@model TestProjects.Models.RazorControls.RZRCheckBoxListModel

            <h5>Data Enty</h5>
            for (int i = 0; i < Model.CheckBoxList.Count(); i++)
            {
                <div class="row">
                    <div class="col-6">
                        @Html.HiddenFor(m => m.CheckBoxList[i].Id)
                        @Html.HiddenFor(m => m.CheckBoxList[i].Name)
                        @Html.CheckBoxFor(m => m.CheckBoxList[i].IsChecked, new { @class = "check-box m-2", data_id = Model.CheckBoxList[i].Id, data_name = Model.CheckBoxList[i].Name})
                        @Html.DisplayFor(m => m.CheckBoxList[i].Name, new { htmlAttributes = new { @class = "control-label m-2" } })
                    </div>
                </div>
                <input type="submit"
                       value="Fake button" 
                       class="btn btn-default" 
                       data-counter="@Model.CheckBoxList.Count()"
                       onclick="javascript: RZRCheckBoxList(this);" />
            }

JQUERY

function RZRCheckBoxList(cntrl) {

    var list = [];
    list.push($('.check-box:Checkbox'));

    var result = [];
    for (var i = 0; i < list[0].length; i++) {
        var RZRCheckBoxModel = {};
        RZRCheckBoxModel.Id = parseInt(list[0][i].attributes["data-id"].value);
        RZRCheckBoxModel.Name = list[0][i].attributes["data-name"].value;
        RZRCheckBoxModel.IsChecked = list[0][i].checked;
        result.push(RZRCheckBoxModel);

    }
var postData = { values: result };
    $.ajax({
        url: baseUrl + 'TestControlsRazorController/RZRJqueryChkBoxList',
        type: 'POST',
        //data: JSON.stringify({ 'MyModel': postData.values }),
        data: JSON.stringify({ 'MyModel': postData }),
        datatype: 'json',
        contentType: "application/json",
        traditional: true,
        success: function (data) {
            var $div = $('#JqueryResults');
            $div.html(data);
        },
        error: function (response, error, message) {
            //populate the error div
            var tst = 'test';

            var msg = "";
            msg += 'Javascript (RZRCheckBoxList): ';
            msg += { 'Error {0} - ': err.toString() };
            msg += { 'Message {0} - ': message.toString() };
            msg += { 'Response {0} ': response.responseText };

            alert(msg);//'JavaScript Error (RZRCheckBoxList): ' + error.toString() + ' - ' + message.toString() + - + response.responseText);
            alert(error + ' - ' + message + ' - ' + response);
        }
    });
}

JSON.stringify({ 'MyModel': postData })

produces the below results


    {
        "MyModel":
        {
            "values":
            [
                {
                    "Id": 0,
                    "Name": "Check Box 1",
                    "IsChecked": false
                },
                {
                    "Id": 1,
                    "Name": "Check Box 2",
                    "IsChecked": true
                }
            ]
        }
    }


JSON.stringify({ 'MyModel': postData.values })

produces the below results

    {
        "MyModel":
        [
            {
                "Id": 0,
                "Name": "Check Box 1",
                "IsChecked": false
            },
            {
                "Id": 1,
                "Name": "Check Box 2",
                "IsChecked": true
            }
        ]
    }

CONTROLLER ACTION

The ajax call never gets here

        //public JsonResult RZRJqueryChkBoxList([FromBody] List<RZRCheckBoxModel>[] MyModel)
        //public JsonResult RZRJqueryChkBoxList(List<RZRCheckBoxModel> MyModel)
        [HttpPost]
 public JsonResult RZRJqueryChkBoxList(RZRCheckBoxModel[] MyModel)
        {
            List<RZRCheckBoxModel> mdl = new List<RZRCheckBoxModel>();
            foreach (RZRCheckBoxModel chkBx in MyModel)
            {
                mdl.Add(chkBx);
            }

            var view = RenderRazorViewToString(ControllerContext, "_RZRChkBoxJqueryList", mdl);
            return Json(new { view });
        }

VIEW

This view should display the results of the JQuery Ajax call to the Controller action but it does not

@model IEnumerable<TestProjects.Models.RazorControls.RZRCheckBoxModel>

<h6>JQuery Result</h6>
<table class="table thead-light table-striped table-hover table-sm">
    <tr>
        <th>@Html.LabelFor(m => m.FirstOrDefault().Id)</th>
        <th>@Html.LabelFor(m => m.FirstOrDefault().Name)</th>
        <th>@Html.LabelFor(m => m.FirstOrDefault().IsChecked)</th>
    </tr>
    @foreach (var itm in Model)
    {
        <tr>
            <td>@Html.DisplayFor(m => itm.Id)</td>
            <td>
                @itm.Name
            </td>
            <td>
                @itm.IsChecked
            </td>

        </tr>
    }
</table>

I get no error message

The Jquery gets to the ajax call exits the function and returns to the View just as though it did everything it was supposed to

I'm expecting it to display the results of the Checkbox as an IEnumeration of Model (RZRCheckBoxModel) but it does not

Any help is greatly appreciated!

Thank you in advance.




I'm trying to use checkboxes to enter data into a document in MongoDB

I want users to use checkboxes to determine toppings that are on a new pizza.

I have a collection called ingredients for veg, meat, cheese and sauce. And I have a collection called pizzas.

I want to pull all possible ingredents from each category, display them on screen, allow the user to check the ones that are on a pizza then submit it. The submission would go to the pizza collection.

At the moment veg, meat, cheese and sauce have their own dictionaries pulled into a python file called app.py:

meats = mongo.db.ingredients.find_one({'meats' : {'$exists': True}})
vegs = mongo.db.ingredients.find_one({'vegs' : {'$exists': True}})
sauces = mongo.db.ingredients.find_one({'sauces' : {'$exists': True}})
cheeses = mongo.db.ingredients.find_one({'cheeses' : {'$exists': True}})

They are then passed into the addpizza.html file:

@app.route('/add_pizza')
def add_pizza():
    return render_template("addpizza.html", 
                           meats = meats,
                           vegs = vegs,
                           sauces = sauces,
                           cheeses = cheeses)

Pizza collection example:

{"_id":{"$oid":"5d506eed1c9d4400000a4254"},"pizza_name":"vegetairian supreme","pizza_code":"vs","sauce_type":"pizza","cheese_type":"mozzarella","toppings":["onions","mushrooms","peppers","sweetcorn","tomatoes"],"allergens":"","is_veg":true}

Ingredient collection example:

{"_id":{"$oid":"5d5353ee1c9d440000cb278e"},"meats":["bacon","beef","roast chicken","tandoori chicken","ham","meatballs","pepperoni","chorizo","sausage"]}

addpizza.html, at the moment I am only trying to display meat toppings to the user:

<h3>Add Pizza</h3>
<div class="row">
    <form action="" method="POST" class="col s12">
        <div class="row">
            <div class="input-field col s12">
             
        </div>
        <div class="row">
            <button class="btn waves-effect waves-light" type="submit" name="action">Add Pizza
                <i class="material-icons right">playlist_add</i>
             </button>
        </div>
    </form>
</div>

This displays checkboxes and each individual meat. However regardless of which checkbox you try to check, it will check the first one then send you to the top of the page.




Expandable listView with checkboxes clicklistener

I'm new in android development.I have create a expandable listview with checkboxes and textViews. What I'm trying to implement is that on checking the checkboxes a toast should be displayed with the corresponding text from textView but I'm not able to do that.

This code below doesn't way ! Is there any other work.I have done research and I'm still not finding the answer to my query

 expandableListView.setOnChildClickListener(
                new ExpandableListView.OnChildClickListener() {
                    @Override
                    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                        Toast.makeText(getApplicationContext(), listData_H.get(groupPosition)+" - "
                                +listData_Ch.get(listData_H.get(groupPosition)).get(childPosition)
                                , Toast.LENGTH_SHORT).show();
                        return false;
                    }
                });




Woocommerce checkout checkbox if checked show information/warning

Im new in this coding stuff, I researched many sites now and try to build my own checkout field in Woocommerce. It should be a checkout field, when it is checked, some information or warning should plop up, it worked with showing on checkout page normal, but my script doesn't work.

add_filter( 'woocommerce_checkout_fields', 'add_custom_checkout_fields' ); function add_custom_checkout_fields( $fields ) {

$fields['billing']['checkbox_trigger'] = array(
    'type'      => 'checkbox',
    'label'     => __('You dont live in Germany?', 'woocommerce'),
    'class'     => array('form-row-wide'),
    'clear'     => true
);
return $fields;

} add_action( 'woocommerce_after_checkout_billing_form', 'echo_notice_billing' );

function echo_notice_billing() { echo 'It may take forever'; }

add_action( 'woocommerce_after_checkout_form', 'show_notice_billing' );

function show_notice_billing(){

?>
    <script>
    jQuery(document).ready(function($){

        $('checkbox_trigger').change(function(){

            if(this.checked){
                $('billing-notice').show();
            }
            else {
                $('billing-notice').hide();
            }
        });

    });
</script>

<?php

}