lundi 30 septembre 2019

How to make enabling a button work when any of checkboxes is selected with react hooks?

I have a bug in enabling a button, when any of the checkboxes is selected. Currently it doesnt work on the first click, but only on the second one. Unselecting a checkbox works on the first click also. I think it has something to do with states, but I don't really understand what is causing the problem.

I tried commenting out this line: checked.length > 0 ? setTaskBtnsEnabled(true) : setTaskBtnsEnabled(false); and it removes the issue so I'm sure it has something to do with the useState. However that line is vital for me so I should come up with a fix for this. I also tried to start with opposite boolean values and the issue remains.

Upper component:

const checkedBoxes = () => {
    var checkedOnes = [];
    for (
      var i = 0;
      i < document.getElementsByClassName('count-checkboxes').length;
      i++
    ) {
      if (document.getElementsByClassName('count-checkboxes')[i].checked) {
        checkedOnes.push(
          document.getElementsByClassName('count-checkboxes')[i].parentNode
            .id
        );
      }
    }
    return checkedOnes;
  };

  const [taskBtnsEnabled, setTaskBtnsEnabled] = useState(false);
  const handleBtnsEnabling = event => {
    var checked = checkedBoxes();
    checked.length > 0 ? setTaskBtnsEnabled(true) : setTaskBtnsEnabled(false);
  };

Component inside the previous one:

<Button
   disabled={!taskBtnsEnabled}
   id="nappi"
>
   OK
</Button>

The issue is that first click doesn't work and it doesn't check the checkbox. No error messages coming to console.




Pass a prop to a form in Nuxt

The user clicks on a link that refers to a package that i offer to make a homepage. It's like three packages, Small, Medium and Big. All that has different prices.

If the user clicks on Small. That takes him to another page with a form that he can type his name and message. In the URL-bar it say, www.example.com/small. Now i've got a hidden checkbox that checks the small checkbox based on the prop that i pass it to. All fine and dandy there. But when i send the mail and i read it in gmail. I can't see what package selected. All a see is, Small: True, and the name and message...

Don't know if you guys understand me but i will clarify if you want.

This is the Contact component

<template>
  <div class="container">
    <h1></h1>
    <h3></h3>

    <div class="content wrapper">
      <form
        name="contact-form"
        action="/tack"
        autocomplete="off"
        netlify-honeypot="bot-field"
        method="POST"
        netlify
        @submit="validateBeforeSubmit"
      >
        <div class="input-field">
          <label class="form-label" for="name">Ditt namn:</label>
          <input
            v-validate="'required|alpha_spaces'"
            class="form-field inputs"
            name="namn"
            placeholder="För- &amp; efternamn"
            onfocus="this.placeholder = ''"
            onblur="this.placeholder = 'För- &amp; efternamn'"
            required
            v-model="namn"
            :class="{'input': true, 'is-danger': errors.has('namn') }"
          >
          <span v-show="errors.has('namn')" class="error"></span>
          <input type="hidden" name="form-name" value="contact-form">
        </div>

        <div class="input-field">
          <label class="form-label" for="email">Din email:</label>
          <input
            type="email"
            required
            v-validate="'required|email'"
            class="form-field inputs"
            name="email"
            placeholder="namn@foretag.se"
            onfocus="this.placeholder = ''"
            onblur="this.placeholder = 'namn@foretag.se'"
            v-model="email"
            :class="{'input': true, 'is-danger': errors.has('email') }"
          >
          <span v-show="errors.has('email')" class="error"></span>
        </div>

        <div class="select-package hidden">
          <p>Välj vilket paket du önskar - <em>Valfritt</em></p>
          <div class="package-field">
            <input type="checkbox" id="checkbox1" name="checkboxes" :value="liten" :checked="value" v-on:input="liten = $event.target.value" v-model="liten">
            <label for="checkbox1">Liten</label>
          </div>

          <div class="package-field">
            <input type="checkbox" id="checkbox2" name="checkboxes" :checked="value">
            <label for="checkbox2">Mellan</label>
          </div>

          <div class="package-field">
            <input type="checkbox" id="checkbox3" name="checkboxes"    :value="stor" :checked="value" v-on:input="stor = $event.target.value" v-model="stor">
            <label for="checkbox3">Stor</label>
          </div>
        </div>
        <div class="input-textarea">
          <label class="form-label" for="message">Meddelande:</label>
          <textarea
            required
            class="form-field inputs"
            name="meddelande"
            placeholder="Ditt meddelande..."
            onfocus="this.placeholder = ''"
            onblur="this.placeholder = 'Ditt meddelande...'"
            v-model="meddelande"
            v-validate="'required|min:5'"
            :class="{'input': true, 'is-danger': errors.has('meddelande') }"
          ></textarea>
          <span v-show="errors.has('meddelande')" class="error"></span>
        </div>

        <div class="gdpr">
          <div class="gdpr-checkbox">
            <input type="checkbox" id="GDPR" v-validate="'required'" value="checked" name="GDPR">
            <label v-show="errors.has('GDPR')" class="error" for="GDPR"> Godkänn hanteringen av din personliga data.</label>
            <label v-if="!errors.has('GDPR')" for="GDPR">Godkänn hanteringen av din personliga data.</label>
          </div>
          <p>Ni kan läsa mer om vår policy och vår hantering av persondata <nuxt-link to="/policy" class="gdpr-link eyebrow">här</nuxt-link></p>
          <p>Du måste godkänna <nuxt-link class="gdpr-link eyebrow" to="/policy">hantering av persondata</nuxt-link> för att kunna skicka ditt meddelande.</p>

        </div>

        <div class="form-button">
          <input class="button" type="submit" value="Skicka meddelande">
        </div>

      </form>
    </div>
  </div>
</template>

<script>
import vuex from "vuex"
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";



export default {
  props: ['paketText', 'underText', 'stor', 'mellan', 'liten', 'value'],
  data: () => {
    return {

    }
  },
  methods: {
    validateBeforeSubmit(e) {

      this.$validator.validate().then(result => {
        console.log(result);
        if (!result) {
          alert("Ange rätt uppgifter i formuläret");
          e.preventDefault();
        } else {
          console.log("Skickat");
          this.$router.push({
            name: "tack",
            path: "/tack"
          });
          return true;
        }
      });
    }
  },
  computed: {
    meddelande: {
      get() {
        return this.$store.state.meddelande;
      },
      set(val) {
        this.$store.commit("update_meddelande", val);
      }
    },
    email: {
      get() {
        return this.$store.state.email;
      },
      set(val) {
        this.$store.commit("update_email", val);
      }
    },
    namn: {
      get() {
        return this.$store.state.namn;
      },
      set(val) {
        this.$store.commit("update_namn", val);
      }
    }
  }
};
</script>

liten = small

This is the smallpackage component

<template>
  <div class="container">
    <Contact paketText="Lilla paketet" underText="Det här paketet är perfekt för dig som vill ha en hemsida som är enkel men som ändå förmedlar ditt budskap på ett bra sätt." liten="true" value="checked" />
  </div>
</template>

<script>
 import Contact from '@/components/Contact'
export default {
  components: {
    Contact
  }
}
</script>

<style lang="sass" scoped>

</style>

I'm hoping to see what package the user selected in my mail when he sends the form.




Checkboxes inside a dynamic table in PHP

I am trying to implement CheckBoxes to each row of a dynamic table. The checkboxes are being displayed correctly but I cannot get it values when I submit.

Here is my code:

 <?php foreach ($arr_devices as $devices) {
                            ?>

                        <tr>

                            <td>

                                <input name="checkbox[]" type="checkbox" id="checkbox[]" value='<? echo $devices["id"]; ?>'>

                            </td>

                            <td>
                                <?php echo '<a href=selectedCustomer.php?device_id=' . urlencode($devices["id"]) . '>' . $devices["id"] . '</a>'; ?>
                            </td>

                            <td>
                                <?php echo '<a href=selectedCustomer.php?device_id=' . urlencode($devices["id"]) . '>' . $devices["serial_imei"] . '</a>'; ?>
                            </td>

                            <td>
                                <?php echo '<a href=selectedCustomer.php?device_id=' . urlencode($devices["id"]) . '>' . $devices["serial_no"] . '</a>'; ?>
                            </td>


                        </tr>
                    <?php } ?>



Add elements in a list when clicking in a checkbox without code-behind

I have a list of checkbox :

<ListBox Name="listBoxZone" ItemsSource="{Binding FilesInDirectories}"  Height="115" Background="Azure" SelectionMode="Multiple">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <CheckBox Name="CheckBoxZone" Margin="0,5,0,0" Content="{Binding}" Checked="{}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

I want to add the checked elements in a list in my ViewModel.

I don't want to use the code behind and the event : clicked.

Is it possible ?

How can I do this ?




dimanche 29 septembre 2019

Implementing Checkbox inside Picker in React-Native

Is there a possibility to attach multiple CheckBoxes inside Picker component in React-Native? I want to know if this is possible, I am already aware that there other components that I can download with npm.




visual studio C# listview save and load problem

i have a problem with visual studio c# listview items that i cant found a solution over googling.

I've made from application with a listview, i can add, remove, update listview items. I'm saving and loading the listview to/from file correctly with this code:

 private void saveListViewItems(string path, ListView lv)
    {
        var delimeteredListviewData = new List<string>();
        string delimeteredItems = string.Empty;

        foreach (ListViewItem lvi in lv.Items)
        {

            foreach (ListViewItem.ListViewSubItem lvsi in lvi.SubItems)
            {

                    delimeteredItems += lvsi.Text + "#";

            }
            delimeteredListviewData.Add(delimeteredItems);
        }


        System.IO.File.WriteAllLines(path, delimeteredListviewData.ToArray());
    }

    private void loadListViewItems(string path, ListView lv)
    {

        foreach (string line in System.IO.File.ReadAllLines(path))
        {
            lv.Items.Add(new ListViewItem(line.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries)));

        }
    }

the problems is i have activated checkbox next to each item. i cant save listview items with checkbox checked. i want to save listview and load with selected items. thanks

enter image description here




If checkbox from parent component is checked, do something in child component

I'm trying to accomplish the following: I have a checkbox in my parent component (Players.vue). If the checkbox is checked, then something should be done in the child component (PlayerTabs.vue)

Here's the relevant part of Players.vue:

<template>
  <div class="row">
      <div class="d-inline col-lg-6 col-md-6 col-sm-6">
        <div class="row">
          <div class="d-inline col-lg-6 col-md-6 col-sm-6">
            <b>Scholarship Player</b>
          </div>
          <div class="d-inline col-lg-6 col-md-6 col-sm-6">  
            <input type="checkbox" id="checkbox" v-model="players.Scholarship"> </div>
        </div>
</template> 


<script>
import * as $ from "jquery";
import Parents from "./Details/Parents.vue";
export default {
  components: {
    appParents: Parents
  },
  data: function() {
    return {
      players: [],
      parents: [],
      characters: [],
      selectedArrayIndex: "",
      team: [],
      showInfo: false,
    };
  },
};
</script>

Here's PlayerTabs.vue:

<template>
  <div>
    <div class="row" style="margin-bottom:20px">
      <button class="btn btn-primary" @click="changeSelectedComp">Back</button>
    </div>
    <vue-tabs>
      <v-tab title="Basic">
        <app-players></app-players>
      </v-tab>
      <v-tab title="History">
        <app-histories></app-histories>
      </v-tab>
      <v-tab title="Timetable">
        <app-timetables></app-timetables>
      </v-tab>
      <div v-if="players.Scholarship">
        <v-tab title="Scholarship">
          <app-timetables></app-timetables>
        </v-tab>
      </div>
      <div v-else>
        <v-tab title="Scholarship">
          <app-timetables></app-timetables>
        </v-tab>
      </div>

    </vue-tabs>
  </div>
</template>

<script>
import * as $ from "jquery";
import Players from "./PlayerBasicInfo/Players.vue";
import Histories from "./History/Histories.vue";
//import Characters from "./History/Character/Characters.vue";
import Timetables from "./Timetable/Timetables.vue";

//import Test from "./History/Test.vue";


export default {
  components: {
    appPlayers: Players,
    // appCharacters: Characters,
    //appStatistcs: Statistics,
    appTimetables: Timetables,
    appHistories: Histories,
  },
  methods: {
    changeSelectedComp: function() {
      this.$store.state.selectedComp = "appTeamInfo";
    }
  }
};
</script>

The problem is that the checkbox value players.Scholarship is not passed properly in PlayerTabs.vue. What did I do wrong here?




Python athplotlib.pyplot: Save the marked Check Buttons in text file

I'm doing a study about the shape of lightcurves. Therefore I plot my tables with the data points. Now I want different Check Buttons for the different shapes, i.e. non-periodic variability or periodic variability. After I checked all properties and go on to the next lightcurve, I want to save those properties in a new text file in the form of 'name' and 'chosen Check Buttons'.

I do not have any idea, how to work this out. Thank you for your help.

Cheers Benedetto




samedi 28 septembre 2019

Variable not reassigning on checked value

Value of variable garageVal is not being updated on checkbox selection.

Since the default position of the checkbox is checked on the first selection, garageVal is 15000, but it does not change when a different value is selected.

The purpose of this section is to calculate an estimate on a house. garageVal is plugged into a calculator along with other variables to generate a final value.

HTML:

  <div class="garage-block">
      <input type="checkbox" class='g1' name='garage'/>1</label>
      <input type="checkbox" class='g2' name='garage'/>2</label>
      <input type="checkbox" class='g3' name='garage'/>3</label>
  </div>

JS:

    let g1 = document.querySelector('.g1');
    let g2 = document.querySelector('.g2');
    let g3 = document.querySelector('.g3');
    let garageVal;
    if(g1.checked = true){
       garageVal = 15000;
    }else if(g2.checked = true){
       garageVal = 30000;
    } else if(g3.checked = true){
       garageVal = 45000;
    }
    console.log(garageVal);

console will show 15000 by default, despite my efforts, I have not been able to update garageVal.




Referencing element from other class in Vue.js

I've got a checkbox in my Players.vue:

<div class="row">
   <div class="d-inline col-lg-6 col-md-6 col-sm-6">
      <b>Scholarship Player</b>
   </div>
   <div class="d-inline col-lg-6 col-md-6 col-sm-6">  
      <input type="checkbox" id="checkbox" v-model="players.Scholarship"> </div>
</div>

Checkbox

When the checkbox is checked (true), then another tab should open.

The problem is that the way I reference players.Scholarship in my other class PlayerTabs, it doesn't seem to work. I get a TypeError:

Cannot read property 'Scholarship' of undefined

Can someone tell me how I have to reference the players.Scholarship (or whether my if itself is false)? (I'm new to Vue.js)

<div v-if="Scholarship">
    <v-tab title="Scholarship">
      <app-timetables></app-timetables>
    </v-tab>
</div>
<div v-else>
</div>

Scholarship itself is in an array of players in my TeamInfos.vue class:

playersData: function(data) {
  this.players = [];
  var $this = this;
  for (var i = 0; i < data.length; i++) {
    $this.players.push({
      ID: data[i].ID,
      PlayerID: data[i].NameId,
      Scholarship: data[i].Scholarship
      // others
    });
  } 
},



truth tables in php with more then 3 variable

Hi StackOverflow people.

if i have 3 variable out side of the loop called :

 $atr
 $ber
 $cdr

Another system will provide 2 option value for this 3 variable: Empty or not empty.

and other 3 variables inside the loop: the value for each variable come from Another system and depend on $i every loop will get different value

$aa 
$bb 
$cc

now my code:

function SelectAll2()
{

$arrArraySize = 283;

$atr =  Empty or not empty.;
$ber =  Empty or not empty.; 
$cdr =  Empty or not empty.; 


if($atr=="" && $ber=="" && $cdr==""){
  return 1;
}
elseif($atr=="" && $ber=="" && $cdr!=""){
  for ($i=1; $i<$arrArraySize; $i++)
  {
  $cc = value come from Another system and depend on $i every loop will get diffrent value
    if( $cdr==$cc){ 
    return 1;
    }
  }
}elseif($atr=="" && $ber!="" && $cdr==""){
  for ($i=1; $i<$arrArraySize; $i++)
  {
  $bb = value come from Another system and depend on $i every loop will get diffrent value
    if($ber==$bb){ 
    return 1;
    }
  }  
}elseif($atr!="" && $ber=="" && $cdr==""){
  for ($i=1; $i<$arrArraySize; $i++)
  {
  $aa = value come from Another system and depend on $i every loop will get diffrent value
    if($atr==$aa){ 
    return 1;
    }
  } 
}elseif($atr=="" && $ber!="" && $cdr!=""){
  for ($i=1; $i<$arrArraySize; $i++)
  {
  $bb = value come from Another system and depend on $i every loop will get diffrent value
  $cc = value come from Another system and depend on $i every loop will get diffrent value
    if($ber==$bb && $cdr==$cc){ 
    return 1;
    }
  } 
}elseif($atr!="" && $ber=="" && $cdr!=""){
  for ($i=1; $i<$arrArraySize; $i++)
  {
  $aa = value come from Another system and depend on $i every loop will get diffrent value
  $cc = value come from Another system and depend on $i every loop will get diffrent value
    if($atr==$aa && $cdr==$cc){ 
    return 1;
    }
  } 
}elseif($atr!="" && $ber!="" && $cdr==""){
  for ($i=1; $i<$arrArraySize; $i++)
  {
  $aa = value come from Another system and depend on $i every loop will get diffrent value
  $bb = value come from Another system and depend on $i every loop will get diffrent value
    if($atr==$aa && $ber==$bb){ 
    return 1;
    }
  } 
}else{
  for ($i=1; $i<$arrArraySize; $i++)
  { 
  $aa = value come from Another system and depend on $i every loop will get diffrent value
  $bb = value come from Another system and depend on $i every loop will get diffrent value
  $cc = value come from Another system and depend on $i every loop will get diffrent value
    if($cdr==$cc && $atr==$aa && $ber==$bb){
      return 1;
    } 
  }
}
}

there is a way to write this code more effectively?

because it's messy and it's for only 3 outside loop variable ($atr,$ber,$cdr) and 3 inside loop variable ($aa,$bb,$cc)

and i need this for 4 variable and even 6. if its 6, for example, I can add other 3 outside variable ($atr,$ber,$cdr,$fdsf,$tre,$dsds) and other 3 inside variable ($aa,$bb,$cc,$dd,&ee,$ff)

thanks!




Linking checkbox to list item in Vue.js

I have a list element Scholarship in Sharepoint of type "Yes/No (Checkbox)".

Scholarship element

So, I created a checkbox via Vue.js:

<div class="row">
       <div class="d-inline col-lg-6 col-md-6 col-sm-6">
          <b>Scholarship Player</b>
       </div>
       <div class="d-inline col-lg-6 col-md-6 col-sm-6">  
          <input type="checkbox" id="checkbox" v-model="Scholarship"> </div>
       </div>

Checkbox

The problem I'm having is that it shows me the checkbox and next to it "true". When I change the list element to false, it will show me "false" and the checkbox will remain the same. This means that it didn't link the list element "Scholarship" to the checkbox.

How can I link/connect my list element with the checkbox? (Meaning that when the checkbox is checked, the list element will be true and whenever the checkbox is not checked it will be false)




How could I store row checked value in textarea with datatabel pagination

I'm using icheck along with datatable. There are four different checkbox options per line. Users can choose between the four checkboxes. They can select one or more checkboxes on each line. The selected checkbox values are collected in four different textarea fields. If there is only one page, there is no problem. When multiple pages are passed to the second or third page and a new checkbox is checked, the textarea field is updated with these page values only. Previous values disappear. checkboxes are still selected when I return to the first page. The textarea field is updated with the first page values only when a new line is selected on the first page or when the current checkbox is unchecked.

How can I maintain and update the values in the textarea values with page changes in datatable?

<table class="table dataTables-example">
    <thead>
        <tr>
            <th>ID</th>
            <th>Function</th>
            <th>Price</th>
            <th>IY</th>
            <th>PT</th>
            <th>ET</th>
            <th>KO</th>
        </tr>
    </thead>
    <tbody>
    <tr>
        <td><input name="CB1" id="IY1" type="checkbox" value="IY=1"></td>
        <td><input name="CB2" id="PT1" type="checkbox" value="PT=1"></td>
        <td><input name="CB3" id="ET1" type="checkbox" value="ET=1"></td>
        <td><input name="CB4" id="KO1" type="checkbox" value="KO=1"></td>
    </tr>
    <tr>
        <td><input name="CB1" id="IY2" type="checkbox" value="IY=2"></td>
        <td><input name="CB2" id="PT2" type="checkbox" value="PT=2"></td>
        <td><input name="CB3" id="ET2" type="checkbox" value="ET=2"></td>
        <td><input name="CB4" id="KO2" type="checkbox" value="KO=2"></td>
    </tr>
    <tr>
        <td><input name="CB1" id="IY3" type="checkbox" value="IY=3"></td>
        <td><input name="CB2" id="PT3" type="checkbox" value="PT=3"></td>
        <td><input name="CB3" id="ET3" type="checkbox" value="ET=3"></td>
        <td><input name="CB4" id="KO3" type="checkbox" value="KO=3"></td>
    </tr>
    <tr>
        <td><input name="CB1" id="IY4" type="checkbox" value="IY=3"></td>
        <td><input name="CB2" id="PT4" type="checkbox" value="PT=3"></td>
        <td><input name="CB3" id="ET4" type="checkbox" value="ET=3"></td>
        <td><input name="CB4" id="KO4" type="checkbox" value="KO=3"></td>
    </tr>   
    </tbody>
</table>

<textarea id="ResultBox1"></textarea><strong> ResultBox1 - IY / Total: <span class="RS1"></span> Checkbox selected.</strong><br>
<textarea id="ResultBox2"></textarea><strong> ResultBox2 - PT / Total: <span class="RS2"></span> Checkbox selected .</strong><br>
<textarea id="ResultBox3"></textarea><strong> ResultBox3 - ET / Total: <span class="RS3"></span> Checkbox selected .</strong><br>
<textarea id="ResultBox4"></textarea><strong> ResultBox4 - KO / Total: <span class="RS4"></span> Checkbox selected .</strong><br>

<script type="text/javascript" src="css/DataTables/datatables.min.js"></script>
<script>
$(document).ready(function(){
    $('.dataTables-example').DataTable({
        pageLength: 10,
        responsive: true,
        dom: '<"html5buttons"B>lTfgitp',
        buttons: [
            { extend: 'copy'},
            {extend: 'csv'},
            {extend: 'excel', title: 'ExampleFile'},
            {extend: 'pdf', title: 'ExampleFile'},

            {extend: 'print',
             customize: function (win){
                    $(win.document.body).addClass('white-bg');
                    $(win.document.body).css('font-size', '10px');

                    $(win.document.body).find('table')
                            .addClass('compact')
                            .css('font-size', 'inherit');
            }
            }
        ],
       'drawCallback': function(settings){
          //iCheck for checkbox and radio inputs
          $('input[type="checkbox"]').iCheck({
            checkboxClass: 'icheckbox_square-green',
            radioClass: 'iradio_square-green'
          });
       }        

    });

});


</script>
<!-- iCheck -->
<script src="js/plugins/iCheck/icheck.min.js"></script>
<script>
$('.i-checks').on('ifChanged', function(event) {
  updateAllChecked1();
  updateAllChecked2();
  updateAllChecked3();
  updateAllChecked4();
});
function updateAllChecked1() {
  $('#ResultBox1').text('');
  $("input[name=CB1]").each(function() {
    if (this.checked) {
      let old_text = $('#ResultBox1').text() ? $('#ResultBox1').text() + ',' : '';
      $('#ResultBox1').text(old_text + $(this).val());
    }
  })
}
function updateAllChecked2() {
  $('#ResultBox2').text('');
  $("input[name=CB2]").each(function() {
    if (this.checked) {
      let old_text = $('#ResultBox2').text() ? $('#ResultBox2').text() + ',' : '';
      $('#ResultBox2').text(old_text + $(this).val());
    }
  })
}
function updateAllChecked3() {
  $('#ResultBox3').text('');
  $("input[name=CB3]").each(function() {
    if (this.checked) {
      let old_text = $('#ResultBox3').text() ? $('#ResultBox3').text() + ',' : '';
      $('#ResultBox3').text(old_text + $(this).val());
    }
  })
}
function updateAllChecked4() {
  $('#ResultBox4').text('');
  $("input[name=CB4]").each(function() {
    if (this.checked) {
      let old_text = $('#ResultBox4').text() ? $('#ResultBox4').text() + ',' : '';
      $('#ResultBox4').text(old_text + $(this).val());
    }
  })
}   
</script>
<script>
    $('input[name=CB1]').on('ifChanged', function(event){
      var countChecked = function() {
      var n = $( "input[name=CB1]:checked" ).length;
      $( ".RS1" ).text( n + ( " Item" ));
    };
    countChecked();
        $( "input[name=CB1]" ).on( "click", countChecked );
    });
    $('input[name=CB2]').on('ifChanged', function(event){
      var countChecked = function() {
      var n = $( "input[name=CB2]:checked" ).length;
      $( ".RS2" ).text( n + ( " Item" ));
    };
    countChecked();
        $( "input[name=CB2]" ).on( "click", countChecked );
    });
    $('input[name=CB3]').on('ifChanged', function(event){
      var countChecked = function() {
      var n = $( "input[name=CB3]:checked" ).length;
      $( ".RS3" ).text( n + ( " Item" ));
    };
    countChecked();
        $( "input[name=CB3]" ).on( "click", countChecked );
    }); 
    $('input[name=CB4]').on('ifChanged', function(event){
      var countChecked = function() {
      var n = $( "input[name=CB4]:checked" ).length;
      $( ".RS4" ).text( n + ( " Item" ));
    };
    countChecked();
        $( "input[name=CB4]" ).on( "click", countChecked );
    });
</script>



disable button on certain select checkbox

I had condition in my reactive form where one checkbox selected, submit button will be enabled, and if there are none checkbox selected, it will remain disabled, the problem is I had selectAll function, which if I clicked, it will selected all the checkbox and enabled submit button, then if I unselect individual checkbox after select all function, the submit button should be enabled until all the checkbox is unselect, this is what I had tried:

ts file

  selectAll() {
    this.formReceivedSummons.controls.map(value => value.get('isChecked').setValue(true));
    return this.disabledButton = false;
  }

  changeCheck(event){
    this.disabledButton = !event.target.checked;
  }

html file

<div *ngIf="isShowResponse">
    <p>Inquiry Response</p>
    <form [formGroup]="form" (ngSubmit)="submitSelectedCheckboxes()">
        <ng-container formArrayName="receivedSummons" *ngFor="let 
            summon of formReceivedSummons.controls; let i = index">
            <ng-container [formGroupName]="i">
                <input type="checkbox" formControlName="isChecked"
        (change)="changeCheck($event)">
  
      </ng-container>
    </ng-container>
    <button [disabled]="disabledButton">Submit</button>
</form>
<button (click)="selectAll()">Select All</button>
</div>

supposed to be after select all function, submit button will enabled until all checkbox is unselected individually then it will disabled, this is my stackblitz demo, I could use any suggestion to solve this problem,




vendredi 27 septembre 2019

check the checkbox if name and value match with the input checkbox field

.html

var url = http: //127.0.0.1:8000/search/?name=san&language=1&cast=1&language=2&cast=3;
  existingUrl(var);

function existingUrl(fullUrl) {
  $('.language').each(function() {
    var hasValue = fullUrl.indexOf($(this).val());
    if (hasValue != -1)
      this.checked = true;

  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="get">


  <input type="text" name="name" id="name" hidden> language
  <input type="checkbox" name="language" class="language" id="1" value="1"> cast
  <input type="checkbox" name="cast" class="cast" id="2" value="1"> language
  <input type="checkbox" name="language" class="language" id="3" value="2"> cast
  <input type="checkbox" name="cast" class="cast" id="4" value="3"> 
  <input type="submit" value="submit">
</form>

It work fine if all the checkbox input value have different value.If we try with different name having same value it checked all checkbox with that value.




Hi i want the task(number) dynamic using pivot table

enter image description here

I just tried this code to show you the output but this will be crazy if I got different number of tasks that's why i want the Task1,2,3,4,5,6,7 to be dynamic because I save it like this : enter image description here




How to get values in Check boxes from database using viewbag?

I am using view bag to get skills. How to get data from viewbag in @html.Checkboxfor().

  ViewBag.ListSkill = GetSkills();


  public List<UserViewModel> GetSkills()
    {
        var client = new RestClient(url);
        var request = new RestRequest("api/Users/GetAllSkillList", Method.GET);
        var response = client.Execute<List<UserViewModel>>(request);


        return response.Data;
    }

I saw many examples using viewbag but they all using but I need to write the code in @html.Checkbox. Please Help.




How do I get checkbox value to be used in another function?

I have a widget that displays a checkbox. The checkboxes display days of the week. I am curious to know how I can use the values below in another function? For example, how can I know in another function what the user has selected in terms of a week day?

Here is my checkbox widget code:

  bool monVal = false;
  bool tuVal = false;
  bool wedVal = false;
  bool thurVal = false;
  bool friVal = false;
  bool satVal = false;
  bool sunVal = false;

  Widget checkbox(String title, bool boolValue) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text(title),
        Checkbox(
          value: boolValue,
          onChanged: (bool value) {
            /// manage the state of each value
            setState(() {
              switch (title)
              {
                case "Mon":
                  monVal = value;
                  print(value);
                  break;
                case "Tu":
                  tuVal = value;
                  print(value);
                  break;
                case "Wed":
                  wedVal = value;
                  print(value);

                  break;
                case "Thur":
                  thurVal = value;
                  print(value);

                  break;
                case "Fri":
                  friVal = value;
                  print(value);

                  break;
                case "Sat":
                  satVal = value;
                  print(value);

                  break;
                case "Sun":
                  sunVal = value;
                  print(value);

                  break;
              }
            });
          },
        )
      ],
    );
  }

the print(value) is pointless.. I just tried that to see if I could get the day of the week selected, but its only going to return true or false.

Many thanks friends




javascript/html - change color of checkbox text when box if checked by user

So I'm trying to change the color of my checkbox text label when the user checks the box and clicks the toggle button. I looked up other examples and tried to make my own solution below but it doesn't work when I check the boxes I want to check and click the button. I was wondering why?

html:

<html>
    <head>
        <title>Survey</title>
    </head>
    <body>
        <div id ="myCheckList">Enter:</div>
        <div>Type something: <input type="text" id="textbox"> </input></div>
        <input type="button" id="addBut" value = "Add item" onclick="addItem()"/>
        <input type="button" id="toggleBut" value = "Toggle highlight" onclick="toggleItem()"/>

        <script src="addHandler.js"></script>
        <div id="checklist_items"></div>
    </body>
</html>

javascript:

function addItem() {
    var input = document.getElementById("textbox");
    var wrapper = document.getElementById("checklist_items");
    if(input.value.trim() != "") {
        var new_element = document.createElement("DIV");
        new_element.innerHTML = '<input type="checkbox"> '+input.value;
        wrapper.appendChild(new_element);
    document.getElementById('textbox').value = '';
    }else {
        alert("You must enter at least 1 character.");
    }
}

function toggleItem(){
    var chkbx = document.querySelectorAll('checklist_items');
    if (chkbx.checked){
        document.getElementById('checklist_items').style.color = "red";
    }else{
        document.getElementById("box").style.backgroundColor = "transparent";

}

}



javascript & html - how to delete a check box

I basically just posted a question related to this task so I apologize if it seems really repetitive but I ran into another problem.

So basically I'm creating a program that allows the user to create and manage a ‘to-do list’ by getting the user to add and remove items. Currently if the user enters something in the textbox and clicks the add button, a new checkbox is made. I'm trying to get it so that the user can also remove checkboxes/items by checking a box and clicking the remove button. I tried writing a program in an attempt to do the above, but when I went to run it in my html browser, it didn't do anything and I'm not sure why.

HTML CODE:

<html>
    <head>
        <title>Checklist</title>
    </head>
    <body>
        <div><h1>My to-do list</h1></div><br />
        <div id ="myCheckList">Enter an item:</div>
        <div>Type something: <input type="text" id="textbox"></input></div>
        <input type="button" id="addBut" value = "Add item" onclick="addItem()"/>
        <input type="button" id="removeBut" value =  "Remove items" onclick="removeItem()"/>
        <input type="button" id="toggleBut" value = "Toggle highlight" onclick="toggle()"/>
        <input type="button" id="sortBut" value = "Sort items" onclick="sort()"/>

        <script src="addHandler.js"></script>
        <div id="checklist_items"></div>
    </body>
</html>

JAVASCRIPT CODE:

function addItem() {
    var input = document.getElementById("textbox");
    var wrapper = document.getElementById("checklist_items");
    if(input.value.trim() != "") {
        var new_element = document.createElement("DIV");
        new_element.innerHTML = '<input type="checkbox"> '+input.value;
        wrapper.appendChild(new_element);
    }
    else {
        alert("You must enter at least 1 character.");
    }
}


function removeItem(){
    if (document.getElementById('checklist_items').checked){
        ("checklist_items").remove();
    }

}



radio and checkbox appearance difference on chrome and Firefox bowers and safari browser on Ipad and iphone 10 are in small size

(First point) Radio and checkbox appearance difference on chrome and Firefox browsers, and (second point) safari browser on Ipad & iPhone 10 it appears smaller in size. ( third point ) is about the input placeholders appearance on chrome, firefox & safari browsers.

Tried on Chrome windows, firefox windows, safari on Ipad & iPhone 10 Placeholders on chrome upwards, firefox downwards, safari center.




Linking 2 check boxes on different page on MFC dialog based application

I have made 1 single dialog with 2 different GUIs and they can be selected by tabs. Each GUI has many check boxes. Some of the check boxes are linked, such that when 1 is checked, the other one will automatically be checked. When the 2 linked check boxes are on the same GUI, I can do it. But when they are on different GUIs, I have problems. Is it possible to link 2 check boxes on different GUIs?

This is how I linked 2 check boxes on the same GUI. When checkbox1 is checked, checkbox2 will also become checked.

void ProjectName::OnBnClickedCheckBox1()
{
    bool x = ((CButton*)GetDlgItem(IDC_CheckBox1))->GetCheck();
    ((CButton *)GetDlgItem(IDC_CheckBox2))->SetCheck(x);
}

But this doesn't work when the other checkbox is on the other GUI. Is there a way I can call a checkbox (eg. IDC_CheckBox3) which is on another GUI on this GUI's .cpp? Or is there any other way I can do this?

Thank you in advance!




change text dynamically based on checkbox value

using FormArray I had bind checkbox on my component, default label of checkbox is select, when I clicked checbox, label will change to selected for each of checkbox (supposed to be), I also got selectAll button which change value of all checkbox to true and change text to selected, my problem is :

  • when I select only one checkbox, change label will also effected other checkbox
  • when I had selectAll checkbox, all checkbox label will change to selected,then if I unselected individual checkbox, it supposed to be change label to select

this is what I had tried:

html file

<div *ngIf="isShowResponse">
    <p>Inquiry Response</p>
    <form [formGroup]="form" (ngSubmit)="submitSelectedCheckboxes()">
        <ng-container formArrayName="receivedSummons" *ngFor="let summon of formReceivedSummons.controls; let i = index">
            <ng-container [formGroupName]="i">
                <input type="checkbox" formControlName="isChecked"
        (change)="checkedState(summon)">
            
           </ng-container>
       </ng-container>
   </form>
<!-- <pre></pre> -->
<button (click)="selectAll()">Select All</button>
</div>

ts file

    checkedState(summon) {
    summon.checked = !summon.checked;
    this.summonText = summon.checked === true ? 'selected' : 'select';
  }

  selectAll() {
    this.formReceivedSummons.controls.map(value => value.get('isChecked').setValue(true));
    return this.summonText = 'selected';
  }

and this is my full stackblitz demo, i could use some suggestion and better practice to solve this problem




jeudi 26 septembre 2019

Is it possible to disable a checkbox rather than hide it in an MFC dialog based application?

My program contains many check boxes arranged in a 20 x 15 manner. Some are not needed depending on other conditions. I have managed to hide them using "ShowWindow(False)", but it can get very confusing/messy because the neat arrangement of the 15 x 20 gets disturbed when many boxes are hidden.

Is there a way that I can keep the check boxes there, but grey them out and disable them rather than hide them completely?




How to store the values from array checkbox in laravel controller with vuejs?

I want to store / save the values of my checkboxes from array. Please help i don't get the answers after searching and searching. I also use the spatie package laravel permission.

Role.vue

<ul>
<!-- Check All -->
<input type="checkbox" @click="select" v-model="isCheckAll"> Check All

   <li class="list-group-item bold" v-for="item in permissions" :key="item.id">
   <input type="checkbox" :value="item.id" v-model="selected" name="permission[]"> 
   </li>
</ul>

RoleController.php

if($request['permission']!= null){
            foreach ($request['permission'] as $value){
                $role->syncPermissions($request->all());
            }
        }

What i expect is to store all the values from my checkbox.




How to connect JS functions to checkbox

Hello,

I am making a simple text changer website where I want the user to be able to select what options to use. Right now I have two options; myConvertOption which capitalizes every odd letter in a word and I have myScrambleOption which randomly mixes up each word a bit.

Right now whenever you click on Caps (checkbox_1) it already executes the function where I only want it to execute whenever the user clicks on the "Convert" button + it also puts spaces in between each letter now. The Scramble button (checkbox_2) doesn't do anything for some reason, except for console logging the change.

JSfiddle: https://jsfiddle.net/MysteriousDuck/hLjytr2p/1/

Any help and suggestions will be greatly appreciated!

P.S I am new to Javascript.

Checkbox event listeners:

checkbox_1.addEventListener('change', function () {
    console.log("checkbox_1 changed");
    if (this.checked) {
        myConvertFunction();
    } else {
        //Do nothing
    }
})

checkbox_2.addEventListener('change', function () {
    console.log("checkbox_2 changed");
    if (this.checked) {
        myScrambleFunction(text);
    } else {
        //Do nothing
    }
})

Checkbox HTML:

        <div class="checkbox">
            <input type="checkbox" id="checkbox_1" >
            <label for="checkbox_1">Caps</label>
        </div>
        <div class="checkbox">
            <input type="checkbox" id="checkbox_2" >
            <label for="checkbox_2">Scramble</label>
        </div> 



How do I change the border color of a Checkbox using JavaScript for Google Chrome?

I am trying to to reproduce this border effect

document.getElementById("e1").style.border='2px solid blue';
<input type="text" id="e1">

for checkboxes and radio buttons. I have read similar posts to this, but none seem to offer a solution that works. I am using the JavascriptExecutor object in a Java application so keeping the code to JavaScript is the goal. I've read a good approach is to wrap the checkbox with a div, but I am not strong enough with JavaScript to do that.

Ultimately, I'm trying to highlight an element after I change it with Selenium, so even making the Labels bold will suffice. Any help would be appreciated.




Rails: Using multiple checkboxes for single field

I have a form with multiple checkboxes and I'd like to combine their values into a string before saving to the database. I've designed my form like:

<%= simple_form_for(@health_profile) do |f| %>

    <% @hp_prior.medications.split(", ").each do |med| %>
        <%= check_box_tag "health_profile[medications][]", med, false, id: med, multiple: true %>
        <label for="<%= med %>"><%= med.capitalize %></label>
    <% end -%>

<% end -%>

In my controller I've changed :medications to accept an array:

def health_profile_params
    params.require(:health_profile).permit(:medications => [])
end

But I run into an issue with the data because the submitted form params come through as:

Parameters: {... "health_profile"=>{"medications"=>["zyrtec for allergies", "advil"]}, "commit"=>"Submit"}

But after calling HealthProfile.new(health_profile_params) the record appears as:

#<HealthProfile:0x007fb08fe64488> {... :medications => "[\"zyrtec for allergies\", \"advil\"]"}

How can I combine these values so that the final @health_profile looks like:

#<HealthProfile:0x007fb08fe64488> {... :medications => "zyrtec for allergies, advil"}



How to make checkbox control my Javascript Functions?

Hello people,

I want to be able to check a box enabling only one, or both of the functions (including the myScrambleFunction and myConvertFunction) the myConvertFunction capitalizes every odd letter, and the myScrambleFunction scrambles up each word a bit. Sometimes I'd like to only use the scramble function (without the capitalize function) and the other way around.

I am trying to add a eventlistener to the checkboxes, but for some reason it does not work.

Right now, the checkbox_2 does enable myScrambleFunction and enabling myConvertFunction (checkbox_1) kinda works like the convert button that does not work anymore. I just want my checkboxes to "enable" myConvertFunction and myScrambleFunction.

JSfiddle: https://jsfiddle.net/MysteriousDuck/zue583gq/3/

I have tried googling my problem and couldn't find a solution.

//Checkbox checked checker. 
var checkbox = document.querySelector("#checkbox_1");

checkbox_1.addEventListener( 'change', function() {
    if(this.checked) {
        myConvertFunction(document.getElementById("inputText").value);
    } else {
        //Do nothing
    }
});

var checkbox = document.querySelector("#checkbox_2");

checkbox_2.addEventListener( 'change', function() {
    if(this.checked) {
        myScrambleFunction(document.getElementById("inputText").value);
    } else {
        //Do nothing
    }
});


        <div class="checkbox">
            <input type="checkbox" id="checkbox_1" >
            <label for="checkbox_1">Caps</label>
        </div>
        <div class="checkbox">
            <input type="checkbox" id="checkbox_2" >
            <label for="checkbox_2">Scramble</label>
        </div> 



How to bind checkbox to string value in Angular7?

<input pInputText type="checkbox" [(ngModel)]="rowData.active"> active is a string. It's value is 'true' or 'false'. I wanna bind this string value to a checkbox. So how can I do that?




mercredi 25 septembre 2019

Toggling CheckBox

      <form>

                Age: <input type="checkbox" class="first" value="Below 10">Below 10
                        <input type="checkbox" class="first" value="Below 20"> Below 20
                        <input type="checkbox" class="first" value="Below 30">Below 30
                        <br>

                        You have clicked: 
                <span id="maClass">
                        
                </span>

          </form>
          <script type="text/javascript">
                        var maClass = document.querySelector("#maClass");
                        var first = document.querySelectorAll(".first");

                        var isClicked = false;
                        var i=0;
                        for(i; i<first.length ; i++){

                          first[i].addEventListener("click", function() {
        
                                if(isClicked){
                                        maClass.style.display = "none";
                                        isClicked = false;
                                }else{
                                        maClass.style.display = "inline";
                                        maClass.style.display = first[i].getAttribute("value");
                                        isClicked = true; 
                            }

                          });
                    }
          </script>

I tried to make these 3 checkboxes toggle. I used eventListener in Javascript. I used same class name for 3 different checkboxes. This is because, it will help me to store whole decision into one array. But it doesn't work I cannot make it toggle. Please help




How to enable/disable javascript functions with a checkbox?

Hello stackoverflow,

How would I make it possible to (temporarily) disable/enable javascript functions for a with a checkbox.

I want to be able to check a box enabling only one, or both of the functions (including the myScrambleFunction and myConvertFunction) the myConvertFunction capitalizes every odd letter, and the myScrambleFunction scrambles up each word a bit. Sometimes I'd like to only use the scramble function (without the capitalize function) and the other way around.

Any suggestions and examples will be greatly appreciated :)

This: https://jsfiddle.net/MysteriousDuck/3pndLbgq/3/ is what I have right now.

I have tried googling this problem but could not find a solution that suits my needs.

<body>

    <div class="container">

        <h1> Text Changer </h1>
        <h2> CAPS + randomize letters text changer</h2>

        <div class="checkbox">
            <input type="checkbox" id="checkbox_1">
            <label for="checkbox_1">Caps</label>
        </div>
        <div class="checkbox">
            <input type="checkbox" id="checkbox_2">
            <label for="checkbox_2">Scramble</label>
        </div> 

        <textarea type="text" autofocus="true" placeholder="input text" id="inputText" value="Input Value" spellcheck="false" style="width: 300px;"></textarea>
            <button class="button button1" onclick="myConvertFunction(); myScrambleFunction(text);">Convert</button>
        <textarea type="text" placeholder="CoNvErTeD tExT" id="converted" value="Clear" readonly="true" spellcheck="false" style="width: 300px;"></textarea>
            <button class="button button1" onclick="myCopyFunction(); eraseText();">Copy</button>

    </div>
</body>
function myConvertFunction() {
    var x = document.getElementById("inputText").value;
    var letters = x.split("");
    var string = "";
    for (i = 0; i < letters.length; i++) {
        if (i % 2 == 0) {
            string += letters[i].toUpperCase();
        } else {
            string += letters[i];
        }
    }
    document.getElementById("converted").value = myScrambleFunction(string);
}

function myCopyFunction() {
    var copyText = document.getElementById("converted");
    copyText.select();
    document.execCommand("copy");
    alert("Copied the text: " + copyText.value);
    eraseText();
}

function eraseText() {
    document.getElementById("converted").value = "";
    document.getElementById("inputText").value = "";
    document.getElementById("inputText").focus();
}

function myScrambleFunction(text) {
    let words = text.split(" ");

    words = words.map(word => {
        if (word.length >= 3) {
            return word.split('').sort(() => 0.7 - Math.random()).join('');
        }

        return word;
    });

    return words.join(' ');
}



How to check/uncheck checkbox slowly kendo grid

In my application, I'm using the kendo grid to display data. I'm using dropdown which contains three values called 'opt-in, opt-out and all'. when user select Opt-in from the drop-down and particular data is listing.

enter image description here

In the above grid, you can see, there is a checkbox column called opt in. once the user unchecks the checkbox that row is quickly removing from the grid. (because of its become to the opted-in status ).

code (this works fine)

$("#productServicesByLocationGrid .k-grid-content").on("change", "input.chkbx", function (e) {

    e.preventDefault();
    var grid = $("#productServicesByLocationGrid").getKendoGrid();
    var dataItem = grid.dataItem($(e.currentTarget).closest("tr"));
    dataItem.set("OptIn", this.checked);
});

I need to avoid this quick remove and need to add some slowness to uncheck the checkbox. therefor, I change my code as follows,

$("#productServicesByLocationGrid .k-grid-content").on("change", "input.chkbx", function (e) {

    var delayInMilliseconds = 1000; //1 second
    setTimeout(function () {
    e.preventDefault();
        var grid = $("#productServicesByLocationGrid").getKendoGrid();
        var dataItem = grid.dataItem($(e.currentTarget).closest("tr"));
        dataItem.set("OptIn", this.checked);
    }, delayInMilliseconds);
});

But after changing the code as above, it's not working fine, the checkbox is unchecking slowly, it's working, but it's opt-in status not changed to the opt-out status. how can I add some slowness to the checkbox to display slowly uncheck and check state change? have any proper way to show slowly checkbox uncheck and check.




How to enable/disable javascript functions with a checkbox

Hello stackoverflow,

How would I make it possible to (temporarily) disable/enable javascript functions for a with a checkbox.

I want to be able to check a box enabling only one, or both of the functions (including the myScrambleFunction and myConvertFunction) the myConvertFunction capitalizes every odd letter, and the myScrambleFunction scrambles up each word a bit. Sometimes I'd like to only use the scramble function (without the capitalize function) and the other way around.

Any suggestions and examples will be greatly appreciated :)

This: https://jsfiddle.net/MysteriousDuck/3pndLbgq/3/ is what I have right now.

I have tried googling this problem but could not find a solution that suits my needs.


<body>

    <div class="container">

        <h1> Text Changer </h1>
        <h2> CAPS + randomize letters text changer</h2>

        <div class="checkbox">
            <input type="checkbox" id="checkbox_1">
            <label for="checkbox_1">Caps</label>
        </div>
        <div class="checkbox">
            <input type="checkbox" id="checkbox_2">
            <label for="checkbox_2">Scramble</label>
        </div> 

        <textarea type="text" autofocus="true" placeholder="input text" id="inputText" value="Input Value" spellcheck="false" style="width: 300px;"></textarea>
            <button class="button button1" onclick="myConvertFunction(); myScrambleFunction(text);">Convert</button>
        <textarea type="text" placeholder="CoNvErTeD tExT" id="converted" value="Clear" readonly="true" spellcheck="false" style="width: 300px;"></textarea>
            <button class="button button1" onclick="myCopyFunction(); eraseText();">Copy</button>

    </div>
</body>

</html>
/* Made by MysteriousDuck#5764 */

function myConvertFunction() {
    var x = document.getElementById("inputText").value;
    var letters = x.split("");
    var string = "";
    for (i = 0; i < letters.length; i++) {
        if (i % 2 == 0) {
            string += letters[i].toUpperCase();
        } else {
            string += letters[i];
        }
    }
    document.getElementById("converted").value = myScrambleFunction(string);
}

function myCopyFunction() {
    var copyText = document.getElementById("converted");
    copyText.select();
    document.execCommand("copy");
    alert("Copied the text: " + copyText.value);
    eraseText();
}

function eraseText() {
    document.getElementById("converted").value = "";
    document.getElementById("inputText").value = "";
    document.getElementById("inputText").focus();
}

function myScrambleFunction(text) {
    let words = text.split(" ");

    words = words.map(word => {
        if (word.length >= 3) {
            return word.split('').sort(() => 0.7 - Math.random()).join('');
        }

        return word;
    });

    return words.join(' ');
}



How to remove element from array after uncheck of checkbox

I am having multiple locations, on check of the particular location i can able to push those into array on check of checkbox unable to remove from array

handleChange(e){
    if(e.target.checked){
        let selectedLocations = this.state.selectedLocations;
        selectedLocations.push({
            name: e.target.name,
            isActive: true
        });
        this.setState({
            selectedLocations: selectedLocations
        });
    }else{
        let selectedLocations = this.state.selectedLocations;

    }


}

{
 locations && locations.map((el, i) => {
   return (
         <div className="col-md-4">
         <div className="form-group">
         <input type="checkbox" value="true"  name={el.name} onChange={this.handleChange.bind(this)}/><label> &nbsp;{el.name} </label>
      </div>
  </div>
 )
})
}

I want to remove from array after unchecking particular location




mardi 24 septembre 2019

Drupal attachBehaviors checkbox overlay not working

Although this question relates to Drupal, I am asking it here because I have a JSFiddle example of the behavior, and no knowledge of Drupal should be required.

The Goal

Create an overlayed prettier checkbox for each one. The user should be able to check/uncheck them by clicking or by keyboard. Checking the select all checkbox should check all boxes below. Unchecking should uncheck them all. If already checked, unchecking a checkbox below should uncheck the select all checkbox. Also, clicking a row should act as if you were clicking on the checkbox.

Table with checkboxes

The Problem

Clicking the non-"select all" boxes doesn't work. It changes the value twice, due to some of the VBO code for row-clicking, I think. This can be seen by viewing what is logged in the browser console when clicking one.


The JSFiddle: https://jsfiddle.net/42zxng7c/7/

Only the JQuery is included below.


A summary of the code sections:

The HTML is a small table with simulated VBO (Views Bulk Operations 7.x-3.x) checkboxes. The top checkbox is a Select All checkbox. The HTML will be modified dynamically a bit by the JQuery.

The CSS includes a basic version of some styles I use for the checkboxes. Don't pay it much attention, as it's not important to the question.

The JQuery has basically three parts:

  1. Drupal.attachBehaviors This is boilerplate, and is not super relevant. It is a minimal piece of drupal.js from Drupal 7.67 to use Drupal.attachBehaviors().
var Drupal = Drupal || { 'settings': { 'vbo': { 'row_clickable': true } }, 'behaviors': {} };

Drupal.attachBehaviors = function (context, settings) {
  context = context || document;
  settings = settings || Drupal.settings;
  // Execute all of them.
  $.each(Drupal.behaviors, function () {
if ($.isFunction(this.attach)) {
  this.attach(context, settings);
}
  });
};

$.fn.once = function (events, callback) {
  //The handler is executed at most once per element for all event types.
  return this.each(function () {
$(this).on(events, myCallback);
function myCallback(e) {
  $(this).off(events, myCallback);
  callback.call(this, e);
}
  });
};

// ( and this part from the end )

//Attach all behaviors.
$(function () {
  Drupal.attachBehaviors(document, Drupal.settings);
});
  1. Drupal.behaviors.prettyCheckboxes This is my code, the part with a bug. It is where I modify the HTML a bit and do some work to create pretty checkboxes and radio buttons that replace the normal ones. The radio button portions are not included. Any changes to fix the problem need to happen in this section.
/**
 * Add some JS-based state detection in order to allow prettier checkboxes
 * and radio buttons.
 */
Drupal.behaviors.prettyCheckboxes = {
  attach: function (context, settings) {
// If there are are a ton of elements, don't bring the browser to a
// screeching halt.
var $elements = $('.form-type-checkbox, .form-type-radio', context);
$elements.each(function () {
  // Used for styling purposes.
  $('label', this).prepend('<span class="input"></span>');

  var $input = $('input', this);

  // Add selected state on checkbox inputs.
  $('input[type="checkbox"]', this).each(function () {
    $(this).change(function (event) {
      if (event) {
        // Show change events.
        console.log($(this).attr('value'));
      }
      Drupal.behaviors.prettyCheckboxes.toggleCheckbox(this);

      // Uncheck the "select all" checkbox in the table header.
      var table = $(this).closest('table')[0];
      if (table) {
        var $selectAll = $('.vbo-table-select-all', table);
        Drupal.behaviors.prettyCheckboxes.toggleCheckbox($selectAll);
      }
    });

    Drupal.behaviors.prettyCheckboxes.toggleCheckbox(this);
  });

  // Check if this is a VBO "select all" checkbox.
  if ($input.hasClass('vbo-table-select-all')) {
    // Trigger change event on all vbo-select checkboxes on change,
    // because VBO updates the properties without triggering the event.
    $(this).change(function (event) {
      $(this).closest('table').find('.vbo-select').trigger('change');
    });
  }
});

// if (Drupal.settings.vbo.row_clickable) {
//   $('span.input', context).on('click', function () {
//     $(this).next('input[type="checkbox"]:not(.vbo-table-select-all)').trigger('click');
//   });
// }
  },
  toggleCheckbox: function (checkbox) {
if ($(checkbox).is(':checked')) {
  $(checkbox).closest('.form-type-checkbox').addClass('checked');
}
else {
  $(checkbox).closest('.form-type-checkbox').removeClass('checked');
}
//Drupal.attachBehaviors(checkbox);
  }
};
  1. Drupal.vbo Some code I copied from the Views Bulk Operations 7.x-3.5 project (views_bulk_operations.js) that I am using in order to show how it interacts with my code. It is licensed under GNU GPLv2.
(function ($) {
  Drupal.behaviors.vbo = {
attach: function(context) {
  $('.vbo-views-form', context).each(function() {
    Drupal.vbo.initTableBehaviors(this);
    Drupal.vbo.initGenericBehaviors(this);
  });
}
  }

  Drupal.vbo = Drupal.vbo || {};
  Drupal.vbo.initTableBehaviors = function(form) {
$('.vbo-table-select-all', form).show();
// This is the "select all" checkbox in (each) table header.
$('input.vbo-table-select-all', form).click(function() {
  var table = $(this).closest('table:not(.sticky-header)')[0];
  $('.vbo-select:not(:disabled)', table).prop('checked', this.checked);
});

// Set up the ability to click anywhere on the row to select it.
if (Drupal.settings.vbo.row_clickable) {
  $('.views-table tbody tr', form).click(function(event) {
    var tagName = event.target.tagName.toLowerCase();
    if (tagName != 'input' && tagName != 'a' && tagName != 'label') {
      $('.vbo-select:not(:disabled)', this).each(function() {
        // Always return true for radios, you cannot de-select a radio by clicking on it,
        // it should be the same when clicking on a row.
        this.checked = $(this).is(':radio') ? true : !this.checked;
        $(this).trigger('change');
      });
    }
  });
}
  }

  Drupal.vbo.initGenericBehaviors = function(form) {
// Handle a "change" event originating either from a row click or an actual checkbox click.
$('.vbo-select', form).change(function() {
  // If a checkbox was deselected, uncheck any "select all" checkboxes.
  if (!this.checked) {
    $('.vbo-select-this-page', form).prop('checked', false);
    $('.vbo-select-all-pages', form).prop('checked', false);
    // Modify the value of the hidden form field.
    $('.select-all-rows', form).val('0')

    var table = $(this).closest('table')[0];
    if (table) {
      // Uncheck the "select all" checkbox in the table header.
      $('.vbo-table-select-all', table).prop('checked', false);
    }
  }
});
  }

})(jQuery);

I have spent hours working on this, and I fixed some other issues I had, but so far I cannot figure out why the checkboxes don't work or how I can adapt my code to fix it in a good way. There is a piece of commented out code in my section that might work as a workaround, but it's bad since it simply fires the click event again for each checkbox.

Any help would be great. Thanks.




Unable to get the reference of CheckBox in android

I am using a CheckBox in my activity layout. But I don't know why I am not getting the refrence of the CheckBox. It shows NullPointerException everytime. I have used another checkbox in my dialog fragment but it was working fine. I don't know what is the cause of NullPointerException.

Here is xml code

 <CheckBox
        android:id="@+id/ccb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="8dp"
        android:text="Add Your Previous Amount\n with Current Amount "
        android:textColor="@color/batteryChargedBlue"
        android:textSize="13dp"
        android:fontFamily="@font/caviardreams_bolditalic"
        />

Here is the java code where I am using the checkbox and getting NullPointerException.

public class StartActivity extends AppCompatActivity {



//Declaring the CheckBox variable globally


CheckBox scb;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);



    ...

       //Initializing in the onCreate() method
       scb = (CheckBox)findViewById(R.id.ccb);

    ...
}

//using it in the button clicked method to check whether checkbox is checked or not
public void setInitialMonthlyAmount(View view) {

      if(scb.isChecked()) { //Getting The NullPointerException Here Don't know why ??
                System.out.println("Checkbox is checked");
                //Code
            }else {
                //Code
            }
}


}

I think everything is correct. and I am using the same way to get the references of other views like TextViews, EditText etc and they are working fine. I don't what is wrong with this checkbox. Please Help!!!




How can I open a new tab automatically if a checkbox is checked in Vue.js?

There are three tabs: Basic, History and Timetable on my sharepoint webpage. (See image). I've got a class PlayerTabs.vue in which those tabs were created and infos from other classes imported:

<template>
  <div>
    <div class="row" style="margin-bottom:20px">
      <button class="btn btn-primary" @click="changeSelectedComp">Back</button>
    </div>
    <vue-tabs>
      <v-tab title="Basic">
        <app-players></app-players>
      </v-tab>
      <v-tab title="History">
        <app-histories></app-histories>
      </v-tab>
      <v-tab title="Timetable">
        <app-timetables></app-timetables>
      </v-tab>
    </vue-tabs>
  </div>
</template>

<script>
import * as $ from "jquery";
import Players from "./PlayerBasicInfo/Players.vue";
import Histories from "./History/Histories.vue";
import Timetables from "./Timetable/Timetables.vue";

export default {
  components: {
    appPlayers: Players,
    appTimetables: Timetables,
    appHistories: Histories,
  },
  methods: {
    changeSelectedComp: function() {
      this.$store.state.selectedComp = "appTeamInfo";
    }
  }
};
</script>

<style>
.content_3f74e132 {
  padding: 0px;
}
</style>

I want to open a new tab Scholarship Player whenever the checkbox right next to the text is checked.

Tabs

The checkbox is defined in my Players.vue class which contains the following codepart:

<div class="row">
      <div class="d-inline col-lg-6 col-md-6 col-sm-6">
        <div class="row">
          <div class="d-inline col-lg-6 col-md-6 col-sm-6">
            <b>Scholarship Player</b>
          </div>
          <div class="d-inline col-lg-6 col-md-6 col-sm-6"> <input type="checkbox" id="checkbox" v-model="this.players.Scholarship"> </div>
        </div>

The data is saved in a playersData method:

playersData: function(data) {
  this.players = [];
  var $this = this;
  for (var i = 0; i < data.length; i++) {
    var Birthday = this.getJSONDateAsString(data[i].Birthday, "dd.MM.yyyy");
    $this.players.push({
      ID: data[i].ID,
      PlayerID: data[i].NameId,
      Name: data[i].Name,
      IDinformation: data[i].IDinformation,
      Nationality: data[i].Nationality,
      Birthday: Birthday,
      Scholarship: data[i].Scholarship
      // other stuff
    });
  } 

I'm pretty new to Vue.js which is why I don't know how/where exactly I have to write the "if else" part. How do I get a new tab to open up if the checkbox next to Scholarship is checked? I read about conditional rendering in Vue, f.ex. the v-if directives, such as <h1 v-if="awesome">Vue is awesome!</h1>, but I don't know how to apply the same analogy to tabs.




CSS/HTML checklist content alignment

I'm having difficulty with the following code - everything works as I wish it EXCEPT the contents of the check boxes. The ticks and crosses are too low.

Can someone tell me what I am doing wrong here please? I admit I hacked this code from several sources and glued it together, so I'm more than happy to admit I have misunderstood something or other.

Thanks!

.checkbox {
  display: inline-block;
  float: left;
  width: 25%;
  font-size: 16px;
  line-height: 36px;
  text-align: left;
}

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

.checkbox:before {
  display: inline-block;
  width: 18px;
  height: 18px;
  content: "\2715\0020";
  background-color: #f3f3f3;
  color: #000000;
  text-align: center;
  box-shadow: inset 0px 2px 3px 0px rgba(0, 0, 0, .3), 0px 1px 0px 0px rgba(255, 255, 255, .8);
  border-radius: 3px;
  margin: 0px 10px 0px 0px;
  vertical-align: middle;
}

input[type=checkbox]:checked+.checkbox:before {
  color: #f3f3f3;
  background-color: #abcdef;
  content: "\2714\0020";
  text-shadow: 1px 1px 1px rgba(0, 0, 0, .2);
}
<section>
  <form>
    <input id="option1" type="checkbox">
    <label class="checkbox" for="option1">Unchecked</label>
    <input id="option2" type="checkbox" checked>
    <label class="checkbox" for="option2">Checked, changeable</label>
    <input id="option3" type="checkbox" checked disabled>
    <label class="checkbox" for="option3">Checked, fixed</label>
    <input id="option4" type="checkbox" checked disabled>
    <label class="checkbox" for="option4">Checked, fixed</label>
    <input id="option5" type="checkbox">
    <label class="checkbox" for="option5">Unchecked</label>
  </form>
</section>



Why Checkbox animation doesn't show in Flutter?

I used Checkbox to update some data. The sharing data method is Consumer<T>. The problem is that Checkbox can work ok on changing state, but the checking animation is missing. I have located the problem, if I used notifyListeners()to notify the Data changed, then the animation of Checkbox is missing.

The Widget code just like below:

bool _value = false;
@override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Row(
      children: <Widget>[
        Checkbox(
          activeColor: Colors.green,
          value: _value,
          onChanged: (value) {
            setState(() {
              _value = value;
              widget.updateEnergy(); //The problem is Here!!!!!
            });
          },
        ),

        Text("foodName",
          style: TextStyle(color: Colors.blue,
              fontSize: 13, fontWeight: FontWeight.w300),
        ),

        Spacer(),

      ],
    );
  }

If I used the widget.updateEnergy(); to update the data in onChanged(), the animation is missing. The updateEnergy() as below:

void updateCurrentEnergy(){
    _currentEnergyCount.setValue(_getCurrentEnergyCount(), _dailyTargetEnergy.unit);

    notifyListeners();
  }

The key is "notifyListeners()", if removed the invoke, the animation is return.

I hope your help, how can get the animation of checkbox. Thank you!




lundi 23 septembre 2019

How to add the results from checkbutton and text entries on GUI into dictionary in key:value format?

Trying to create a simple shopping list app, that will have user check the checkbox then enter the number of items. The button press should output a name with the number of item. for example, Apples 10, 1 banan etc. I would like to grow the fruits dictionary and later add other items to GUI, like meats/fish, general etc.

I thought the logical way would be to create a dictionary {key:value} where key would be the name of the checkbox, and a value will be the number inside entry text box.

Could you please show me how to do this? Thanks!

tried following some examples but could not understand how to extract a text="Apples" from checkbox and add this as a key into dictionary. Also played with lambda as output but nothing really materialized because all examples alreaddy had a dictionary created. here is my example.

from tkinter import *

item_list = []
items_dict = {}

    # mget gets output from checkboxes and prints results
def mget():
    print(apples.get(), pears.get(), bananas.get(),apricots.get())
    print(apples_qnty.get(),pears_qnty.get(), bananas_qnty.get(), 
    apricots_qnty.get())
    #item_list.append(apples.get)

 window = Tk()


apples = IntVar()
chk_apples = Checkbutton(window,text="Apples", 
variable=apples).grid(row=1,sticky=W) 
apples_qnty = StringVar()
apples_qnty = Entry(width=3)
apples_qnty.grid(column=1, row = 1)
item_list.append("Apples")

pears = IntVar()
chk_pears = Checkbutton(window,text="Pears", 
variable=pears).grid(row=2,sticky=W)
pears_qnty = StringVar()
pears_qnty = Entry(width=3)
pears_qnty.grid(column=1, row = 2)
item_list.append("Pears")

bananas = IntVar()
Checkbutton(window,text="Bananas", 
variable=bananas).grid(row=3,sticky=W)
bananas_qnty = StringVar()
bananas_qnty = Entry(width=3)
bananas_qnty.grid(column=1, row = 3)
item_list.append("Bananas")


apricots = IntVar()
Checkbutton(window,text="Apricots", 
variable=apricots).grid(row=4,sticky=W)

apricots_qnty = StringVar()
apricots_qnty = Entry(width=3)
apricots_qnty.grid(column=1, row = 4)
item_list.append("Apricots")

print(item_list)  # just to see list


Button(window,text="print check box states", command = mget).grid(row=5,sticky=W)
Button(window,text="exit", command =window.destroy).grid(row=5,sticky=E)

window.mainloop()

I would like the program to do the following: user checks on checkbuttons and enters numbers of items. pressing the button would output the items selected. For example, Apples 4, Bananas 1 etc... If the checkbutton is unchecked then don't output anything.




GridViewCheckBowColumn Updates in UI after scrolling back to it

I have a RadGridView with one of the columns being a GridViewCheckBoxColumn. Upon clicking rhis column I want the checkbox to check / uncheck. I see my changes affecting the data and if I click on the column, scroll away from it and come back to it the row's check box is then updated. How do I make it so the check box updates automatically without me having to scroll away from it and come back to see the changes. Any help is appreciated.

Here's my selectedCellsChanged event in where I handle this checkbox column update:

<code>
private void SelectedCellsChanged(object sender, Telerik.Window.Controls.GridView.GridViewSelectedCellsChangedEventargs e)
{
if(!(this.grid.DataContext is ViewModel viewModel))
return;

var selectedItem = viewModel.selectedItem as Model;
if(grid.CurrentCellInfo.Column.Header.Equals("Selected"))
{
selectedItem.Selected = !selectedItem.Selected;
viewModel.SelectedItem = selectedItem;
}
}
</code>



Unable to get HTTP data to next item in Node-Red flow

I would greatly appreciate some help with some HTTP functions, like radio buttons, dropdown boxes, and checkboxes.

I have a flow, its displays a screen and gets input from the user, that input needs to be represented to the second screen in the flow for the user to confirm it is correct.

Currently, the second screen only contains most of the code from the first screen, to make it easier to update the code to the correct code.

I have been playing with this all of last week and have not been able to get the data back to the second screen.

I have included a simplified version of my code which can be loaded into Node-Red.

Thank you very much for your help.

[{"id":"e8ec9e7e.74b12","type":"tab","label":"Flow 4","disabled":false,"info":""},{"id":"7ad0187d.0e87f8","type":"http in","z":"e8ec9e7e.74b12","name":"Get v1","url":"/v1","method":"get","upload":false,"swaggerDoc":"","x":293.0173645019531,"y":119.01041412353516,"wires":[["c8e01cb.dc164e","81e7a704.c13c68"]]},{"id":"932a3f41.c4574","type":"http response","z":"e8ec9e7e.74b12","name":"","statusCode":"","headers":{},"x":313.0173645019531,"y":199.01041412353516,"wires":[]},{"id":"c8e01cb.dc164e","type":"debug","z":"e8ec9e7e.74b12","name":"Flow test1 a","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":533.0173645019531,"y":119.01041412353516,"wires":[]},{"id":"f483522.c940bb","type":"debug","z":"e8ec9e7e.74b12","name":"Flow test1 b","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":533.0173645019531,"y":159.01041412353516,"wires":[]},{"id":"81e7a704.c13c68","type":"template","z":"e8ec9e7e.74b12","name":"Input form HTML","field":"payload","fieldType":"msg","format":"html","syntax":"mustache","template":"<HTML>\n  \n    <head>\n    <meta charset=\"UTF-8\">\n        <center>Vehicle details</center>\n            <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n            <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">\n         <title>Document</title>\n    <fieldset>\n\n    <form action=\"/v1\" method=\"post\"></form>\n\n    <form id=\"v1\"><formid></formid>\n    \n    </form>\n\n    <p>Belonging to Departments:</p>\n            \n            <div>\n                  <input type=\"radio\" id=\"Tennant\" name=\"Dept A Name\" value=\"Dept A Value\" checked>\n                  <label for=\"Dept A Label\">Dept A</label>\n        \n                  <input type=\"radio\" id=\"Dept A\" name=\"Dept B Name\" value=\"Dept B Value\">\n                  <label for=\"Dept B Label\">Dept B</label>\n        \n                  <input type=\"radio\" id=\"Dept A\" name=\"Dept C Name\" value=\"Dept C Value\">\n                  <label for=\"Dept C label\">Dept C</label>\n        \n            </div>\n \n<p>Choose day of working week: </p>\n\n    <select id=\"DayOfWeek\">\n   \n      <option>Monday</option>\n      <option>Tuseday</option>\n      <option>Wednesday</option>\n      <option>Thursday</option>\n      <option>Friday</option>\n    \n    </select>\n    \n    <br>\n\n    <p>Send following type of message when seen</p>\n        <input type=\"checkbox\" name=\"CheckChoice\" id=\"\" value=\"Email\">Email\n        <input type=\"checkbox\" name=\"CheckChoice\" id=\"\" value=\"SMS\">SMS\n\n\t<br>  <br>\n\t  \n    <p>Update record</p>\n    <form action=\"/v2\" method=\"post\">\n   <button onclick=\"updatedata()\">Update Record:</button>     \n       </form>   \n \n  </fieldset>\n","x":283.0173645019531,"y":159.01041412353516,"wires":[["932a3f41.c4574","f483522.c940bb"]]},{"id":"4be22287.c3ff4c","type":"http in","z":"e8ec9e7e.74b12","name":"Post v2","url":"/v2","method":"post","upload":false,"swaggerDoc":"","x":293.0173645019531,"y":259.01041412353516,"wires":[["fc86b7c5.c21228","aa75e2b2.fcf17"]]},{"id":"55bbd60e.de9868","type":"http response","z":"e8ec9e7e.74b12","name":"","statusCode":"","headers":{},"x":313.0173645019531,"y":339.01041412353516,"wires":[]},{"id":"fc86b7c5.c21228","type":"debug","z":"e8ec9e7e.74b12","name":"Flow test2 a","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":533.0173645019531,"y":259.01041412353516,"wires":[]},{"id":"fa09f4e.2bb3a08","type":"debug","z":"e8ec9e7e.74b12","name":"Flow test2 b","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":533.0173645019531,"y":299.01041412353516,"wires":[]},{"id":"aa75e2b2.fcf17","type":"template","z":"e8ec9e7e.74b12","name":"Input form HTML","field":"payload","fieldType":"msg","format":"html","syntax":"mustache","template":"<HTML>\n  \n    <head>\n    <meta charset=\"UTF-8\">\n        <center>You updated vehicle details to the following</center>\n            <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n            <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">\n         <title>Document</title>\n    <fieldset>\n\n    <form action=\"/v2\" method=\"post\"></form>\n\n    <form id=\"v2\"><formid></formid>\n    \n    </form>\n\n    <p>Belonging to Departments:</p>\n            \n            <div>\n                \n              <input type=\"radio\" id=\"Tennant\" name=\"Dept A Name\" value=\"Dept A Value\" checked>\n              <label for=\"Dept A Label\">Dept A</label>\n    \n              <input type=\"radio\" id=\"Dept A\" name=\"Dept B Name\" value=\"Dept B Value\">\n              <label for=\"Dept B Label\">Dept B</label>\n    \n              <input type=\"radio\" id=\"Dept A\" name=\"Dept C Name\" value=\"Dept C Value\">\n              <label for=\"Dept C label\">Dept C</label>\n        \n            </div>\n \n    <p>Choose day of working week: </p>\n\n    <select id=\"DayOfWeek\">\n   \n      <option>Monday</option>\n      <option>Tuseday</option>\n      <option>Wednesday</option>\n      <option>Thursday</option>\n      <option>Friday</option>\n    \n    </select>\n    \n    <br>\n\n    <p>Send following type of message when seen</p>\n        <input type=\"checkbox\" name=\"CheckChoice\" id=\"\" value=\"Email\">Email\n        <input type=\"checkbox\" name=\"CheckChoice\" id=\"\" value=\"SMS\">SMS\n\n\t<br>  <br>\n\n    <p>Confirm details</p>\n\n    <form action=\"/v3\" method=\"post\">\n   <button onclick=\"updatedata()\">Confirm details:</button>     \n       </form>   \n       \n    <p>Fix errors</p>\n       <form action=\"/v1\" method=\"post\">\n   <button onclick=\"updatedata()\">Dont save:</button>  \n    </form>     \n     \n\n </fieldset>","x":283.0173645019531,"y":299.01041412353516,"wires":[["55bbd60e.de9868","fa09f4e.2bb3a08"]]},{"id":"4c949785.ca0998","type":"http in","z":"e8ec9e7e.74b12","name":"Post v3","url":"/v3","method":"post","upload":false,"swaggerDoc":"","x":288.0173645019531,"y":429.0104064941406,"wires":[["52214be7.d66de4","70527a96.ba8044"]]},{"id":"ed21cb1b.3bba68","type":"http response","z":"e8ec9e7e.74b12","name":"","statusCode":"","headers":{},"x":308.0173645019531,"y":509.0104064941406,"wires":[]},{"id":"52214be7.d66de4","type":"debug","z":"e8ec9e7e.74b12","name":"Flow test3 a","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":528.0173645019531,"y":429.0104064941406,"wires":[]},{"id":"696645ad.63cf3c","type":"debug","z":"e8ec9e7e.74b12","name":"Flow test3 b","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":528.0173645019531,"y":469.0104064941406,"wires":[]},{"id":"70527a96.ba8044","type":"template","z":"e8ec9e7e.74b12","name":"Input form HTML","field":"payload","fieldType":"msg","format":"html","syntax":"mustache","template":"\n\n<p>More processing here</p>\n\n\n","x":278.0173645019531,"y":469.0104064941406,"wires":[["ed21cb1b.3bba68","696645ad.63cf3c"]]},{"id":"abda4e87.8626d","type":"http in","z":"e8ec9e7e.74b12","name":"Post v1","url":"/v1","method":"post","upload":false,"swaggerDoc":"","x":297.0173645019531,"y":62.010414123535156,"wires":[["81e7a704.c13c68"]]}]




Default checked checkbox not working in angular

I tried almost all ways checked,checked="true",[checked]="true" and tried different answers like this one on stackoverflow but not working for me

    <ng-template #content>

    <label class="switch">
        <input  type="checkbox" name=""  ngModel required #="ngModel"  [checked]="true"  checked="true">
        <span class="slider round"></span>
    </label>
</ng-template>

<ng-template #other_content>

    <label class="switch">
        <input type="checkbox" name="" ngModel required #="ngModel">
        <span class="slider round"></span>
    </label>
</ng-template>




V-for and Checking Checkboxes Initially

I've been looking around SO and Google for quite a while now, while i found some working examples i cannot seem to grasp the logic behind it and adapt it to my code so here I am in need of help:

I want: to have checkboxes initially set (i get the Id, Name, whatever i want from the database and send it to vue as a prop)

                <li v-for="(value,index) in usertypes" :key="index">
              <label>
                <input
                  v-model="user.preference"
                  :id="'short_desc_'+index"
                  type="checkbox"
                  :value="value['short_desc_'+locale]"
                />
                <span class="label-text"></span>
              </label>
            </li>

the code above renders the checkboxes , they are bound to user.preferences whereas the data looks like this:

 data: function() {
return {
  user: {
    usertype: {},
    preference: [],
    languages: [],
    ...
  },

also this is how my data which determines what should be checked looks like

console.log(this.userdataobject.pre_preferences)
//Returns: (2)[{...},{...}]

//Unfolded:
-> 0: {id: ...,name:...}
-> 1: {id: ...,name:...}

so i have access to the ids and names and, if i want, ill put a checked attribute in there from my backend, no problem. But I cannot seem to grasp the logic behind the "set something initially checked".. Do i have to rename my model to something.selected and create an array, push stuff into this array then? is selected as an array a vue specific thing? (question because this is what ive seen so far on my research) or how does it work. Thanks in advance.

Edit: I think i'm on to something just as i finished sending in this post. But i'll be happy to receive explanations because I might be wrong. If i manage to solve this problem myself, i'll send in an answer.




How to remember checkbox status Rails?

My app has a list of skills to choose from. When you click on 'Save', user id and skill id are recorded in the database.

checkboxes

If the user visits this page again, all checkboxes are turned off.

How to check from the database so that the selected checkboxes are always included in the view?

My view:

= form_for(:skill_list, url: user_skill_list_index_path) do |f|
 %li
  = f.check_box(:a1, class: 'm-enabled')
  = f.label(:a1, 'Programming')
%li
  = f.check_box(:a2, class: 'm-enabled')
  = f.label(:a2, 'Communication')
%li
  = f.check_box(:a3, class: 'm-enabled')
  = f.label(:a3, 'Problem-solving')
%li
  = f.check_box(:a4, class: 'm-enabled')
  = f.label(:a4, 'Teamwork')
%li
  = f.check_box(:a5, class: 'm-enabled')
  = f.label(:a5, 'Creative')
%li
  = f.check_box(:a6, class: 'm-enabled')
  = f.label(:a6, 'Marketing')

My controller:

def create
  @skill_record = UserSkillList.where(user_id: current_user.id).first
  ...
  if @skill_record.blank?
    UserSkillList.create(user_id: current_user.id, skill_id: skills)
  else
    @skill_record.update_attributes(skill_id: skills)
  end
  redirect_to :back
end




Controlling Content Control Checkboxes Using Userform Checkboxes

I have a word document with 5 check box content controls - these are used to show which options have been selected (or not) when the document is pdf'd and/or printed. They themselves don't actually need to 'do' anything, code wise.

I have a userform which has 5 checkboxes, which corresepond to the 5 check boxes within the document. The user can select any, none, or all of these userform checkboxes, and I want the word document content control check boxes to match.

For the sake of simplicity I have named the content control checkboxes the same as the userform checkboxes, in a hope to loop through the code once I get it working.

The following works when opening the userform:

Private Sub UserForm_Initialize()

    Dim x As Variant
    Dim z As control

On Error GoTo quit

    For Each x In Array("ChkA", "ChkB", "ChkC", "ChkD", "ChkE")
        For Each z In Me.Controls
            If z.Name = x And ActiveDocument.SelectContentControlsByTitle(x).Item(1).Checked = True Then z.Value = True
        Next z
    Next x

quit:

End Sub

This does technically work, but is a little ineligent, since there is only one instance of "ChkA", or "ChkB", etc, but this code loops through each name for each checkbox, meaning it's performing 25 checks when really it only needs to be doing 5.

However, when trying to move the checkbox values from the userform back into the word document, the 'same' code above (but reversed) doesn't work, i.e.:

Private Sub cmdEnter_Click()

    Dim x As Variant
    Dim z As control

    For Each x In Array("ChkA", "ChkB", "ChkC", "ChkD", "ChkE")
        For Each z In Me.Controls
            If z.Name = x And z.Value = True Then ActiveDocument.SelectContentControlsByTitle(x).Item(1).Checked = True
        Next z
    Next x

    Unload Me

End Sub

This gives a type mismatch error on the "For Each z ..." line.

What I want to be able to do is refer to my userform checkboxes with a variable name, so that I can loop through them, something like the following maybe?

    Dim x as Variant
    Dim y as String
    Dim z as control

    x = Array("ChkA", "ChkB", "ChkC", "ChkD", "ChkE")

    For i = 0 To 4
        y = x(i)
        Set z = Me.Controls(y)
        ActiveDocument.FormFields(y).CheckBox.Value = z.Value
        Set z = Nothing
    Next i

or something like that?




dimanche 22 septembre 2019

Swift 5 Simulate Radio Button - deselecting other UIButton's not working

I have an array of around 20 UIButtons which I would like to control the selection and unselection of a set of criteria.

I have used the following as a basis https://iostutorialjunction.com/2018/01/create-checkbox-in-swift-ios-sdk-tutorial-for-beginners.html

In the example below, I have a button called mondayAM, and one called mondayPM. For the life of me, I cannot figure out how to deselect the mondayPM button. When I try and use mondayPM.isSelected, it doesn't work

@IBAction func mondayAM(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
    }

    @IBAction func mondayPM(_ sender: UIButton) {

    }

Can anyone help me figure out what I need to do to be able to deselect one or more other buttons so that I can better simulate radio buttons, please?