samedi 29 février 2020

In Vuetify, how to prevent the click on a chip inside a checkbox to check the checkbox?

I have a chip inside a checkbox, and I thought "@click.stop" or "@click.capture" would prevent the checkbox to be checked. But it doesnt't work. Have I misunderstood something?

  <v-checkbox
    v-model="myModel"
    hide-details
  >
    <template v-slot:label>
      <div>
        My label
        <v-tooltip bottom>
          <template v-slot:activator="{ on }">
            <v-chip
              class="ma-2"
              color="green"
              text-color="white"
              v-on="on"
              @click.capture="myValue = true"
            >
              <v-avatar left>
                <v-icon>mdi-help-circle-outline</v-icon>
              </v-avatar>
              chip content
            </v-chip>
          </template>
          The tooltip
        </v-tooltip>
      </div>
    </template>
  </v-checkbox>

"myValue" updates correctly, but the checkbox toggles anyway...

Thanks in advance :)




react input checkboxes - not toggling with change in state

I'm having trouble getting a group of checkboxes to toggle with changes in state. I'm rendering the checkboxes using array.map and returning input elements.

It looks like my handleUpdateCheck function updates state appropriately, but the DOM does not re-render.

const [checked, updateChecked] = useState([true, true, true, false, false]);

function handleUpdateChecked(index) {
    let newArr = checked;
    newArr[index] = !checked[index]
    updateChecked(newArr);
}

checked.map((box, index) => {
    return (
        <input
            key={index}
            type='checkbox'
            checked={checked[index]}
            onChange ={() => handleUpdateChecked(index)}
        />
    )
})


Thanks




jQuery toggleclass Button action to Checkbox action

Hi I use the code for Wordpress and the theme builder DIVI. I am a really noob beginner with JS and jQuery. The code provide a features to have Night Mode when pushing on a button. I find a custom toggle switch button on Codepen and I like it, and I would love to use it for the code bellow. This JQuery code it's make for button action "click" but I would love to custom it to react to a "Checkbox". Is it possible to make a toggleclass with checkbox?

here is the link : Link off the website

<script type="text/javascript">
jQuery(document).ready(function() {
// Hide the div
jQuery('#rv_button').click(function(e){
e.preventDefault();jQuery(".reveal").toggleClass('light dark', 1000);
jQuery('#rv_button').toggleClass('opened closed');
});
});
</script>



How to save the terms and conditions checkbox field when it's checked in the Woocommerce checkout order meta and display in the order edit page

I´m trying to save the terms and conditions chickbox field in the WooCommerce checkout order meta and display it in the order edit page.




Primefaces Tree : The checkbox selection gets deselected when I click on the button to open modal on the parent / child node

Hi I'm using the component Tree - Selection with the variant Checkbox. Everything in the component is working fine but I need to put a button next to every parent and child of my nodes to open a model which happen with the id of that node, the problem is that if I press the button that unchecks that node. This is my code

 <p-tree [value]="casePartyServiceContactModel" selectionMode="checkbox"
                                    [(selection)]="selectedServiceContactsTree" (onNodeSelect)="nodeSelect($event)"
                                    (onNodeUnselect)="nodeUnselect($event)">
                              <template let-node pTemplate="default">
                                <span class="listname"></span>

                                <span class="listicons pull-right" *ngIf="!node.parent">
                                <button type="button" class="btncontact btn-primary box mar-r-20 pad-t-2 pad-b-2" data-toggle="modal" (click) = "setCasePartyIdForServiceContacts(node.data.partyID,node.data.caseId)"
                                        data-target="#addServiceContactToCase">Add Service Contact To Case
                                </button>

                                </span>

                                <span class="listicons pull-right" *ngIf="node.parent">
                                           <button type="button" class="buttonicon blueicon" data-toggle="modal"
                                                   data-target="#viewservicecontactdetails"
                                                   pTooltip="View Service Contact Details"
                                                   (click)="getServiceContactDetail(node.data.serviceContactID);"
                                                   tooltipPosition="top">
                                                     <i class="fa fa-user" aria-hidden="true"></i>
                                            </button>
                                            <button type="button" class="buttonicon blueicon" data-toggle="modal"
                                                    data-target="#viewattachedcaselist"
                                                    pTooltip="View Attached Case List"
                                                    (click)="attachedCaseList(node.data.serviceContactID,node.data.firstName,node.data.lastName)"
                                                    tooltipPosition="top">
                                              <i class="fa fa-paperclip" aria-hidden="true"></i>
                                            </button>

                                            <button type="button" class="buttonicon blueicon" pTooltip="Detach Contact"
                                                    *ngIf="node.data.editableFlag"
                                                    (click)="detachContact(node.data.serviceContactID,node.parent.data.caseId,node.parent.data.partyID,false)"
                                                    tooltipPosition="top">
                                              <i class="fa fa-trash" aria-hidden="true"></i>
                                            </button>
                                        </span>
                              </template>
                            </p-tree>



How to disable multiple checkboxes in javafx

I have 40 checkboxes and I need to disable some depending on a variable ArrayList. Is there is a way to do this in JavaFX?

List<Integer> aList = new ArrayList<Integer>(){add(2);};

CheckBox s01, s02, s03;
s01 =new CheckBox("S01");s02 =new CheckBox("S02");s03 =new CheckBox("S03");

(if x is found in aList disable Checkbox sx) 



vendredi 28 février 2020

CSS prevent rotation transform from affecting :before elements

I'm trying to have the checkboxes appear below their slanted "span" label. However, the transform applied to the "span" is also applying to the custom checkbox created with the ":before" selector. How do you prevent the 45deg rotation to the custom checkbox, and have it appear directly below it's label?

.slanted_chkbx {
  margin-top: 25px;
}

.slanted_check {
  margin-left: 5px;
  margin-right: 15px;
  display: inline-block;
  position: relative;
}

.slanted_check span {
  position: absolute;
  top: -20px;
  left: .7em;
  transform-origin: bottom left;
  transform: rotate(-45deg);
}

.custom_check {
  display: none;
}

.custom_check + span:before {
  content: '';
  display: block;
  cursor: pointer;
  width: 10px;
  height: 10px;
  left: 0;
  top: 0;
  position: absolute;
  border: 2px solid #111111;
  -webkit-transition: all .2s;
  transition: all .2s;
}

.custom_check:checked + span:before {
  width: 5px;
  top: -2px;
  left: 2px;
  border-radius: 0;
  opacity: 1;
  border-top-color: transparent;
  border-left-color: transparent;
  -webkit-transform: rotate(45deg);
  transform: rotate(45deg);
}
<div class="slanted_chkbx">
  <label class="slanted_check">
    <input type="checkbox" class="custom_check" name="option_one" value="option_one">
    <span>One</span>
  </label>
  <label class="slanted_check">
    <input type="checkbox" class="custom_check" name="option_two" value="option_two">
    <span>Two</span>
  </label>
  <label class="slanted_check">
    <input type="checkbox" class="custom_check" name="option_three" value="option_three">
    <span>Three</span>
  </label>
</div>



Persistent checkbox - Swift for MacOS project

I have been looking to solve this problem for a while but I'm finding only solutions for IOS projects.

I'm building a little macOS application with swift and I would like to make the state of my checkbox persistent, so when I open the application back the state of the checkbox didn't change.

Currently I'm trying to use the UserDefaults.standard to save the value in a persistent way

class ViewController: NSViewController, NSTextFieldDelegate{
        @IBOutlet weak var LoginItemButton: NSButton!
        var checkButtonState = UserDefaults.standard

       @IBAction func LoginItemPressed(_ sender: NSButton) {
            checkButtonState.set(sender.state, forKey: "buttonState") }}

Now I would like with that saved value to assign it back to the sender.state, and keep it that way!

But whatever I do the checkbox goes off every time I restart the app, even if I set it manually with sender.state = .on

Do you have any suggestions?

This is the full application




Setting Checkbox Required Attribute onClick

I'm building a web form that hides/shows table rows and sets certain fields required or not required based on user selections.

My question is two fold. First, how do I require users to check at least one box in the group of checkboxes called "ReallocationType"? I'm unsure what the code in "ValidateCheckboxes" function should look like. Secondly, how do I only enforce this only when "ReallocationTypeRow" is displayed?

   function ReqTypeHideShow(selection) {
           var s1 = document.getElementById("ReallocationRow")
  
           if (selection === "ReallocateCost") {
              s1.style.display = "table-row" ;
              //call function ValidateCheckboxes() ;
           }
        }

        function ValidateCheckboxes() {
               form.ReallocationType[0].checked === false
           //Need additional code here

               form.ReallocationType[1].checked === false
           //Need additional code here

               form.ReallocationType[2].checked === false
           //Need additional code here
        }
<table>
  <tr id="ReqTypeRow">
     <td>Request Type</td>
     <td>
        <select id="ReqType" name="ReqType" onchange="ReqTypeHideShow(this.value)">
           <option value="">-- Select an Option --</option>
           <option value="ReqDef">Request New Project</option>
           <option value="ProjAppr">Request Funding</option>
           <option value="ProjReappr">Request Re-approval</option>
           <option value="ReallocateCost">Re-allocate Funding</option>
        </select>
     </td>
  </tr>

  <br>

  <tr id="ReallocationTypeRow" style="display:none">
     <td>Reallocation Type (check all that apply)</td>
     <td>
        <input type="checkbox" name="ReallocationType" value="LabToExt">Internal to External Spend<br>
        <input type="checkbox" name="ReallocationType" value="ExtToLab">External to Internal Spend<br>
        <input type="checkbox" name="ReallocationType" value="LabToLab">Shift Internal Phases Around
     </td>
  </tr>
</table>

Thank you in advance for the help!




How do you make a checkbox checked by default in Kivy?

I have created two checkboxes in a .KV file (one for default settings and one for custom keywords) and I am trying to get the default box to be checked when the GUI opens this window initially. I am able to get the default value output to be set correctly however, I can't get the actual checkbox to visually show it is selected when the window is initially shown.

The goal of this program is to make a basic graphic user interface for an existing simulation software my lab has created and completed previously.

I am pretty new to Kivy so I am not sure if I am doing something fundamentally wrong or if I just don't understand how checkboxes work properly.

I have tried both methods I've seen on other related posts

defaultCheckbox = ObjectProperty(True) #in .py file

and I've tried adding

active: True # in the .kv file

Here is the checkbox portion of the .kv file

The canvassing section was replicated from another stackoverflow post where the box behind a checkbox was not showing up when a page is rendered and thus the solution was to draw it manually.

            FloatLayout:
                BoxLayout:
                    orientation: "horizontal"
                    height: 20
                    pos_hint: {'center': (0.5, 0.7)}

                    FloatLayout:
                        Label:
                            text: "Default \n Keywords"
                            size_hint_x: 1
                            halign: 'center'
                            pos_hint: {'center': (0.2, 0.5)}
                            font_size: 30

                    #todo make default kwargs checkbox active on program boot
                    CheckBox:
                        id: defaultCheckbox
                        canvas.before:
                            Color:
                                rgb: 30,35,38
                            Ellipse:
                                pos:self.center_x-11, self.center_y-11
                                size:[22,22]
                            Color:
                                rgb: 0,0,0
                            Ellipse:
                                pos:self.center_x-10, self.center_y-10
                                size:[20,20]
                        on_active: root.default_click(self, self.active)
                        size_hint_x: .20
                        group: "keywords"

                    Label:
                        text: " "
                        valign: 'bottom'


                    FloatLayout:
                        Label:
                            text: "Define \n Experiment \n Keywords"
                            size_hint_x: 1
                            halign: 'center'
                            pos_hint: {'center': (0.15, 0.5)}
                            font_size: 25


                    CheckBox:
                        canvas.before:
                            Color:
                                rgb: 30,35,38
                            Ellipse:
                                pos:self.center_x-11, self.center_y-11
                                size:[22,22]
                            Color:
                                rgb: 0,0,0
                            Ellipse:
                                pos:self.center_x-10, self.center_y-10
                                size:[20,20]
                        on_active: root.custom_click(self, self.active)
                        size_hint_x: .20
                        group: "keywords"

and here is the related portion of the .py file

class PhysicsModeling(Screen):
    kwargPopup = ObjectProperty(None)
    physicsModel = ObjectProperty(None)
    initialConditions = ObjectProperty(None)
    default = ObjectProperty(True)
    defaultExpKwargs = {'G0' : 1., 'G1' : .1, 'G2': 1., 'MU':1.,  'scaling' : 25, "solution1" : 1,"solution2" : 3, "orientation2" : "x", "y_shift2" : 1./4.}
    customExpKwargs = ObjectProperty(None)
    defaultCheckbox = BooleanProperty(True)


    def physicsmodel_spinner_clicked(self, value):
        print("Physics Model selected is " + value)

    def initialconditions_spinner_clicked(self, value):
        print("Intial Conditions " + value + " Selected")

    def default_click(self, instance, value):
        if value is True:
            PhysicsModeling.default = True
            print("Checkbox Checked")

        else:
            PhysicsModeling.default = False
            print("Checkbox Unchecked")

    def custom_click(self, instance, value):
        #todo add popup window for custom kwargs
        if value is True:
            PhysicsModeling.default = False
            print("Checkbox Checked")
            PhysicsModeling.default = True
            popup = Popup(title='Define Keyword Arguments', content=Label(text='Test Popup'),
                          auto_dismiss=True, size_hint=(0.5,0.5), pos_hint={'x': 0.25,
                            'y':0.25})
            popup.open()
        else:
            print("Checkbox Unchecked")

    def next_button(self):
        outputArray[11] = self.physicsModel.text
        outputArray[10] = self.initialConditions.text
        print("NEXT button pressed!!")
        print("Batches Selected ", self.physicsModel.text)
        print("Run Solutions ", self.initialConditions.text)
        if self.default == True:
            outputArray[12] = self.defaultExpKwargs
            print("Default KWargs Selected")
        else:
            print("Custom KWargs are DEFINED")
            outputArray[12] = self.customExpKwargs





Can't deselect all checkbox

I have a checkbox list and another checkbox at the top to check them all, but when I check them all, I can't clear them anymore.

class App extends React.Component {
  state = { checked: undefined }
  selectAll = ({ target: { checked } }) => this.setState({ checked })

  render() {
    const { checked } = this.state
    const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    return <ul>
      <input type='checkbox' onChange={this.selectAll} /> Check All
      {arr.map(i => <li>
        <input type='checkbox' checked={checked} />
        <span>checkbox {i}</span>
      </li>
      )}
    </ul>
  }
}

ReactDOM.render(<App />, document.getElementById('root'))
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>



If a checkbox is checked, REQUIRE a text field to be filled in. Text field is FAILING: always required regardless of checkbox status

I have a group of 3 check boxes. If the one labelled as "mouthpiece" is checked, then the text field labelled mpTxt must NOT be left blank for the form to validate. Currently, the form is requiring the mpTxt field to be filled regardless of what is checked.

HTML:

 <div class="col-6">
    <b><u>Interface </u></b><br>
    <input id="F429_interfaceTrachCkBx" class="F429_backupV" name="F429_interfaceTrachCkBx" 
type="checkbox">
    Trach 
    <input id="F429_interfaceMaskCkBx" class="F429_backupV" name="F429_interfaceMaskCkBx" 
type="checkbox">
    Mask 
    <input id="mouthpiece" class="F429_backupV" name="F429_interfaceMouthpieceCkBx" type="checkbox">
    Mouthpiece <br>
</div>

 Mouthpiece Ventilation (MPV) Settings 
 <input id="mpTxt" class="F429_mpvSetting" name="F429_mpvSetting" type="text">

JavaScript:

//REQUIRE MPV TEXT IF CKBX CHECKED

var checkBox = document.querySelector('input[id="mouthpiece"]');
var textInput = document.querySelector('input[id="mpTxt"]');

function toggleRequired() {

if (textInput.hasAttribute('required') !== true) {
    textInput.setAttribute('required','required');
}

else {
    textInput.removeAttribute('required');  
}
}

checkBox.addEventListener('change',toggleRequired,false);



I'm trying to use the Tri-State-Checkbox library authored by sephiroth74 and am getting an error when I run the application

I followed the installation instructions at android arsenal and was able to build the solution but when I try to run the app I get this error:

2020-02-27 14:49:01.800 14357-14357/com.software.test E/AndroidRuntime: FATAL EXCEPTION: main Process: com.software.test, PID: 14357 java.lang.NoClassDefFoundError: Failed resolution of: Ltimber/log/Timber; at it.sephiroth.android.library.checkbox3state.CheckBox3.(CheckBox3.java:19) at java.lang.reflect.Constructor.newInstance0(Native Method) at java.lang.reflect.Constructor.newInstance(Constructor.java:343) at android.view.LayoutInflater.createView(LayoutInflater.java:852) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1004) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:959) at android.view.LayoutInflater.rInflate(LayoutInflater.java:1121) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082) at android.view.LayoutInflater.inflate(LayoutInflater.java:680) at android.view.LayoutInflater.inflate(LayoutInflater.java:532) at android.view.LayoutInflater.inflate(LayoutInflater.java:479) at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469) at androidx.

I've also tried to follow the installation instructions at his github repository, but I can't even get the solution to build if follow those. So for the time being I've deserted this route.




Creating a list of CheckBoxed items across multiple google sheets

I'm struggling to find the right formula to do a relatively simple task. I have a google sheet document with multiple sheets that have items listed each with a checkbox. I'd like to have each item that is checked be returned in a separate sheet in order to create a list. I've tried a few VLOOKUP formulas as well as combinations of IF/MATCH logic to get there but nothing seems to be working. Here's what I'm looking at:

enter image description here

Id like the list to return the "Item Location" for each column with a checked checkbox.




check uncheck checkbox using angularjs using attribute

I want to add checked and unchecked attribute to the checkbox which is in a table I tried to using it via jquery in angularjs

$('#chksitecolumn_' + item.Id).attr('checked', true)

Here item.Id is the id which I am iterating and binding it on ng-model.

and also tried it using angularjs

 var element = angular.element('#chksitecolumn_' + item.Id);
                            element.attr('checked', 'checked');

but it is not working

Here is my checkbox

<input  type="checkbox" class="test"  id="chksitecolumn_" ng-model="selected[item.Id]"/>

I am passing an ID as a key using ng-model I want to know that can we check uncheck checkbox except using ng-model?




Django form: How to check only one checkbox?

I have a really simple form:

forms.py

OPTIONS = (
    ("B", "Black"),
    ("Y", "Yellow"),
    ("R", "Red"),
)
colors = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
                                   choices=OPTIONS)

Is it possible to check only one of these checkbox?

I manage to check all of them

attrs = {"checked": True}
colors = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs=attrs),
                                   choices=OPTIONS)

But I would like to be able to check "Black" and not the two other.

Thank you.

(Django==2.0.7)

Fred




How to select all checkbox when i checked all check boxes

I want to select all checkbox checked when i select all checkboxes in my dropdown menu. I am a beginner js developer need help. This is my js code

var expanded = false;
function showCheckboxes() {
var checkboxes = document.getElementById("checkboxes");
if (!expanded) {
checkboxes.style.display = "block";
expanded = true;
} else {
checkboxes.style.display = "none";
expanded = false;
}
}
var selectallBox = document.getElementById('selectall');
var checkBoxes = document.querySelectorAll('.select-me');
selectallBox.addEventListener('click', function() {

for (var i = 0; i < checkBoxes.length; i++) {
    if (checkBoxes[i] != selectallBox)
        checkBoxes[i].checked = selectallBox.checked;
}


})
for (var i = 0; i < checkBoxes.length; i++) {
   checkBoxes[i].addEventListener('click', function() {

    selectallBox.checked = false; 
})
}
document.querySelector('.close-check-box').addEventListener('click' , function(){
checkboxes.style.display = 'none'
})

This is my js fiddle: https://jsfiddle.net/b9ueL3fw/




jeudi 27 février 2020

how to select select all checkbox when i checked all check boxes using vanila javascript [closed]

I want to select all checkbox checked when i select all checkboxes in my dropdown menu. I am a beginner js developer need help. This is my js code

`var expanded = false;`
function showCheckboxes() {
var checkboxes = document.getElementById("checkboxes");
if (!expanded) {
 checkboxes.style.display = "block";
expanded = true;
 } else {
checkboxes.style.display = "none";
expanded = false;

}

var selectallBox = document.getElementById('selectall');
var checkBoxes = document.querySelectorAll('.select-me');
selectallBox.addEventListener('click', function() {

for (var i = 0; i < checkBoxes.length; i++) {
    if (checkBoxes[i] != selectallBox)
        checkBoxes[i].checked = selectallBox.checked;
}

})

for (var i = 0; i < checkBoxes.length; i++) {
   checkBoxes[i].addEventListener('click', function() {

    selectallBox.checked = false; 
})
}
document.querySelector('.close-check-box').addEventListener('click' , function(){
checkboxes.style.display = 'none'

})

This is my js fiddle

https://jsfiddle.net/8kg6dcst/




Select People to Show on a Plot Using checkboxGroupInput in Shiny

I want to use Shiny to build an interactive plot of my "Phone Usage" data - 5 students' hours of phone usage during a week (from 2/20 to 2/26).

Name    2.20    2.21    2.22    2.23    2.24    2.25    2.26
Minruo  6.05    5.53    6.47    5.47    5.87    7.80    5.70
Xudian  6.18    6.70    5.50    5.42    5.50    6.12    6.77
Luyi    12.53   18.77   12.72   9.80    10.95   9.57    11.08
Xiaojue 6.78    6.88    6.91    5.66    6.18    5.43    6.66
Ziyuan  15.45   19.25   14.48   15.25   7.47    9.42    10.52

I want to use checkboxGroupInput to select students to show on the plot. Without the code of checkboxGroupInput, the code below can produce a plot smoothly. However, an error "Breaks and labels are different lengths" occurred after I add checkboxGroupInput.

library(ggplot2)
library(plotly)
library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(
    titlePanel("Phone Usage Time"),
    # select students to display on plot -> error occurred
    checkboxGroupInput("names", "Students to show:",
                     c("Luyi", "Minruo", "Xiaojue", "Xudian", "Ziyuan")),
    plotlyOutput("plot")
)

# Define server logic required to draw a histogram
server <- function(input, output) {
      output$plot <- renderPlotly({
        # load data
        phone_time <- read.csv("PhoneTime.csv")
        colnames(phone_time) <- c("Name", 2.20, 2.21, 2.22, 2.23, 2.24, 2.25, 2.26)
        # wide to long
        phone_df <- tidyr::gather(phone_time, date, usage_time, 2:8)
        phone_df$date <- as.numeric(phone_df$date)
        # change column name
        colnames(phone_df) <- c("Student.Name", "Date","Usage.Time")
        # subset by student -> where things go wrong!
        phone_sub <- phone_df[which(phone_df$Student.Name == input$names), ]

        # interactive plot
          ggplotly(
            ggplot(phone_sub) + 
              geom_point(aes(x = Date, y = Usage.Time, color = Student.Name)) +
              geom_line(aes(x = Date, y = Usage.Time, color = Student.Name)) +
              labs(title = "Daily Phone Usage Time in a Week", x = "Date", y = "Usage Time") +
              scale_x_continuous(breaks = seq(2.20, 2.26, 0.01), 
                           labels = c("2.20", "2.21", "2.22", "2.23", "2.24", "2.25", "2.26")) +
              ylim(5, 20) +
              theme_bw()
          )
    })
}

# Run the application 
shinyApp(ui = ui, server = server)



Confirm Checkbox Via Alert

I am trying to make a checkbox become checked/Not checked after a user confirms via a model.

The user would click a checkbox, then be prompted by an alert that says "Accept" to check the box or "Cancel" to uncheck or not allow the checkbox to check.

I am using the Package React Confirm Alert with Informed for my forms.

I have created a Sandbox here https://codesandbox.io/s/hardcore-sara-j34x8

My code is below.

 const Bear = () => {
    confirmAlert({
      title: "Confirm to submit",
      message: "Are you sure to do this.",
      willUnmount: () => {},
      buttons: [
        {
          label: "Yes",
          onClick: e => {
            //console.log("True");
            // return true;
          }
        },
        {
          label: "No",
          onClick: e => {
            console.log("false");
            return false;
          }
        }
      ]
    });
  };
eturn (
    <div className="App">
      <label className="saAdminCheckBoxLabel">
        <Checkbox
          onClick={e => {
            Bear();
          }}
          field="arecNeutral"
        />
        <span>Neutral USE THIS ONE</span>
      </label>
    </div>
  );
}



Defining checkbox based on value in URL query string

Traffic is driven to one of our pages with a query string that includes a 'campaign' value. There are 12 different campaign values possible. Here's an example:

www4.foo.com/p3423?campaign=30&cid=4401&lid=342&etrack=54tr88

When the campaign value is equal to 30, like in the example above, the checkbox needs to appear with the following label:

Category: Television

For the label, the category would be defined in the 'prefix' variable.

var prefix = "Category: ";

The checkbox code I'm working with looks like this:

<li id="showCampaignCheck"> 
<div class="checkbox">
  <input type="checkbox" id="campaign_topic" name="campaign_topic_mediaTelevision" value="on" class="check custom-class" oninvalid="this.setCustomValidity('Please make selection')">
  <label for="subscription"><span>Category: Television</span>
  </label>
</div>
</li>

So each category has to have the following defined:

Category: 30
topic   : prefix + "Television",  
idAttr  : "tv",
name    : "tv"

These values would be used to create the checkbox.

What is an efficient way to code this out, preferably using jQuery?




Django 2.2 How to disable checkboxes in list view

Django 2.2

I have a list view controlled by admin.py class. No custom template, all default. I can control what fields from the table should be shown in the view with this: fields = ('myfield1','myfield2', ...).

Each row in the list table has a checkbox in the first column:

    <td class="action-checkbox">
      <input type="checkbox" name="_selected_action" value="123" class="action-select">
    </td>

My questions are:

  1. How to disable those checkboxes ?

  2. Can it be done for SOME of the checkboxes (let's say I have a list of pk ids for the rows I don't want to see checkboxes.)




automatically uncheck checkbox when checking another react native

I have two checkboxes (from react-native elements), let's call them box a and box b, where it should only be possible to have one of them checked at a time (no multiple selection), iow - if box a is checked, it is not possible to check box b. So as of this moment, if I were to have checked box a by mistake, I need to uncheck box a manually by clicking it again, in order to check box b. However, I want to be able to automatically uncheck box a by clicking and checking box b - if that makes any sense.

I have tried to look at both issue 54111540 and others, but none of the answers there seem to help with what I want to achieve.

My code:

import React, { useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, } from 'react-native';
import { CheckBox } from 'react-native-elements';
import { Ionicons } from '@expo/vector-icons';
import { slider } from '../../components/SliderStyle';
import { useDispatch } from 'react-redux';
import { addfirstrole } from '../../redux/actions/index';
import store from '../../redux/store';
import * as firebase from 'firebase';

const RoleScreen = ({ navigation }) => {

const dispatch = useDispatch()
const addFirstRole = firstRole => dispatch(addfirstrole(firstRole))

const [landlordChecked, setLandlordChecked ] = useState(false)
const [tenantChecked, setTenantChecked] = useState(false)

const user = firebase.auth().currentUser

return (
  <View>
    <Text>Role screen</Text>
    <CheckBox
      title='Jeg er utleier'
      checkedIcon='dot-circle-o'
      uncheckedIcon='circle-o'
      checked={landlordChecked}
      onPress={tenantChecked ? () => setLandlordChecked(false) : () => setLandlordChecked(!landlordChecked)}
    />
    <CheckBox
      title='Jeg er leietaker'
      checkedIcon='dot-circle-o'
      uncheckedIcon='circle-o'
      checked={tenantChecked}
      onPress={landlordChecked ? () => setTenantChecked(false) : () => setTenantChecked(!tenantChecked)}
    />
    <TouchableOpacity onPress={() => { navigation.navigate('Search'); addFirstRole(user.uid); console.log(store.getState()); }}>
      <View style={slider.buttonStyle}>
        <Text style={slider.textStyle}>Neste</Text>
        <Ionicons name='ios-arrow-forward'style={slider.iconStyle} />
      </View>
    </TouchableOpacity>
  </View>
 )
} 

const styles = StyleSheet.create({})

export default RoleScreen;



How to check / un check the checkbox depends on value in checkbox using jquery? [closed]

<input type="checkbox" name="allowedEntireDay_<?php echo $shortDay; ?>" class="allowedEntireDay" 
<?php
$key = "allowedEntireDay_" . $shortDay;
echo (!isset($targetedAd[$key]) || (isset($targetedAd[$key]) && $targetedAd[$key] == "on")) ? 'checked' : "";
?>>

This is my HTML code $shortDay and $targetedAd[$key] the two parameter from backend . In my code when value set 'on' checkbox need to tick , if 'off' set in value checkbox need to untick . In my case 'on' 'off' are set in the value But check and uncheck are not work .

java script

$("input:checkbox[name='allowedEntireDay_Tu']")
    .val(response.targetedAd.allowedEntireDay_Tu)
    .prop('checked', true);



Which is the best way to get all selected checkbox values on main page in angular 6

I am trying to get selected checkbox values, but I am getting last checkbox value only not all selected checkbox values. I have multiple values in array. Whatever checkbox I am selecting its values is showing in console but its not filtering all selected checkbox. Angular 6




mercredi 26 février 2020

How to save a boolean value in Laravel 6?

I have

Migration file:

public function up()
{
    Schema::create('bookings', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('user_id');
        $table->string('name');
        $table->string('phone');
        $table->boolean('wifi');
        $table->string('address');
        $table->text('desc');
        $table->timestamps();
    });
}

BookingController.php's store method:

public function store()
    {
        $booking = new Booking();
        $booking->user_id = 1;
        $booking->name = request('name');
        $booking->phone = request('phone');
        $booking->wifi = request('wifi');
        $booking->address = request('address');
        $booking->desc = request('desc');
        $booking->save();

        return redirect('/bookings');
    }

create.blad.php's the part of wifi checkbox:

<div class="field">
   <label for="wifi" class="label">Wi-Fi</label>
   <div class="control">
      <input type="checkbox" class="form-check" name="wifi" id="address">
   <div>
</div>

When I trying creating a record, I'm getting error:

1) I'm trying to save a value as FALSE:

Illuminate\Database\QueryException SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'wifi' cannot be null (SQL: insert into bookings (user_id, name, phone, wifi, address, desc, updated_at, created_at) values (1, Dragon, 12341234, ?, asdfasdfasdkf hsadfasdf, asdfasdfas, 2020-02-27 07:10:55, 2020-02-27 07:10:55))

2) And when I checked Wi-Fi checkbox (TRUE value)

Illuminate\Database\QueryException SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: 'on' for column kaganat.bookings.wifi at row 1 (SQL: insert into bookings (user_id, name, phone, wifi, address, desc, updated_at, created_at) values (1, Dragon, 12341234, on, asdfasdfasdkf hsadfasdf, asdfasdfasdfsafaa, 2020-02-27 07:17:15, 2020-02-27 07:17:15))




Don't complete checkbox until after modal is Accepted

I want to create a confirmation with a checkbox. Unfortunately, we are having an issue where no matter what we do when we click cancel, the checkbox still checks.

We can prevent it initially but can't get it after.

We are using Informed for our Forms & react-confirm-alert for our notification package.

I have attached a sandbox https://codesandbox.io/s/hardcore-sara-j34x8?fontsize=14&hidenavigation=1&theme=dark

`

 const Bear = () => {

confirmAlert({
  title: 'Confirm to submit',
  message: 'Are you sure to do this.',
  willUnmount: () => {

  },
  buttons: [
    {
      label: 'Yes',
      onClick: (e) => {
        // console.log('True');
        // return true;
      },
    },
    {
      label: 'No',
      onClick: (e) => {
        return false;
        console.log('false');
      },
    },
  ],
});
};`
      <label className="saAdminCheckBoxLabel">
        <Checkbox
          onClick={(e) => {
            e.preventDefault();
            Bear();
          }}
          field="arecNeutral"
        />
        <span>Neutral USE THIS ONE</span>
      </label>



Semantic-ui preset checkbox state

I've got a simple semantic-ui checkbox as follows:

<div id="del-checkbox-div" class="ui checkbox">
   <input type="hidden" value="0" name="delete_show_data" onclick=check()>
   <input id="delete-data-checkbox" type="checkbox" value="1" name="delete_show_data" onclick=check()>
   <label for="delete-data-checkbox">Delete show data</label>
</div>

I'd like to preset its state on page load. Per the semantic-ui documentation I should be able to do the following in javascript:

jQuery('#del-checkbox-div').checkbox('behavior', 'uncheck');

However, I'm getting the following error:

TypeError: jQuery(...).checkbox is not a function

Can someone clue me in as to what I might be doing wrong?




angular chekcbox is checked change other input value

I want to find a solution that if I check a checkbox then the value of the input field in another div will change to disabled.

``

<div class="24hr-example">
        <input placeholder="24hr format" aria-label="24hr format" [ngxTimepicker]="fullTime" [format]="24"  readonly>
        <ngx-material-timepicker #fullTime></ngx-material-timepicker>
   </div>

``

<app-checkbox [checked]="openingHours.is_closed_all_day" (change)="openingHours.is_closed_all_day = !openingHours.is_closed_all_day"></app-checkbox>

So if I click on the checkbox then the value of the input field given will be taken as disabled. I've tried to solve it with a function, but it couldn't work. What solution is possible to solve this?




How can I set numbers that equals days of month [duplicate]

First of all, I'm sorry if im explaining it too bad, but I'm at least trying...

I have a table with checkboxes, https://i.stack.imgur.com/K0xPv.png code is like that:

<td>
<?php 
    $date = date('Y-m-d');
    $k = $date;
    for($k=8; $k<=31; $k++){
?>
</td>
<td>
<?php 
        for($k=1; $k<=31; $k++){
?>
<td>

How can I get change these numbers to calendar numbers, because I want it to begin not with 1, but with the day that is today.

I hope i did ask a question right, if not, please, feel free to comment for more details




Bokeh plot not updating with checkboxgroup.on_change()

I am plotting a name frequency figure with Bokeh and all of my code works perfectly apart from one issue with checkboxgroup. The current issue is that the new plot is not updating when updating my checkboxgroup. I have simplified the code below to only include the checkbox part. My code is split into two parts: 1) A main function and 2) callbacks. I have been looking around and seen that this is an ongoing issue, but to me it seems that I am doing as people are suggesting. I am deploying the figure on a local host.

To me it seems that it would be enough to only update the data source, but I have also made a new plotting callback, but still nothing happens and no error is returned. The main file is ran only once, which is the very first time and then the callbacks are used to update the data and plot. The callbacks are basically a copy of what is happening in the main file.

I would really appreciate some help for this one. I hope that everything is clear.

I am using python 3.7 and bokeh 4.0.

Main

from bokeh.palettes import d3
from bokeh.layouts import layout, gridplot, column, row
from bokeh.plotting import figure
from bokeh.document import Document
from bokeh.models.widgets import inputs, Div, CheckboxGroup
from bokeh.models import ColumnDataSource, Column, Button, CDSView, GroupFilter, Select, Range1d, Legend

import pytz
import pandas as pd
import datetime as dt
import numpy as np
from functools import partial

from utils.server import run_server
from utils.functions import load_names, get_name_freq, make_plot
from utils.callbacks import *


names = ['VEvaa', 'Drugnas', 'Polace', 'WERTB']

def document(doc: Document):

    timezone = pytz.utc
    sd = dt.datetime(2015,1,1, tzinfo=timezone)
    ed = dt.datetime(2020,4,1, tzinfo=timezone)

    # check_box_group
    selection = CheckboxGroup(labels = names, active = [2,3])

    # get data
    names = load_names(start_date=sd, end_date=ed)
    names = names[names['Name'].isin(selection.labels)]

    values.names_PQ = get_name_freq(names)
    source_DA = ColumnDataSource(data = values.names_PQ)


    # Plot
    plot_name_freq = figure(plot_width = 1200, 
                           plot_height = 400, 
                           x_range = Range1d(sd, ed), 
                           y_range = Range1d(0, 5.2),
                           y_axis_label = 'Day Ahead Price Volatility',
                           x_axis_type = 'datetime')

    for c in [selection.labels[i] for i in selection.active]:
        view_DA = CDSView(source = source_DA, filters = [GroupFilter(column_name = 'Name', group = c)])

        plot_name_freq.line(source = source_DA, 
                           x = 'TradeGasDay', 
                           y = 'Volatility', 
                           view = view_DA,
                           line_color = mypalette[selection.labels.index(c)], 
                           line_width = 2,
                           legend_label = c)

    # import callbacks
    all_arguments = dict(doc = doc, names_PQ = source_DA, selection = selection)

    selection.on_change('active', update_checkbox_callback(**all_arguments))


    # arrange elements in page
    menu = Column(app_header, selection)

    doc.add_root(layout(row(menu, plot_name_freq)))

if __name__ == "__main__":
    run_server(document, ioloop = None, port = 8055)

Callbacks

import datetime as dt  # type: ignore
import pandas as pd  # type: ignore
from bokeh.models import ColumnDataSource, CDSView, GroupFilter, Range1d, Column
from utils.functions import load_names, get_name_freq, make_plot
from bokeh.models.widgets import inputs
from bokeh.palettes import d3
import pytz
from bokeh.plotting import figure
from bokeh.layouts import layout

class App_Values():
    def __init__(self):
        self.prices = pd.DataFrame()


values = App_Values()

def update_checkbox_callback(**kwargs):
    def update_checkbox(attr, old, new):

        timezone = pytz.utc
        sd = dt.datetime(2015,1,1, tzinfo=timezone)
        ed = dt.datetime(2020,4,1, tzinfo=timezone)

        # Get the list of carriers for the graph
        labels = [kwargs['selection'].labels[i] for i in kwargs['selection'].active] 

        names = load_names(start_date = sd, end_date = ed)
        names = names[names['Name'].isin(labels)]

        names_PQ = get_name_freq(names)
        values.names_PQ = names_PQ

        kwargs['doc'].add_next_tick_callback(update_plot(**kwargs))

    return update_checkbox

def update_plot(**kwargs):

    def callback():

        new_src_DA = ColumnDataSource(data = values.names_PQ, id = 'names_PQ')

        kwargs['names_PQ'].data.update(new_src_DA.data)

        timezone = pytz.utc
        sd = dt.datetime(2015,1,1, tzinfo=timezone)
        ed = dt.datetime(2020,4,1, tzinfo=timezone)

        mypalette = d3['Category20'][13]

        plot_name_freq = figure(plot_width = 1200, 
                               plot_height = 400, 
                               x_range = Range1d(sd, ed), 
                               y_range = Range1d(0, 5.2),
                               y_axis_label = 'Day Ahead Price Volatility')


        selection = [kwargs['selection'].labels[i] for i in kwargs['selection'].active]

        for c in selection:
            print('looping')
            view_DA = CDSView(source = kwargs['names_PQ'], filters = [GroupFilter(column_name = 'Name', group = c)])
            print(view_DA.to_json_string(True))
            plot_name_freq.line(source = kwargs['names_PQ'], 
                               x = 'TradeGasDay', 
                               y = 'Volatility', 
                               view = view_DA,
                               line_color = mypalette[kwargs['selection'].labels.index(c)], 
                               line_width = 2,
                               legend_label = c)

    return callback



C# Dynamically Creating Checkboxes is too slow

I am currently creating a permission form in Windows C# and the purpose of this screen is to have a matrix of checkboxes, column being each userGroup and row being each report.

I have designed the screen, creating dynamically as many checkboxes as userGroups x reports. However the time it takes to load the screen is very slow. (Around 400 checkboxes currently)

Here is my code:

        Label lblU;
        Label lblR;
        Label line;           

        for (int u = 0; u < userGroups.Count; u++)
        {
            lblU = new Label();
            ...
            lblU.Location = new Point(60 + (u * 100) , 10);
            this.Controls.Add(lblU);
        }

        for (int r = 0; r < allReports.Count; r++)
        {
            lblR = new Label();
            ...
            lblR.Location = new Point(10, 60 + (r * 80));
            this.Controls.Add(lblR);
        }

        for (int r = 0; r < allReports.Count; r++)
        {
            line = new Label();
            ...
            line.Location = new Point(10, 40 + (r * 80));
            this.Controls.Add(line);
        }

        CheckBox box;
        for (int u = 0; u < userGroups.Count; u++)
        {
            for (int r = 0; r < allReports.Count; r++)
            {
                box = new CheckBox();
                ...
                box.Location = new Point((u * 100) + 60, 60 + ((r * 80) + 25));
                this.Controls.Add(box);
            }
        }

I tried other controls, such as CheckedListBox, but they couldn't achieve what I want e.g. there are no functionality in CheckedListBox to separate checkboxes as I want per column.

What is the most efficient way to cut down on loading time?

PS: I am also having Infragistics controls 14.2




Remove item when unchecked checkbox

I have checkbox with a couple item in it, when i click the check box the item will add to state called currentDevice, but when i unchecked the item it keep add item and not remove it.

How do i remove item from state when i unchecked the box. Im using react-native-element checkbox. Thankyou before

The code:

constructor(props) {
super(props)
this.state = {
currentDevice: [],
checked: []
 }
}

handleChange = (index, item) => {
    let checked = [...this.state.checked];
    checked[index] = !checked[index];
    this.setState({ checked });

    this.setState({currentDevice: [...this.state.currentDevice, item.bcakId]})
  }

renderFlatListDevices = (item, index) => {
    return (
      <ScrollView>
      <CheckBox
        title={item.label || item.bcakId}
        checked={this.state.checked[index]}
        onPress={() => {this.handleChange(index, item)}}
        checkedIcon='dot-circle-o'
        uncheckedIcon='circle-o'
        checkedColor='#FFE03A'
        containerStyle={styles.containerCheckBox}
        textStyle={styles.textCheckBox}
      />
    </ScrollView>
    )
  }



Filtering data WITHOUT checkboxes using jquery

I managed to filter results using jquery and checkboxes. My problem is when I use a style checkbox, it stops working.

Below is my code

$('input[type="checkbox"]').click(function() {
if ($('input[type="checkbox"]:checked').length > 0) {
    $('.searchresults >div').fadeOut(500);
    $('input[type="checkbox"]:checked').each(function() {
        $('.searchresults  >div[data-category=' + this.id + ']').fadeIn(600);
    });
} else {
    $('.searchresults >div').fadeIn(650);

}
});

this works fine when the filter is standard checkbox like this:

<input type="checkbox" id="horror" value="horror" /> Horror<br />

but fails when this is the code:

<input id="drama" type="checkbox" class="icheck" value="" />

because the class icheck modifies the html like this:

<div class="checkbox theme-search-results-sidebar-section-checkbox-list-item">
                      <label class="icheck-label">
                        <div class="icheck" style="position: relative;"><input class="icheck" type="checkbox" style="position: absolute; opacity: 0;"><ins class="iCheck-helper" style="position: absolute; top: 0%; left: 0%; display: block; width: 100%; height: 100%; margin: 0px; padding: 0px; background: rgb(255, 255, 255); border: 0px; opacity: 0;"></ins></div>
                        <span class="icheck-title">EWR: Newark</span>
                      </label>
                      <span class="theme-search-results-sidebar-section-checkbox-list-amount">276</span>
                    </div>

can anybody suggest if the same filtering can be achieved by not using checkboxes but using span id's perhaps?




mardi 25 février 2020

Override the way the checkbox changes in Virtual TreeView

I am using Virtual TreeView. It seems that Virtual TreeView will automatically update the node check state when its children check states are changed. Is there a way to prevent this?

Thanks




Check state in Virtual TreeView seems not virtual

I am using Virtual TreeView. In my understanding, since the whole treeview is virtual, the node properties(including the check state) are set on request(such as on a OnData event handler) instead of storing together with the node, since the node is total virtual. However, it seems that Virtual TreeView will store the check state of the node together with the node, instead of obtain from external data source and set on request.

Why?




CSS checkboxes with slanted labels

I've been trying to achieve checkboxes with slanted text like the image below (where some level of overlapping is necessary):

checkboxes with slanted text

With using the transform styling and setting margins I have been able to get the text to be at the same vertical level, however I am having issues offsetting the elements horizontally so that they appear beside each other.

(this is inside a dynamic table where the rows will be duplicated, which is why I used "span" instead of "label for" to avoid the complications with generating unique id's for all checkboxes)

table tbody {
  display: block;
}

.angled_text {
  display: block;
  margin-top: -18px;
  transform:         rotate(-45deg);

  /* legacy */
  -webkit-transform: rotate(-45deg);
  -moz-transform:    rotate(-45deg);
  -ms-transform:     rotate(-45deg);
  -o-transform:      rotate(-45deg);
}
<!DOCTYPE html>
<html lang="en">
<body>
  <table id="dynamic_table">
    <tbody>
      <tr>
        <td>
          <span class="angled_text">Monday</span>
          <span class="angled_text">Tuesday</span>
          <span class="angled_text">Wednesday</span>
          <span class="angled_text">Thursday</span>
          <span class="angled_text">Friday</span>
          
          <br>
  
          <input type="checkbox" name="monday" value="monday">
          <input type="checkbox" name="tuesday" value="tuesday">
          <input type="checkbox" name="wednesday" value="wednesday">
          <input type="checkbox" name="thursday" value="thursday">
          <input type="checkbox" name="friday" value="friday">
        </td>
      </tr>
    </tbody>
  </table>
</body>
</html>



Angular 9 cannot check or uncheck checkbox

I have a table that is populated from an array coming from an API. The next thing I want to do is to add some checkboxes in a tab next to the table to filter data in the table. I'm adding the checkboxes dynamically because until the array comes from the API I don't know the filters (I know the category of the filters. ie Country or Language, but I don't know which countries or which languages will come in the array).

So, the problem is that I am trying to have a formArray to contain the checkboxes and I add to them programmatically as soon as I know what the values for the filters will be. But, when I try to click (just with my mouse) on the generated checkboxes I cannot. It doesn't check or uncheck.

However, if I just add the checkboxes without the formArray I can check and uncheck to my hearts content.

Here is my html for when I cannot check or uncheck (initially all of them are checked)

<form [formGroup]="languageForm">
    <div *ngIf='results && results.length'>
        <div class=" custom-control custom-checkbox mb-3" *ngFor="let item of languageForm.controls.filters.controls; let i = index" formArrayName="filters">
            <input class=" custom-control-input" [formControlName]="i" id="i" type="checkbox" />

            <label class=" custom-control-label" [for]="i">
                
            </label>
        </div>
    </div>
</form>

Here is the html (for the one that does work)

<div *ngIf='results && results.length'>
    <div class=" custom-control custom-checkbox mb-3" *ngFor="let item of f_countries; let i = index">
        <input class=" custom-control-input" id="" type="checkbox" />

        <label class=" custom-control-label" for="">
            
        </label>
    </div>
</div>

Here is the TS for both (for the sake of the example I will make the filters static)

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.scss']
})
export class SearchComponent implements OnInit {
  f_countries = [
    {label: 'United States', value: 'US' },
    {label: 'United Kingdom', value: 'UK' },
    {label: 'Germany', value: 'DE' },
    {label: 'Philippines', value: 'PH' }
  ];

  f_languages = [
    {label: 'English', value: 'EN' },
    {label: 'German', value: 'DE' },
    {label: 'French', value: 'FR' },
    {label: 'Spanish', value: 'ES' }
  ];

//constructor omitted but nothing interesting there

ngOnInit() {
    // search form init and other things
    this.languagesForm = this.formBuilder.group({
      filters: new FormArray([])
    });
}

doSearch(): void {
    this.searchService.search(this.searchForm.get('country').value, this.searchForm.get('language').value)
        .subscribe(results => {
            this.results = results;
            this.slicedResults = this.results.slice(0, this.pageSize);

            //load the filters
            this.initializeFilters();
        });
}

initializeFilters(): void {
    //normally here the mapping from results to the filters 
    //but omitted since I said that for the example the filters are static

    this.f_languages.forEach((o, i) => {
      const control = new FormControl(true);
      (this.languagesForm.controls.filters as FormArray).push(control);
    });
  }

Thanks in advance for all the help, I'm sure it's something stupid that I just cannot see anymore after staring at it for so many hours.




How to change label styling on checkbox :checked

I'm currently building a form that has checkboxes wrapped inside of labels. We are doing this because we need to swap our the original checkbox for an image. However, when the checkbox is checked, we need to make the label have a border to give some user feedback.

Here is the setup of the labels/checkboxes

<div class="one_column">
    <label for="fieldname2_1_cb0">
      <input name="fieldname2_1[]" id="fieldname2_1_cb0" class="field depItem group  required" value="Alloy Wheel(s)" vt="Alloy Wheel(s)" type="checkbox"> <span>Alloy Wheel(s)</span>
    </label>
</div>

We have tried going about is using the following but obviously doesn't work

label input[type="checkbox"]:checked + label {
border: 5px solid blue;
}

Any help would be appreciated!




Typescript - Check values in one array are present in another

I have the following array. I am using this array to dynamically produce checkboxes on my UI. This is being used to save user config as to what they will be able to see in a nav menu.

  accessLevels: any = [
    {
      description: "Properties",
      type: '1',
      selected: false
    },
    {
      description: "Equipment",
      type: '2',
      selected: false
    },
    {
      description: "Jobs",
      type: '3',
      selected: false
    },
    {
      description: "Calender",
      type: '4',
      selected: false
    }
]

I am making a call to an API which returns me an array of the users config. So what I will get is an array of the pages and their type like this:

    {
      description: "Equipment",
      type: '2'
    },
    {
      description: "Jobs",
      type: '3'
    }

In the array returned from the API I am just getting the values that should appear checked on the check boxes so what I want to do is loop through the returned array and check if any of the types match any types in the checkbox array if they do I want to set 'selected' to true. Thus checking the checkbox.

Here is what I have so far:


  async loadLandlordConfig(key: string) {

    const result = await this.userService.loadLandlordConfig(key);

    //let accessLevels = [];

    this.selectedApiValues = result[0].accessLevels;

    this.selectedApiValues.forEach((selectedValue)=> {

    });
  }

Im not sure how to cross check the values and then change selected to true.

Hope I have made everything clear enough. Any questions please ask. All help appreciated.




Shiny: Select single row in DT with checkbox

In the example here there is an example of how to select rows with a checkbox: R Shiny, how to make datatable react to checkboxes in datatable

That works fine. But I need to only be able to select a single row.


I got close but there are two problems:

  1. when a box is ticked the reactive is trigger twice. I don't understand why. But then again I don't understand what activates the reactive since I don't see the input directly inside the reactive...
  2. If I click on the same box twice the selection is not really updated.


Any clue appreciated.

What I got so far. I also have a feeling I am over complicating things.

library(shiny)
library(DT)
shinyApp(
  ui = fluidPage(
    DT::dataTableOutput('x1'),
    verbatimTextOutput('x2')
  ),

  server = function(input, output, session) {
    # create a character vector of shiny inputs
    shinyInput = function(FUN, len, id, value, ...) {
      if (length(value) == 1) value <- rep(value, len)
      inputs = character(len)
      for (i in seq_len(len)) {
        inputs[i] = as.character(FUN(paste0(id, i), label = NULL, value = value[i]))
      }
      inputs
    }

    # obtain the values of inputs
    shinyValue = function(id, len) {
      unlist(lapply(seq_len(len), function(i) {
        value = input[[paste0(id, i)]]
        if (is.null(value)) FALSE else value
      }))
    }

    n = 6
    df = data.frame(
      cb = shinyInput(checkboxInput, n, 'cb_', value = FALSE, width='1px'),
      month = month.abb[1:n],
      YN = rep(FALSE, n),
      ID = seq_len(n),
      stringsAsFactors = FALSE)

    df_old <- df


    loopData = reactive({


      checked <- shinyValue('cb_', n)

      changed <- which((checked-df_old$YN)!=0)

      print(checked)
      print(changed)

      if(length(changed)==0){ df 
        }else{


      df$cb <<- shinyInput(checkboxInput, n, 'cb_', value = rep(FALSE, n), width='1px')
      df$YN <<- FALSE

      df$YN[changed] <<- checked[changed]
      df$cb[changed] <<- shinyInput(checkboxInput, length(changed), 'cb_', value = df$YN[changed], width='1px')


      df_old <<- df
      df
        }

    })

    output$x1 = DT::renderDataTable(
      isolate(loopData()),
      escape = FALSE, selection = 'none',
      options = list(
        dom = 't', paging = FALSE, ordering = FALSE,
        preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
        drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')
      ))

    proxy = dataTableProxy('x1')

    observe({
      replaceData(proxy, loopData(), resetPaging = FALSE)
    })

    output$x2 = renderPrint({
      data.frame(Like = shinyValue('cb_', n))
    })
  }
)



Revert a Checkbox value in the ChkBoxGroup_Click event

I have multiple checkboxes created, and I would like to prompt the users when they CLICK on the checkbox. They can only change the value of the check box with the correct PIN. If they enter a incorrect PIN, the checkbox will revert back to it's original value. However every time when it try to revert the checkbox value, it seems like it recursively calling the ChkBoxGroup_Click() event until a correct password is entered.

Private Sub ChkBoxGroup_Click()
    Dim ValidatePIN_RNT As Boolean

    ValidatePIN_RNT = ValidatePIN()
    If Not ValidatePIN_RNT Then
        ChkBoxGroup.Value = Not ChkBoxGroup.Value
        Exit Sub
    End If
End Sub



To create and update attendance system in laravel.. Having issue in array storing

I have undergoing a project of student management system where i have certain number of batches for month so each batch will have a max of 20 students, As well as each batch will have certain dates (Morning session and Afternoon session). For Example : Batch A will have 18 Students and will have 3 dates like DD-MM-YYYY, DD-MM-YYYY, DD-MM-YYYY. As a admin i need to register attendance for each student, each batch, each date and each session.

It means i have a consolidated screen for one batch including students, dates and sessions.

when i click batch it should show the batch students as well as batch dates, under batch dates there should be check box when i click the checkbox it should be marked as present, if not should be marked as absent.

It is in the table view where header consists of dates. While the body rows consists of student name and checkbox matching the dates column.

All the datas should be posted in one go and also need to retrieve and update the datas.

I have tried using array to store the datas but all the datas storing into the database are not stored according to the need.

How to achieve this?

Tried codes are below..

In Controller..

public function get_add($id)
{
    $module = $this->module;

    $singleData = $this->batch->find($id);
    return view('admin.'.$module.'.add_edit', compact('singleData', 'module'));
}

public function post_add(Request $request, $id)
{
    $module = $this->module;
    // $this->attendance->fill($request->all());

    $dd = $request->schedule_id;
    if($dd){
        foreach($request->schedule_id as $key => $v){
            $data = array(
                'batch_id' => $id,
                'schedule_id' => $request->schedule_id [$key],
                'user_id' => $request->user_id [$key],
                'am_attendance_status' => isset($request->am_attendance_status [$key]) ? 1 : 0,
                'pm_attendance_status' => isset($request->pm_attendance_status [$key]) ? 1 : 0,
                'created_at' => new DateTime,
                'updated_at' => new DateTime,
            );
            // dd($data);
            Attendance::insert($data);
        }
      return redirect('admin/'.$module.'/')->with('success', 'Data has been updated');
    }else{
      return redirect('admin/'.$module.'/')->with('error', 'Data has not been updated');
    }

}

In Modal..

<?php namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;

class Attendance extends Authenticatable
{
   use SoftDeletes;
   protected $dates = ['deleted_at'];

   protected $table = 'attendance';
   protected $fillable = ['batch_id', 'schedule_id', 'user_id', 'am_attendance_status', 'pm_attendance_status'];

   public function user()
   {
     return $this->belongsTo('App\User', 'user_id');
   }

  public function batch()
   {
    return $this->belongsTo('App\Batch', 'batch_id');
   }

   public function schedule()
   {
     return $this->belongsTo('App\Schedule', 'schedule_id');
   }

 }

In Route..

 //Attendance
Route::get('attendance', 'Admin\AttendanceController@get_index');
Route::get('attendance/{id}/add', 'Admin\AttendanceController@get_add');
Route::post('attendance/{id}/add', 'Admin\AttendanceController@post_add');

In View..

<div class="table-responsive text-center">
<table id="dataTable" class="table table-bordered table-hover" style="white-space: nowrap;">
    <thead>
        <th>#</th>
        <th>NRIC</th>
        <th>Student Name</th>
        @foreach($singleData->schedule as $list)
        <th class="text-center" colspan="2"></th>@endforeach
    </thead>
    <thead>
        <th></th>
        <th></th>
        <th></th>
        @foreach($singleData->schedule as $list)
        <th class="text-center"></th>
        <th class="text-center"></th>
        @endforeach
    </thead>
    @php $students = App\StudentHasCourse::with('user')->where('batch_id', $singleData->id)->get(); @endphp
    <?php $count = 0; ?>
        @foreach($students as $row)
        <?php $count++; ?>
            <tr>
                <th style="font-weight: normal;"></th>
                <th style="font-weight: normal;">@foreach($row->user->student as $stud)  @endforeach</th>
                <th style="font-weight: normal;"></th>
                @foreach($singleData->schedule as $list)
                <input type="hidden" name="batch_id[]" value="">
                <input type="hidden" name="user_id[]" value="">
                <input type="hidden" name="schedule_id[]" value="">
                <td>
                    <input type="checkbox" name="am_attendance_status[]" value="1">
                </td>
                <td>
                    <input type="checkbox" name="pm_attendance_status[]" value="1">
                </td>
                @endforeach
            </tr>
            @endforeach
</table>

Database Fields..

id 
user_id 
batch_id 
schedule_id 
am_attendance_status 
pm_attendance_status 
created_at 
updated_at 
deleted_at

View image link.. https://ibb.co/r485jYX




lundi 24 février 2020

Changing checkbox styling in css

I have a checkbox that needs different custom styling to different conditions. I was able to customise the check box using following css

.custom-control-lg .custom-control-label::before,
.custom-control-lg .custom-control-label::after {
    top: 0.1rem !important;
    left: -2rem !important;
    width: 2rem !important;
    height: 2rem !important;
    overflow: hidden;
    border: none;
    background-color: $buttonBack;
}

.custom-control-lg .custom-control-label {
    margin-left: 0.5rem !important;
    font-size: 1rem !important;
    line-height: 2rem;
    padding-left: 10px;
    font-size: 14px !important;

}

.custom-control-label:before{
    background: rgba(24, 68, 119, 0.2) !important;
    border: none !important;
    box-shadow: none !important;
  }
.custom-checkbox .custom-control-input:checked~.custom-control-label::before{
    background-color:$evcCardLightBlue !important;
    box-shadow: none !important;
  }

my checkbox code is implemented like follows

 <div class="custom-control custom-checkbox my-1 pl-0">
   <input type="checkbox" name="vehicle2"
     checked={stationIdArray.length !== 0 && groupIdArray && groupIdArray.some(e => e.groupIdz.groupId === groupId)}
     onClick={() => this.addEvcGroupToArray(item.stations.map((item, key) => {
      return (item.stationID)
     }), groupId)}
     className="custom-control-input"
     id={`'group'${item.groupId}`} />
     <label className="custom-control-label"
      for={`'group'${item.groupId}`}></label>
</div>

currently the color i have given for this check box is blue. I need to change it to red on certain conditions. How can i do this? As you can see my id is also dynamic so cannot be used in css.




Triggering a link via a checkbox in only HTML and Javascript

Is there a way of launching a link from clicking/tapping on a checkbox with only HTML and CSS (no JavaScript)?

I'm scripting something for personal use and looking for a way to launch a URL scheme by checking a checkbox.

It is trivial to write a checkbox that "has" a link:

<a href="kmtrigger://macro=some%20macro"><input type="checkbox" name="checkbox" id="done" value="value"></a> Test

Hovering over the checkbox reveals the link (as shown in this CodePen sample of the above code). Still, I cannot get the link to launch. It seems like the checkbox action "absorbs" clicks.

I have tried giving the link a higher z-index, but it had no effect.

(There are other ways of achieving this that I will probably pursue, but this is the simplest if it is possible!)




Change DataGridView Column Cells from CheckBox to String

Okay, so I have a DataGridView in which the third column, index 2, is a checkbox column, with some checkboxes checked, and some checkboxes unchecked, but instead of that, i want to show a string value depending if the value of the cell is true or false.

This is the problem

My DataGridView DataSource is a DataTable. Here is the method that gets the datatable for the DataGridView.DataSource.

public static DataTable DevolverInfoFuncionarios()
        {
            DataTable dtFuncs = new DataTable();


            string select_all_Funcs = "select IDFuncionario, Nome, is_gerente from Funcionarios";
            using (SqlCommand sql_com = new SqlCommand(select_all_Funcs, conexao))
            {
                conexao.Open();
                SqlDataReader dr = sql_com.ExecuteReader();
                dtFuncs.Load(dr);
                conexao.Close();
            }

            return dtFuncs;
        }

Helpp




inserting checkbox value to database

i have 2 checkboxes whose values i am sending from ajax to controller to post the data(approved/reject) in database now i want that if both the checkboxes are unchecked pending should be inserted in database and also if i uncheck the checked box the value should be updated again to pending.what can be the logic

html

<td> <input type="checkbox" id="APPROVED_" class="approve_chk" name="chkBestSeller" value="APPROVED"  data-id=""></td>
<td> <input type="checkbox" id="REJECTED_" class="reject_chk"  name="chkBestSeller" value="REJECTED" data-id=""> </td>

Jquery

     $('.approve_chk').on('change', function (e) {
    var pswd = prompt("enter password to confirm");
    if (pswd == 'approve') {

        alert('APPROVED');

        var currentEle = $(this).attr('id');
        var chk = currentEle.split("_");
        console.log(chk[0]);
        var status=chk[0];
        var ID=chk[1];

        e.preventDefault();
        $.ajax({
            url:'EmployeeChkBoxStore',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type:'POST',
            dataType:'json',
            data:{status:status,ID:ID},
            success:function(data){
                console.log(data);
                alert('success');
            }
        });



    } else {
        alert('NOT APPROVED');
        $(this).prop('checked', false);
    }

});






     $('.reject_chk').on('change', function (e) {
    var pswd = prompt("enter password to confirm");
    if (pswd == 'reject') {
        alert('REJECTED');
        $(this).closest('tr').find('.approve_chk').prop('checked', false);

        var currentEle = $(this).attr('id');
        var chk = currentEle.split("_");
        console.log(chk[0]);
        var status=chk[0];
        var ID=chk[1];

        e.preventDefault();
        $.ajax({
            url:"EmployeeChkBoxStore",
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type:'POST',
            dataType:'json',
            data:{status:status,ID:ID},
            success:function(data){
                console.log(data);
                alert('success');
            }
        });

    } else {
        alert('NOT REJECTED');
        $(this).prop('checked', false);
    }
});

controller

    public function EmployeeChkBoxStore(Request $request){
    $data=new Leave();
    $data->status=$request->get('status');
    $data->id=$request->get('ID');
     DB::update("UPDATE `leaves` SET status = '$data->status' WHERE id = '$data->id'");
     }



How to set checkbox in a table checked?

I have a table I have the id of the checkbox that I want to set as checked, but I cannot do it and I don't know why.

I try with this, but nothing happens and I don't have any kind of error message:

$('#medicalListTable input.type_checkbox[id="sindicate-345"]').prop('checked', true);
$('input.type_checkbox[id="sindicate-345"]').prop('checked', true);
$('input.type_checkbox[id="sindicate-345"]').attr('checked', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="medicalListTable" class="display responsive nowrap dataTable no-footer" cellspacing="0" width="100%" role="grid" aria-describedby="medicalListTable_info" style="width: 100%;">
  <thead>
    <tr role="row">
      <th class="sorting ui-state-default sorting_asc" tabindex="0" aria-controls="medicalListTable" rowspan="1" colspan="1" aria-sort="ascending" aria-label="Id empleado: activate to sort column descending" style="width: 134px;">
        <div class="DataTables_sort_wrapper">Id empleado<span class="DataTables_sort_icon css_right ui-icon ui-icon-triangle-1-n"></span></div>
      </th>
      <th class="sorting ui-state-default" tabindex="0" aria-controls="medicalListTable" rowspan="1" colspan="1" aria-label="Nombre: activate to sort column ascending" style="width: 174px;">
        <div class="DataTables_sort_wrapper">Nombre<span class="DataTables_sort_icon css_right ui-icon ui-icon-caret-2-n-s"></span></div>
      </th>
      <th class="sorting ui-state-default" tabindex="0" aria-controls="medicalListTable" rowspan="1" colspan="1" aria-label="Apellidos: activate to sort column ascending" style="width: 329px;">
        <div class="DataTables_sort_wrapper">Apellidos<span class="DataTables_sort_icon css_right ui-icon ui-icon-caret-2-n-s"></span></div>
      </th>
      <th class="sorting ui-state-default" tabindex="0" aria-controls="medicalListTable" rowspan="1" colspan="1" aria-label="Seleccionar: activate to sort column ascending" style="width: 125px;">
        <div class="DataTables_sort_wrapper">Seleccionar<span class="DataTables_sort_icon css_right ui-icon ui-icon-caret-2-n-s"></span></div>
      </th>
    </tr>
  </thead>
  <tbody>
    <tr role="row" class="odd">
      <td class="vehicleId sorting_1">345</td>
      <td class="model">NAME</td>
      <td class="model">SURNAME</td>
      <td>
        <input type="checkbox" id="sindicate-345">
      </td>
    </tr>
  </tbody>
</table>



Create a dropdown and a checkbox along with it whenever a checkbutton is checked in tkinter

I am new to programming, help would be much appreciated. I have written a code in python 3. In my code I have a drop-down which contains a list of inputs and a checkbox. What I want is that every time I check the checkbox, a drop-down should be created along with a new checkbox. The new created checkbox serves the same purpose as the previous checkbox. Now, when I check the new checkbox, the previous process repeats giving me another checkbox and a drop-down. I'll be grateful for any kind of help. Thanks.




Display Checkbox values after submit button

I am trying to implement a filter. When a checkbox is checked, and after submitting, the checked values should display in the div with a Clear all button and an X button to remove separately, as shown in the image.

enter image description here Can anybody help me.

$(document).ready(function() {
  $('#showmenu').click(function() {
    $('.menu').show("slide");
  });
});

jQuery(document).ready(function(e) {
  function t(t) {
    e(t).bind("click", function(t) {
      t.preventDefault();
      e(this).parent().fadeOut()
    })
  }
  e(".dropdown-toggle").click(function() {
    var t = e(this).parents(".button-dropdown").children(".dropdown-menu").is(":hidden");
    e(".button-dropdown .dropdown-menu").hide();
    e(".button-dropdown .dropdown-toggle").removeClass("active");
    if (t) {
      e(this).parents(".button-dropdown").children(".dropdown-menu").toggle().parents(".button-dropdown").children(".dropdown-toggle").addClass("active")
    }
  });
  e(document).bind("click", function(t) {
    var n = e(t.target);
    if (!n.parents().hasClass("button-dropdown")) e(".button-dropdown .dropdown-menu").hide();
  });
  e(document).bind("click", function(t) {
    var n = e(t.target);
    if (!n.parents().hasClass("button-dropdown")) e(".button-dropdown .dropdown-toggle").removeClass("active");
  })
});

/******************************************/

$(function() {

  $('input[type="checkbox"]').click(
    function() {
      // if($(this).is(":checked")){
      //        $("#div ul").append("<li> value <a href='javascript:void(0);' class='remove'>&times;</a></li>"); 
      //    }

      value = $(this).val();
      if ($(this).is(':checked')) {
        $('<li></li>').appendTo('#div ol').text($(this).val());
      } else {
        value = $(this).val();
        if ($('#div ol').has('li:contains("' + value + '")')) {
          $('#div ol li:contains("' + value + '")').remove();
        }
      }
    });
});


/******************************************/
/******************************************/
.filter-section .container {
  margin-right: 100px;
  margin-left: 100px;
  padding: 0px;
  height: 24px;
}

.filter-section #showmenu {
  margin: 0px;
  margin-right: 34px;
}

.filter-section #showmenu p {
  color: #3f3f3f;
  font-size: 18px;
  font-weight: 600px;
  margin: 0px;
  padding: 0px;
}

.filter-section .menu .nav {
  border-left: 1px solid #3f3f3f;
}

.filter-section .nav {
  display: block;
  margin: 0;
  padding: 0;
  height: 24px;
}

.filter-section .nav li {
  display: inline-block;
  list-style: none;
}

.filter-section .menu .nav .button-dropdown {
  position: relative;
  margin-left: 24px;
  height: 24px;
}

.filter-section .menu .nav li a {
  color: #000;
  background-color: #fff;
  font-size: 18px;
  font-weight: 600;
  text-decoration: none;
}

.filter-section .menu .nav li a span {
  font-size: 26px;
  line-height: 0;
  height: 24px;
  margin-right: 10px;
}

.filter-section .menu .nav li .dropdown-toggle::after {
  display: inline-block;
  margin-left: 12px;
  vertical-align: 2px;
  content: "";
  border-top: 6px solid;
  border-right: 3px solid transparent;
  border-bottom: 0;
  border-left: 3px solid transparent;
}

.filter-section .menu .nav li .dropdown-menu {
  display: none;
  position: absolute;
  left: 0;
  padding: 0;
  margin: 0;
  margin-top: 0px;
  margin-left: 22px;
  text-align: left;
  width: 224px;
  padding: 10px 24px;
}

.filter-section .menu .nav li .dropdown-menu div {
  border-bottom: 1px solid #000;
}

.filter-section .menu .nav li .dropdown-menu div:last-child {
  border-bottom: none;
  padding-bottom: 10px;
  padding-top: 20px;
}

.filter-section .menu .nav li .dropdown-menu.active {
  display: block;
}


/*.nav li .dropdown-menu a {
            width: 150px;
        }*/


/****************************************/

.listofslect {
  padding: 0px;
}

.listofslect li {
  padding: 10px;
  font-size: 14px;
  display: inline-block;
  -webkit-transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
  transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.name {
  display: inline-block;
  font-size: 14px;
  font-weight: 600;
  padding: 0;
  margin: 0;
  padding-bottom: 14px;
  padding-top: 10px;
}

.name input {
  margin-right: 12px;
}

.button {
  border: none;
  color: white;
  padding: 14px 0px;
  text-align: center;
  font-size: 16px;
  width: 100%;
  cursor: pointer;
  border-radius: 4px;
  background-color: #000000;
}

button:focus {
  outline: 0px dotted;
  outline: 0px auto -webkit-focus-ring-color;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<section>
  <div class="filter-section">
    <div class="container d-flex">
      <div id="showmenu">
        <p> <img src="images/hamburger-icon-open.png"> Filter</p>
      </div>
      <div class="menu" style="display: none;">
        <ul class="nav">
          <li class="button-dropdown">
            <a href="javascript:void(0)" class="dropdown-toggle"><span>&#8226;</span>Learning Modes</a>
            <div class="dropdown-menu">
              <div class="">
                <label class="name"><input type="checkbox" class="" id="checkbox4" value="Self paced"/>Self paced</label>
              </div>
              <div class="">
                <label class="name"><input type="checkbox" class="" id="checkbox4" value="Classroom"/>Classroom</label>
              </div>
              <div class="">
                <label class="name"><input type="checkbox" class="" id="checkbox4" value="Live Virtual-Classroom"/>Live Virtual Classroom</label>
              </div>
              <div class="">
                <button class="button">Apply</button>
              </div>
            </div>
          </li>
          <li class="button-dropdown">
            <a href="javascript:void(0)" class="dropdown-toggle"><span>&#8226;</span>Level</a>
            <div class="dropdown-menu">
              <div class="">
                <label class="name"><input type="checkbox" class="" id="checkbox4" value="ABC"/>ABC</label>
              </div>
              <div class="">
                <label class="name"><input type="checkbox" class="" id="checkbox4" value="DEF"/>DEF</label>
              </div>
              <div class="">
                <label class="name"><input type="checkbox" class="" id="checkbox4" value="GHI"/>GHI</label>
              </div>
              <div class="">
                <button class="button">Apply</button>
              </div>
            </div>
          </li>
          <li class="button-dropdown">
            <a href="javascript:void(0)" class="dropdown-toggle"><span>&#8226;</span>Role</a>
            <div class="dropdown-menu">
              <div class="">
                <label class="name"><input type="checkbox" class="" id="checkbox4" value="JKL"/>JKL</label>
              </div>
              <div class="">
                <label class="name"><input type="checkbox" class="" id="checkbox4" value="MNO"/>MNO</label>
              </div>
              <div class="">
                <label class="name"><input type="checkbox" class="" id="checkbox4" value="PQR"/>PQR</label>
              </div>
              <div class="">
                <button class="button">Apply</button>
              </div>
            </div>
          </li>
          <li class="button-dropdown">
            <a href="javascript:void(0)" class="dropdown-toggle"><span>&#8226;</span>Skills</a>
            <div class="dropdown-menu">
              <div class="">
                <label class="name"><input type="checkbox" class="" id="checkbox4" value="STU"/>STU</label>
              </div>
              <div class="">
                <label class="name"><input type="checkbox" class="" id="checkbox4" value="VWX"/>VWX</label>
              </div>
              <div class="">
                <label class="name"><input type="checkbox" class="" id="checkbox4" value="YZ"/>YZ</label>
              </div>
              <div class="">
                <button class="button">Apply</button>
              </div>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <div class="container" id="div">
      <ol class="listofslect"></ol>
    </div>
  </div>
</section>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

The jsFiddle and Codepen code is attached.




Javascript for toggle checkbox - Laravel

Hello guys I'm new to Laravel and programming, I'm trying to let the checkbox checked if the value of $status is 1, in my scenario below the value of should be 1 so the checkbox should be checked but its not working.

Javascript

<script>
function sta() {
  var st = document.getElementById("status").value;
  var checkbox = document.getElementById("status");

  if (st == 1) {
        checkbox.checked == true;
  } else {
        checkbox.checked == false;
  }
}
</script>

HTML

<body onload= "sta()">

<form id="ed" name="ed" method="post" action="">
    
    <input type="hidden" name="_method" value="PATCH" />
        <div class="form-group">Name:
     <input type="text" name="name" class="form-control" value="" placeholder="Enter Name" />
        </div>
        <div class="form-group">Description:
                    <input type="textarea" name="description" class="form-control" value="" 
                    placeholder="Enter Description" />
        </div>

//from here is the checkbox code

            <div class="form-group">Status Type:
                <label class="radio-inline">
                   <input type="checkbox" id="status" name="status" value="">
               </label>
             </div>



dimanche 23 février 2020

Checkbox triggered clearcontent Script then automatically unchecking it immediately

I'm looking for clearing a range with checking a checkbox, then having the script to uncheck it.

This is what I tried so far, but besides the fact it's looping, I don't know how to force the TRUE to FALSE automatically whenever a FALSE becomes a TRUE.

function onEdit(e) {
  var aCell = e.source.getActiveCell(), col = aCell.getColumn(); 
  if(col == 2) { 
    var app = SpreadsheetApp;
    var activeSheet = app.getActiveSpreadsheet().getActiveSheet();
activeSheet.getRange("D4:D6").clearContent()
  }}



Custom styled checkbox (contact form 7) not working on iPhone

I've been working on a website that was built in WordPress using bootstrap templates. This website was not originally built by me, so I have troubles with it from time to time when implementing changes. The website uses yarn to build a 'dist' folder from node.js modules and elements contained within the theme folder. The stylesheets are scss files. After the build process finishes, it has created a 'dist' folder that is to be uploaded to the theme folder, which contains all the combined stylesheets, images, etc.

I'm having issues with a form that is created via contact form 7 and I'm not sure if this is an issue relating to the build process using yarn or something else. The issue is with a checkbox that I've added to the form. It works as expected on desktop displays, but when the site is viewed on an iPhone (via Chrome, Safari and Google browser apps) the checkbox tick doesn't appear on click.

Just for clarification, the last few websites I have built myself, that have included a form with a checkbox or checkboxes, are working perfectly across desktop and IOS devices. I use css stylesheets rather than scss, but I have used all the same styles on both the websites that are working fine and the one that is not working on IOS, so I really can't see why the checkbox is not working on mobile. I have also tried applying a couple of other fixes that have also not helped resolve the issue.

Please see below for the html code and scss code for the checkbox section of the website:

<div class="af-field af-field-type-checkbox af-field-checkbox acf-field acf-field-checkbox">
<div class="af-label acf-label">
            <label for="brochure-pack-checkbox">Please send me a Giraffe Equity Release brochure pack</label>
        </div>
<div class="af-input acf-input">
<div class="acf-input-wrap">
                <span class="wpcf7-form-control-wrap brochure-pack"><span class="wpcf7-form-control wpcf7-checkbox" id="brochure-pack-checkbox"><span class="wpcf7-list-item first last"><label><input type="checkbox" name="brochure-pack[]" value="Please send me a Giraffe Equity Release brochure pack"><span class="wpcf7-list-item-label">Please send me a Giraffe Equity Release brochure pack</span></label></span></span></span>
            </div>
<p></p></div>
<p></p></div>
    .acf-field-checkbox {

      .wpcf7-list-item {
        position: relative;
        margin-left: 0;
        width: 100%;
        display: block;
      }

      .wpcf7-list-item-label {
        font-size: 2rem;
        font-weight: 600;
        line-height: 1.5em;
        margin-left: 35px;
        display: block;
        cursor: pointer;
      }

      .wpcf7-list-item-label:before {
        position: absolute;
        left: 0;
        width: 28px;
        height: 28px;
        border: 1px solid #b79c68;
        border-radius: .25rem;
        display: block;
      }

      .wpcf7-list-item-label:after {
        position: absolute;
        content: '\1F5F8';
        font-size: 30px;
        color: #b79c68;
        width: 0px;
        height: 0px;
        top: 2px;
        left: 2px;
        opacity: 0;
      }

      input[type=checkbox] {
        display: none;
        -webkit-appearance: checkbox;
      }

      input[type=checkbox]:checked {

        + span.wpcf7-list-item-label:after {
          opacity: 1;
        }

      }

      label {
        margin-bottom: 0;
        cursor: pointer;
        display: block;
      }

    }

I appreciate there may be some styles applied that are not needed, but they are not affecting the checkbox functionality. Once I have found the right solution to get this working for this specific website, I will clean up the styles applied and remove any that aren't necessary.

If anyone has any idea why the checkbox could be not working on this website, when they work fine on the others I have built, I would really be grateful for any hints or advice you could give.

Thanks in advance, if you need anymore information about the issue, then please ask and I'm sure I can clear up anything needed.




samedi 22 février 2020

customized checkboxes is not clickable in kendo grid

I have kendo grid with checkbox selection column and i customized this checkboxes but now checkboxes are not clickable cannot unchecked or checked

How can i solve this?

Here my code

@( Html.Kendo().Grid<MockUpForeNet.Controllers.CardDetailController.Days>()
     .Name("timegrid")
     .DataSource(d => d.Ajax().Read("TimeGridBinding", "CardDetail").Model(keys =>
     {
         keys.Id(k => k.DayId);
         keys.Field(c => c.DayName).Editable(false);
         keys.Field(c => c.DayId).Editable(false);
     }).PageSize(7))
               .Columns(c =>
               {
                   c.Bound(p => p.DayId).Width(100).Title(" ").ClientTemplate("#= chk2(data) #").Sortable(false);
                   c.Bound(e => e.DayName).Width("auto").Title("Day");
               })
       .Editable(editing => editing.Mode(Kendo.Mvc.UI.GridEditMode.InCell))
       .Sortable()
       .ColumnMenu()
)

here my checkbox template

   function chk2(data) {
    return '<input id="masterCheck' + data.DayId + '" class="k-checkbox" type="checkbox" checked="checked" /><label for="masterCheck" class="k-checkbox-label"></label>';

}



Vue JS CheckBoxGroup with a prop array as v-model

I am stuck at making a CheckBoxGroup with a prop array as v-model. I have read the vuejs guide: https://vuejs.org/v2/guide/forms.html#Checkbox which has the v-model array in the data of the same component, but it is obviously pretty useless if I want to make this component reusable and insert the v-model via props and for example check some of the boxes from "outside". So I tried following:

CheckBoxgroup.vue

<template>
  <div>
    <label v-for="day in allDays" :key="day">
      <input v-model="checkedDays" type="checkbox" :value="day" />
      <span></span>
    </label>
    <div>Checked days: </div>
 </div>
</template>
<script lang="ts">
import Vue from 'vue'
import { Component, Prop } from 'vue-property-decorator'

@Component
export default class CheckBoxGroup extends Vue {
  @Prop() checkedDays!: string[]

  @Prop() allDays!: string[]
}
</script>

Index.vue

<template>
  <div>
    <checkbox-group :checked-days="checkedDays" :all-days="allDays" />
  </div>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
import CheckboxGroup from './checkBoxGroup.vue'

@Component({
  components: { CheckboxGroup },
})
export default class Index extends Vue {

  // This list would usually come from an API
  allDays = ['Monday', 'Tuesday', 'Wednesday']

  checkedDays = ['Monday']
}
</script>

So the code is working almost fine, but I am getting

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders...

Is there any way around it? Any help would be appriciated.