jeudi 31 mars 2016

only first element in checkbox is selected i need select all item on listview

here is my code for check all items on listview. only first element in checkbox is selected i need select all item on listview

public void onCheckedChanged( Compound Button button View, boolean is Checked) {
        Check Box c b=(Check Box)find View By Id(R.id. c b List_hook);
        Text View ex=(Text View) find View By Id(R.id.t v list_name);


        if(is Checked)
        {

            for(integer I =1; I<=l v. get Child Count();I++)
            {
                l v. set Item Checked(I,true);
                test.add(ex . get Text().to String());
            }

        }
        if(!is Checked)
        {
            for(integer I=1;I<=l v. get Child Count();I++)
            {
               l v. set Item Checked(I,false);
                test.remove(ex . get Text(). to String());
            }
        }
    }
}




Execute function when one of many checkboxes are checked

I have some check boxes in a table as shown below:

    <table id="checkBoxTable" class="uk-margin-small-top uk-hidden checkBoxTable" style="width:100%">
        <tr>
            <td><label id="1"><input name="1" type="checkbox"> 12am-1am</label</td>
            <td><label id="2"><input name="2" type="checkbox"> 1am-2am</label</td>
            <td><label id="3"><input name="3" type="checkbox"> 2am-3am</label></td>
            <td><label id="4"><input name="4" type="checkbox"> 3am-4am</labe</td>
       </tr>
    </table>

I want to execute a function whenever any of the checkboxes are checked. I've been trying the following:

$('#checkBoxTable').change(function(){
        var price = 10 * originalPrice;
        $('#price').value = price + "";

    });




C# For-Each Controls

i have this code within my Public Form1():

foreach (Control c in Controls)
            {
                if (c is CheckBox)
                {

                }
            }

what i'm looking to do is trigger an event when any of the CheckBoxes are clicked, it doesn't matter which one. so, for example:

if(CheckBox.Checked == True) {
 //do something to the checked checkbox 
}

but of course, this throws the error, because i havent specified which checkbox:

An object reference is required for the non-static field, method, or property 'CheckBox.Checked'

is there a way around this? Because i have the same event applied to every single checkbox like this:

 if (TestBox.Checked == true)
 {//Do Something}
 else {//Do Something}

 if (TestBox2.Checked == true)
 {//Do Something}
 else {//Do Something}

which makes my code horridly inefficient.




i am having a issues with my check boxes they wont write or load

i have 3 check boxes Nuts Cherries Sprinkles

also i am using Streamwriter and StreamReader

i also have 2 combo boxes and im using an index for those to work with writer/reader

but my checkboxes wont work i am using if ele if statments for the check boxes and im out of ideas syntax is correct as far as i know (if theres another way to get my check boxes to read and write let me know) THERE HAS TO BE A DIFFRENT WAY syntax wise to make this work lets PLEASE LET ME KNOW

for some reason i get no errors in the Debugger

THIS IS my LOAD BUTTON //(THIS IS WHERE IM HAVING PROBLEMS)

 private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        StreamReader sr;
        string strInput;

        OpenFileDialog ofd = new OpenFileDialog();

        if (ofd.ShowDialog() == DialogResult.OK)
        {
            sr = new StreamReader(ofd.FileName);

            strInput = sr.ReadLine();
            savedIndex = Convert.ToInt32(strInput);
            flavorBox.SelectedIndex = savedIndex;
            syrupBox.SelectedIndex = savedIndex;


            if (Nuts.Checked == true) 
                {

               sr.ReadLine();

                }
            else if(Cherries.Checked == true)
            {
                sr.ReadLine();
            }

            if(Sprinkles.Checked == true)
            {
                sr.ReadLine();
            }
            sr.Close();

        }

    }

THIS IS MY SAVE BUTTON (AND HERE TO I MUST BE MISSING SOMETHING)

 public partial class Form1 : Form
{
    int savedIndex = 0;

    public Form1()
    {
        //index for flavor of icecream
        InitializeComponent();
        flavorBox.SelectedIndex = 0;
        syrupBox.SelectedIndex = 0;
        pictureBox1.Image = Properties.Resources.Vanilla;
        //Nuts.
    }
    // my save fucntion
    private void saveToolStripMenuItem_Click(object sender, EventArgs e)
    {
        StreamWriter sw;

        SaveFileDialog sfd = new SaveFileDialog();

        if (sfd.ShowDialog() == DialogResult.OK)
        {
            sw = new StreamWriter(sfd.FileName);
            savedIndex = flavorBox.SelectedIndex;

            sw.WriteLine(flavorBox.SelectedIndex);

            if (Nuts.Checked == true)
            {
                sw.WriteLine();

            }
          else if (Cherries.Checked == true)
            {
                sw.WriteLine();
            }

            else if(Sprinkles.Checked == true)
            {
                sw.WriteLine();
            }

            sw.Close();
        }

    }

THIS IS MY REVERT BUTTON WHERE THE USER CAN OPEN A SAVED FILE THEN MAKE CHANGES AND JUST CLICK REVERT AND IT WILL GO BACK TO ITS ORIGINAL SAVED FILE WITH OUT RE OPENING THE FILE

private void revertToolStripMenuItem_Click(object sender, EventArgs e)
    {
        flavorBox.SelectedIndex = savedIndex;
        syrupBox.SelectedIndex = savedIndex;

    }

THIS IS MY INDEX FOR THE COMBO BOX

 private void flavorBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        int index = flavorBox.SelectedIndex;

        if (index == 0)
        {
            pictureBox1.Image = Properties.Resources.Vanilla;
        }
        else if (index == 1)
        {
            pictureBox1.Image = Properties.Resources.Chocolate;
        }
        else if (index == 2)
        {
            pictureBox1.Image = Properties.Resources.strawberry;
        }

    }

HERES MY EXPEREMENTAL IDEA TRYING TO GET THE CHECK BOX TO WORK

 private void Nuts_CheckedChanged(object sender, EventArgs e)
    {
        if(Nuts.Checked == true)
        {
            Nuts.Checked = true;
        }

        else if(Nuts.Checked != true)
                {
            //Nuts.unchecked()
        }   




More same id´s in document.getElementById("")

I have html file with 157 id´s

id="name"

and i need change style property "display" from "none" to "block" by click on one checkbox On that i have this script :

function nms(){
      if (document.getElementById("name").style.display === 'block') document.getElementById("name").style.display = 'none';
      else {document.getElementById("name").style.display === 'block';}}

which change this property in every single that id.

I need to change it on every not the first id. I just found this :

$("[id=yourID]").

but it didn´t work for me and i can´t use document.getElementByClassName because i need to change display property.

Thanks or your help, i don´t know how to make it run :-(




detecting class changes in Bootstrap Switch Jquery (converting working checkbox JS to button js)

I am trying to convert a piece of JQuery that changes the class of a tr when checked to a piece of JQuery that changes the class of a tr when a button gets a class called "active". I am a JQuery/Javascript newbie and I am at a loss.

For those who have suggested it's a duplicate, I have tried to detect class and failed (updated code below).

ORIGINAL CODE (THAT WORKS)

javascript:
  var $input_class = $('.addCheckbox');
  function setClass() {
    var tr = $(this).closest( "tr" );
    if ($(this).prop('checked') == true){
      tr.addClass( "highlight" );
    }
    else{
      tr.removeClass( "highlight" );
    }
  }
  for(var i=0; i<$input_class.length; i++) {
    $input_class[i].onclick = setClass;
  }

MY HORRIBLE TRY

javascript:
  var $input_class = $('.btn-group .btn-toggle .btn');
  function setClass() {
    var tr = $(this).closest( "tr" );
    if ($(this).prop('.btn-success .active')){
      tr.addClass( "highlight" );
    }
    else{
      tr.removeClass( "highlight" );
    }
  }
  for(var i=0; i<$input_class.length; i++) {
    $input_class[i].onclick = setClass;
  }

I am using the Bootstrap Switch Plugin which converts checkboxes to toggles http://ift.tt/11UUAbz

The converted html looks like this:

<tr>  
  <td width="15px"><input class="addCheckbox" type="checkbox" value="true" style="display: none;">
    <div class="btn-group btn-toggle" style="white-space: nowrap;">
      <button class="btn active btn-success btn-md" style="float: none; display: inline-block; margin-right: 0px;">YES</button>
      <button class="btn btn-default  btn-md" style="float: none; display: inline-block; margin-left: 0px;">&nbsp;&nbsp;&nbsp;</button>
    </div>
  </td>
  <td width="85px">May 2016</td><td class="restaurant-name">
      Joe's Crab Shack
  </td>
  <td class="text-center">
    #my table info
  </td>
</tr>

UPDATE!!! As per 'duplicate' suggestions.

After looking through this question (which was very helpful), I have changed my code to this, and I still can't get it to work. I am wondering if it is having trouble finding the exact input class? Because the plugin converts the checkbox to html, I can't (or don't know how) set specific names or ids for the buttons.

 javascript:
      var $input_class = $('.addCheckbox .btn');
      var tr = $(this).closest( "tr" );
      function checkForChanges()
      {
        if ($('.btn').hasClass('btn-success')) 
          tr.addClass( "highlight" );

        else 
          tr.removeClass( "highlight" );
      }
      for(var i=0; i<$input_class.length; i++) {
        $input_class[i].onclick = checkForChanges;
      }




Django send data to front-end - checkbox value

I read all these topics:

How do I get multiple values from checkboxes in Django

How do I get the values of all selected checkboxes in a Django request.POST?

Get the values of multiple checkboxes in django

I implemented a code, but still it doesnt work correctly. Im getting values correctly here:

VIEW:

class IndexView(TemplateView):
    template_name = 'app_student/home.html'

    def post(self, request):
        #this line returns checked values
        print request.POST.getlist('checks[]')
        url = reverse('app_student:implement')
        return HttpResponseRedirect(url)

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data()
        context['groups'] = StudentGroup.objects.all()
        context['years'] = StudyYear.objects.all()

        return context

However i dont know how to send the correct data to front-end and then to the next page(when sumbit button is pressed).

HTML:

    <button class="btn btn-primary "  value="submit" formaction=
"{% url 'app_student:otherWindow' SOMEVARIABLE %}">Sumbit</button>
    ....
    <form class="box box-default" method="post" action="">
                    {% for i in groups %}
                        {% if years.pk == i.years.pk %}
                        <tr>
                        <td> <input type="checkbox" name="checks[]" value='{{ i.id }}' > </td>
                            <td>{{ i.program }}</td>
                            <td>{{ i.course }}</td>
                            <td>{{ i.group }}</td>
                            <td>{{ i.student_count }}</td>
                            <td>{{ i.program.studyLevel }}</td>
                        </tr>
                        {% endif %}
                    {% endfor %}
                    </form>

I think SOMEVARIABLE should be sent from VIEW - like context['groups'] in HTML it is defined groups , and it is the same with 'years'.

So my question is how to do it with this line also:

somevariable = request.POST.getlist('checks[]')

And then use somevariable in HTML.

BIG THANKS GUYS.




i cant get my check boxes to show that they checked when i open the saved file

I dont understand why my save and open dont work with the check boxes any advice would be great i have three check boxes Nuts Cherries and Sprinkles

i also have to have the check boxes revert back to the original saved file as well`

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
    int savedIndex = 0;

    public Form1()
    {
        //index for flavor of icecream
        InitializeComponent();
        flavorBox.SelectedIndex = 0;
        syrupBox.SelectedIndex = 0;
        pictureBox1.Image = Properties.Resources.Vanilla;
    }
    // my save fucntion
    private void saveToolStripMenuItem_Click(object sender, EventArgs e)
    {
        StreamWriter sw;

        SaveFileDialog sfd = new SaveFileDialog();

        if (sfd.ShowDialog() == DialogResult.OK)
        {
            sw = new StreamWriter(sfd.FileName);
            savedIndex = flavorBox.SelectedIndex;

            sw.WriteLine(flavorBox.SelectedIndex);

            if (Nuts.Checked == true)
            {
                sw.WriteLine();

            }
           if (Cherries.Checked == true)
            {
                sw.WriteLine();
            }

            if(Sprinkles.Checked == true)
            {
                sw.WriteLine();
            }

            sw.Close();
        }

    }

    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        StreamReader sr;
        string strInput;

        OpenFileDialog ofd = new OpenFileDialog();

        if (ofd.ShowDialog() == DialogResult.OK)
        {
            sr = new StreamReader(ofd.FileName);

            strInput = sr.ReadLine();
            savedIndex = Convert.ToInt32(strInput);
            flavorBox.SelectedIndex = savedIndex;
            syrupBox.SelectedIndex = savedIndex;

            if(Nuts.Checked == true)
                {
                sr.ReadLine();

                return;

                }
             if(Cherries.Checked == true)
            {
                sr.ReadLine();
            }

            if(Sprinkles.Checked == true)
            {
                sr.ReadLine();
            }
            sr.Close();

        }

    }

    private void revertToolStripMenuItem_Click(object sender, EventArgs e)
    {
        flavorBox.SelectedIndex = savedIndex;
        syrupBox.SelectedIndex = savedIndex;

    }

    private void closeToolStripMenuItem_Click(object sender, EventArgs e)
    {

        Close();
    }

    private void flavorBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        int index = flavorBox.SelectedIndex;

        if (index == 0)
        {
            pictureBox1.Image = Properties.Resources.Vanilla;
        }
        else if (index == 1)
        {
            pictureBox1.Image = Properties.Resources.Chocolate;
        }
        else if (index == 2)
        {
            pictureBox1.Image = Properties.Resources.strawberry;
        }

    }

    private void Nuts_CheckedChanged(object sender, EventArgs e)
    {
        Nuts.Items.Add(true)// i tried this one on this site that found doesnt work though
    }
}

}




PHP Output multilple tables and its values in one table

I need to show you step by step what I've done so far and what the output I am looking for to happen.

First of all I have a table called stores as follows :

id | store_name
1    S1
2    S2
3    S3
4    S4

And EACH store_name has its own table that contains item number, qty, cost, sell price and date - One of them as follows :

Table Name : S1
id | item_no | qty | cost | sell | date
1      b1001   10     6      12     2015-3-31
2      b1002   12     6      12     2015-3-31
3      b1003   6      3      6      2015-3-30
4      b1004   4      5      10     2015-3-30

And so on for each store_name table.

What I'm aiming for is that I need an output to compare each Item number how many qty for each store and list them next to each other as follows :

item_no | cost | sell | S1 | S2 | S3 | S4
b1001     10     12    10     9    8     N/A
b1002     6      12    6      3    N/A   N/A
b1003     3      6     6      6    N/A   12
b1004     5      10    4      N/A  10    10

Please note, the above stores are chosen up by the user request (it could be one store name, or could be all of them) as follows:

<form method="POST" action="Somewhere.php">
//Looping To show how many stores
<input type=checkbox name=store[] value={$row['stores_name']} style='width:20px; height:20px;'>{$row['stores_name']}
//End of Looping
</form>

After submitting to Somewhere.php , we have to find out which store selected by doing foreach loop:

$allstore = $_POST['store'];

   foreach ($allstore as $store=>$value) {

//Don't Know what code should be here

}

I've tried doing my own way, but it lists store_name tables on top of each others, by which its not what I aimed for. Is there a way to do it ? Any other suggestions?

Please Note: COST and SELL prices are the same for all stores!




PHP checkbox submit with mysql integration

I'm making a user preference page where the user can check off boxes and submit them to the DB so that when the page is reloaded the boxes they previously checked will be displayed as checked. The code "works" but doesn't work as expected as my array is submitting A instead of 0 or 1 into the DB. Please remember this is a mock-up of the final product and is not in the production environment.

The logic (from beginning of code to end) is this:
1: A DB connection is made (a column exists named preferences and is varchar256) and returned is the data in the array stored in column preferences.
2: Parse the data in the array to see if the checkboxes have a value of 0 or 1 and check the boxes as required. If no value for a checkbox is found in the DB then assign one with value of 0 which will be processed if the user clicks submit.
3: Now that the page has been loaded on the users screen, if the user were to check or uncheck a box the POST conditions kick in and submit the new checkbox state to the DB (either 0 or 1) and reloads the page.

The problem is $preference_submit() is submitting A into the DB not 0 or 1 which as you can see detonates my logic since my code is looking for 0's or 1's. Looking forward to reading your inputs on my first question here on stack.

My code:

    <?php
    session_start();
    include_once 'dbconnect.php';
    if(!isset($_SESSION['user']))
{
 header("Location: /login/");
}

$result=mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);

$userInfo=mysql_fetch_assoc($result);
$db_preferences = $userInfo['preferences'];
print_r($db_preferences['preference1']); //this returns A
print_r($db_preferences['preference2']); //this returns A

$preference_submit = array("preference1"=>$preference1, "preference2"=>$preference2);

?>
<form action="" method="post">
<tr>    <td>1st Test Checkbox: </td><td><?php echo "<input type='checkbox' name='preference1' id='preference1' ";
if ($db_preferences['preference1']==1) {
        echo "checked ";
}
else {
$preference_submit['preference1'] = "0";
}
echo "value='1'>";?>

<tr>    <td>2nd Test Checkbox: </td><td><?php echo "<input type='checkbox' name='preference2' id='preference2' ";
if ($db_preferences['preference2']==1) {
        echo "checked ";
}
else{
$preference_submit['preference2'] = "0";
}
echo "value='1'>";?>

<input type="submit" name="submit">
</form>

<?php


    if(isset($_POST['submit'])){
               print_r($preference_submit); /* returns this: 
Array ( [preference1] => 0 [preference2] => 0 ) insert success
 Even when I check off a box & click submit, the values stay 0 because of my else statement 
 since $db_preferences['preference1'] and $db_preferences['preference2'] both return A
            */
         if(isset($preference_submit) && $preference_submit != ""){
                $db_user = $userInfo['user_id'];
            $s = "UPDATE users SET preferences='$preference_submit' WHERE user_id=$db_user";
                $res=mysql_query($s);
                if($res){
                    echo "insert success";
                }else{
                    die(mysql_error());

                }
          }

        }

       ?>




Laravel | Checkbox state on edit page

I have a create page for a new Case in Laravel 5, where I can link services to the case. The services are checkboxes in my createCaseForm. The services are stored in the DB so I write to a ManyToMany table to have many Cases which have many services.

Example: When I create case1, I check the boxes for service1 and service3. So now the manyToMany table is filled in correctly. Now when I go to the edit page for the case I want the checkbox1 and checkbox3 to be checked by default, because they are already linked in the manyToMany table.

I know you can use something like Input::old('username'); for textfields, but I don't know how to do this for a checkbox.

I do use LaravelCollective most of the time, but for these checkboxes I didn't. So preferably I would like a HTML solution, IF POSSIBLE ofcourse.

Thanks




A column in database store one or more values of check boxes, How i get distinct values from whole column?

_imagecolumn______________________ categorycolumn_____________________________ image1.jpg | Abstract Photo,Plants Photo,Brids Photo | image2.jpg | Human Photo,Plants Photo,Brids Photo | _-----------------------------------------------------------------------------

HOW DO I GET DISTINCT VALUES FOR BOTH THESE IMAGES

image2.jpg,image1.jpg-->Human Photo,Plants Photo,Brids Photo,
Abstract Photo




How to post multiple as array to Java servlet?

This question is the same as How to post multiple <input type="checkbox" /> as array in PHP?, but I can't make the solution work in my java servlet setup. When using the apporach of adding a [] to the name property of the grouped checkboxes, I only get the first checked option. I am not sure if it is the actual posted array that is containing only one element, or if I'm not accessing it right server side. Here is what I do to check the value in java:

@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {  
    for(String name : request.getParameterMap().keySet()){      
        System.out.println(name +": " + request.getParameter(name));        
    }
}

this prints countries[]: US, even if I have more checboxes checked after the US-input. the value changes after which checkbox is the first of the checked ones. What am I doing wrong?

Here is my HTML:

<form action="mypage" method="post">
    <input id="cb-country-gb" type="checkbox" name="countries[]" class="hide" value="GB"/>
    <input id="cb-country-us" type="checkbox" name="countries[]" class="hide" value="US"/>
    <input id="cb-country-ge" type="checkbox" name="countries[]" class="hide" value="GE"/>
    <input id="cb-country-es" type="checkbox" name="countries[]" class="hide" value="ES"/>
    <button type="submit" class="btn btn-primary">Search</button>
</form>




Checkboxes - EXT JS

I need to have a checkbox coloumn (checkcolumn) on the grid that I have created.

  1. The checkbox needs to be activated and deactivated based on the value of one particular column in the grid

  2. the checkcolumn should be triggered through a checkbox header which serves as the Select All/ Deselect All functionality

  3. On selecting the rows and then clicking a button, the data from the selected rows need to be sent to a popup window for display

I have tried a lot of approaches such as : http://ift.tt/1V9iv1N

http://ift.tt/1RM5rwX

None of these have been able to help me solve the problem I have stated. Can I get a fiddle or atleast some sort of guideline as to what will be the best approach for this ?




Getting information out of an array knockout js

I have a foreach loop from where I get cash and orig id . I am using a checkbox after the p tags and the checkbox only returns true or false.

<div data-bind="foreach : info">
<p data-bind="$data.cash"></p>
<p data-bind="$data.orig_id"></p>
<input type="checkbox"  data-bind="Switch: $root.on_off"/>
</div>

What I want to do is use the checkbox to change something in the database, so basically I need to get the orig_id of that checkbox. so I was thinking maybe if I add click binding it might give me the orig_id of which every array I get from the for each function, but did not work ofcourse. So my question is how can I get the orig_id each time the person clicks the switch box.

I tried doing something like this on the js, so I can get the orig ID from the checkbox input field.

self.sendCheckBoxInfo = function( data, event){
            alert(data.orig_id);
        }

<div data-bind="foreach : info">
<p data-bind="$data.cash"></p>
<p data-bind="$data.orig_id"></p>
<input type="checkbox"  data-bind="Switch: $root.on_off, click :    $root.sendCheckBoxInfo"  />

IF needed here is the Switch databind code

ko.bindingHandlers.Switch = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        $elem = $(element);
        $(element).bootstrapSwitch();
        $(element).bootstrapSwitch('setState', ko.utils.unwrapObservable(valueAccessor())); // Set intial state
        $elem.on('switch-change', function (e, data) {
            valueAccessor()(data.value);
        }); // Update the model when changed.
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        var vStatus = $(element).bootstrapSwitch('state');
        var vmStatus = ko.utils.unwrapObservable(valueAccessor());
        if (vStatus != vmStatus) {
            $(element).bootstrapSwitch('setState', vmStatus);
        }
    }




CheckBox: Ask user if he is sure

In a MFC custom checkbox i want to ask the user if he is sure, to change the value. So i tried this:

void CADSCheckBox::OnLButtonUp(UINT nFlags, CPoint point)
{
    bool s1, s2;
    if (!mb_ask_user)
    {
        // standard behaviour
        s1 = (GetCheck() == BST_CHECKED);
        CButton::OnLButtonUp(nFlags, point);
        s2 = (GetCheck() == BST_CHECKED);
        return;
    }

    int answer = AfxMessageBox("Are you sure?", MB_YESNO);

    if (answer == IDYES)
    {
        s1= (GetCheck() == BST_CHECKED);
        CButton::OnLButtonUp(nFlags, point);
        s2 = (GetCheck() == BST_CHECKED);
    }
    int t = 1;
}

If i dont rise the MessageBox, it works. But if the MessageBox pops up, it doesnt work. s1 and s2 are just checks to debug the issue. In the Standard behaviour it shows s1 = false and s2=true.

What to change, that i can ask the user and get my intended behaviour?

Win7 + MSVC 2013




mercredi 30 mars 2016

Removing from array values of checkboxes in jQuery

I have a checkboxes like this:

while($userRow=$resultForUsers->fetch_assoc()){
      $nameOfUser=$userRow['users_name'];
      $userId=$userRow['user_facebook_id'];
      $userFBPicture=$userRow['users_picture'];
      echo "
      <tr class='tr-data-users'>
      <td class='text-center'>
      <input type='checkbox' class='checkbox' onclick='if(this.checked){selo(this.value)}else{izbaci(this.value)}' value=$userId>
      </td>

So, for each user in my database I'm having one checkbox with value of his id. I need id's of all checked users(i.e checkboxes) in one array. I did it this way:

<input type='checkbox' class='checkbox' onclick='if(this.checked){put(this.value)}else{remove(this.value)}' value=$userId>
 var  niz={};
    var index=0;
        function put(o){
            niz[index++]=o;
            console.log(niz);
        }

So, console.log now displays id's of all checked checkboxes. What I want to do is if checkbox is unchecked then to remove that id(i.e chechbox value) from array. I tried it like this:

onclick='if(this.checked){put(this.value)}else{remove(this.value)}'
 var  niz={};
    var index=0;
        function put(o){
            niz[index++]=o;
            console.log(niz);
            remove(o,niz);
        }

        function remove(o,niz){
            if($.inArray(o,niz)){
                console.log('radim');
                var indexNiza= $.inArray(o,niz);
               niz= $.grep(niz,function(a,o){
                   return (a!=o);
               });
            }
        }   

As you can see this else part should handle if checkbox is unchecked and remove that id from array, but it doesn't work. Would really appreciate help on this.




Android Custome listview with checkbox selection

i need to save the checkbox selected items to an arraystring and also need to put select all common checkbox

here is my custome adapter class code. http://%20drive.google.com/open?id=0ByOHXkk-NSz0MnRaX1M3UE9HX2M%20%E2%80%93

thanks for help in advance




C# Loop checkbox and add value

I'm trying to add values of phones, where if a checkbox1 (which represpent phone1) is checked and checkbox2 is also checked. The program will add both phones' values. How to add the value in for loop so that the if statement is lesser and simplified.

public double totalPhone()
    {
        double total = 0;
        double item1 = 2249;
        double item2 = 1769;
        double item3 = 3099;
        double item4 = 1198;
        double item5 = 1899;

        if (chkPhone1.Checked == true)
        {
            total = total + item1;
        }

        if (chkPhone2.Checked == true)
        {
            total = total + item2;
        }

        if (chkPhone3.Checked == true)
        {
            total = total + item3;
        }

        if (chkPhone4.Checked == true)
        {
            total = total + item4;
        }

        if (chkPhone5.Checked == true)
        {
            total = total + item5;
        }

        return total;
    }




how to check checkbox in javascript loop

I already get the id from a php loop for my checkboxes, and pass them as a string(maybe not because I could not split them with comma) in parameter, then I need to check if the checkbox is checked in javascript using the ids I passed through. It doesnt seem like I can split it in javascript as well, and after I ran the for loop, the data is undefined in the new string. Do you have any ideas? Please help

here is my php

echo "<div id='addstock'>";
$ids = '';
while($row_add = mysqli_fetch_array($result_add)){

    $id=$row_add['id'];
    $company = $row_add['companyname'];
    //create checkbox for company
    echo "<p class='checkbox'><input type='checkbox' name='stocks' id='".$id."' value='".$id."'>".$company."</p><br>";
    $ids .= $id;
}
echo "</div>"; 
echo "<p class='input'><input type='submit' class='submitbutton' value='Submit' onclick='updatetable(".$ids.",".$user.")'></p>";

here is my javascript

//update table after add to stock
function updatetable(ids,user){
var url = "update.php";
//var res= ids.split(" ");
alert(ids);
var stocks = "";
 //check if the checkbox is checked
for(var id in ids){
    if(document.getElementById(ids[id]).checked)
    {   
        stocks += ids[id];
        alert(ids[id]);
    }
}
//alert(stocks);
var data = "ids="+stocks+"&user="+user;
alert(data);
ajaxRequest(url, "POST", data, true, proceedUpdate);    
}
function proceedUpdate(response){
target_div = document.getElementById("tablediv");
target_div.innerHTML = response; 
}




MVC6 TagHelper not disabling checkbox

I have written a TagHelper called CanEditTagHelper that disables/enables input controls depending on a value passed in from the view.

The TagHelper looks like this:

[HtmlTargetElement("input", Attributes = CanEditAttribute)]
public class CanEditTagHelper : TagHelper
{
    private const string CanEditAttribute = "asp-can-edit";

    [HtmlAttributeName(CanEditAttribute)]
    public bool CanEdit { set; get; }

    public CanEditTagHelper(IHtmlGenerator generator)
    {
    }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        if (!CanEdit)
        {
            output.Attributes["disabled"] = "disabled";
        }
        base.Process(context, output);
    }
}

And it is used in the view like so...

<input asp-for="UserName" asp-can-edit='Model.CanEditMember("UserName")' />

This works well for regular inputs but doesn't seem to work for CheckBoxes (specifically, bootstrap checkboxes). The disabled attribute is never added to the checkbox input.

<div class="checkbox">
    <label asp-for="Active" asp-context="label">
        <input asp-for="Active" 
               asp-can-edit='Model.CanEditMember("Active")'
               type="checkbox" />
            Active
    </label>
</div>

Does anyone know why this tag helper doesn't add a disabled attribute to checkboxes?




Short Bootstrap Checkbox variant works in jsFiddle, but not in my .jsp page

I am trying to implement these checkboxes into my JSP application.

HTML:

   <div class="row" id="checkboxes">
      <div class="col-xs-12">
         <div class="form-group">
            <label for="" class="col-md-6 control-label">Select any checkbox options:</label>
            <div class="col-md-6">
               <input name="checkbox1" type="hidden" value="0"/>
               <input name="checkbox2" type="hidden" value="0"/>
               <input name="checkbox3" type="hidden" value="0"/>
               <div class="btn-group" data-toggle="buttons">
                  <button type="button" class="btn btn-default" data-checkbox-name="checkbox1">Yes</button>
                  <button type="button" class="btn btn-default" data-checkbox-name="checkbox2">Maybe</button>
                  <button type="button" class="btn btn-default" data-checkbox-name="checkbox3">No</button>
               </div>
            </div>
         </div>
      </div>
   </div>

JavaScript:

$('.btn[data-checkbox-name]').click(function() {
    $('input[name="'+$(this).data('checkboxName')+'"]').val(
        $(this).hasClass('active') ? 0 : 1
    );
});

Here is what I know:

  • The buttons are correctly displayed in my page
  • The onclick functions are triggered when clicking a button
  • this inside the onclick method, returns the correct element, in console.log
  • example: <button type="button" class="btn btn-default" data-checkbox-name="checkbox1">Yes</button>
  • Using the above example, $(this).data('checkboxName') returns "checkbox1"
  • $('input[name="checkbox1"]').hasClass('active') returns false
  • $('input[name="checkbox1"]').val(); always returns 0 initially
  • Clicking the button with the mouse, changes the return of previous statement to 1, meaning it correctly noticed that it wasn't active. But it is still not active, unlike the jsFiddle version.
  • Clicking it again, changes nothing at all.
  • The above statements are valid for all of the checkboxes.
  • $('input[name="checkbox1"]').val(0); returns <input name="checkbox1" type="hidden" value="0">
  • $('input[name="checkbox1"]').val(); returns 0 now. Button is still not active, except when the mouse button is pressed.
  • $('input[name="checkbox1"]').hasClass('active') returns false

It seems like everything is happening as in the jsfiddle, except for the fact that the active class is never set. I can't really se where in the code it would add or remove it. After going through the code as best as I could, I am more surprised that it actually works in jsFiddle, than the fact that it doesn't in my JSP.

So why is this working in jsFiddle, and not in my JSP page?

PS: I don't know if this is relevant, but the fiddle uses bootstrap 3.0.0, while I use 3.3.5




how to check if a checkbox is checked on page load, and if it does,then show a form?

I am trying to show() a form if the checkbox is checked when the page load. Currently, my checkbox does show that is checked when I refresh the page. But, it doesn't show the form until you click twice, so if you click on the checkbox once it does uncheck it, then click one more time and the checkbox is checked and show the form.

Another issue is that I have 5 checkbox ID and 5 form classes and so I have 5 function doing the same thing. My question is, how can I make one function to work with 5 different ID?

So, there are two question in one:

1)How to display the form is the checkbox is checked

2)How to convert my 5 functions into one function that does show the form depending on the ID passed.

PS: I have

<script src="http://ift.tt/PI1jmv"></script> 
<script type="text/javascript" src="js/setting.js"></script>

inside <head>

Here is the HTML (NOTE: I will post only one div with one ID)

//This is the checkbox
<div class="col-sm-6">
    <div class="form-group">
      <label class="switch">

          <input name="on_off" checked type="checkbox" id="bc1"  class="switch-input on-off">

        <span class="switch-label" data-on="On" data-off="Off"></span> <span class="switch-handle"></span> 
      </label>
    </div>
  </div>

 //this is the form
<form class="form-horizontal bc-details1" method="post" action="programs-controller.php" style="display:none" role="form">

  <div class="col-sm-6">
    <div class="form-group">
      <label class="control-label" >Start Date:</label>
      <div class="input-width input-group date col-sm-10 date-picker">
          <input placeholder="MM/DD/YYYY" type="text" style="height:30px; font-size:14px" class="form-control " name="start_date" />
          <span class="input-group-addon" ><i class="glyphicon glyphicon-calendar"></i></span>
      </div>    
    </div>
</form>

setting.js

$(document).ready(function(){



$('#bc1').change(function () {

    if (this.checked) {

    $('form.bc-details1').show();

}

else {

    $('form.bc-details1').hide();

}

});



$('#bc2').change(function () {

    if (this.checked) {

    $('form.bc-details2').show();

}

else {

    $('form.bc-details2').hide();

}

});


$('#bc3').change(function () {

    if (this.checked) {

    $('form.bc-details3').show();

}

else {

    $('form.bc-details3').hide();

}

});

$('form.bc4').change(function () {


    if (this.checked) {

    $('form.bc-details4').show();

}

else {

    $('form.bc-details4').hide();

}

});

$('#bc5').change(function () {

    if (this.checked) {

    $('form.bc-details5').show();

}

else {

    $('form.bc-details5').hide();

}

});

});

EDIT: my forms are using classes and not ID...However, they have to use different id or class because they have different input and values




How to take value of checkbox and put it in array with JavaScript?

I have a situation like this:

enter image description here

What I need to do is to take values of all selected checkboxes and put them in some JavaScript array and eventually in PHP session afterwards. I have a code like this:

    while($userRow=$resultForUsers->fetch_assoc()){
          $nameOfUser=$userRow['users_name'];
          $userId=$userRow['user_facebook_id'];
          $userFBPicture=$userRow['users_picture'];
          echo "
          <tr class='tr-data-users'>
          <td class='text-center'>
          <input type='checkbox' class='checkbox' value=$userId>
          </td>
          <td class='td-users text-center'>
          <div class='input-group user-name-users'>
          <img class='user-img-users v-t' src=$userFBPicture>
          </div>
          <div class='input-group user-name-users'>
          <h5 id='no-margin'>$nameOfUser</h5>
          </div>
          <div class='input-group user-name-users'>
          <img class='v-t' src='../img/link-icon.png'>
          </div>
          </td>
          <td>
          <p class='text-center'>$userId</p>
          </td>
          <td>
          <p class='text-center'>113</p>
          </td>
          <td>
          <p class='text-center'>19</p>
          </td>
          <td>
          <p class='text-center'>19</p>
          </td>
          <td>
          <p class='text-center'>39%</p>
          </td>
          <td>
          <p class='text-center'>31.12.2013</p>
          </td>
          </tr>";
}?>

So, for each user in my database I'm generating one row, as you can see above, but value of each checkbox has user's id.

<td class='text-center'>
              <input type='checkbox' class='checkbox' value=$userId>
</td>

I haven't tried anything because I don't know from where to start. Would really appreciate your help on this.




Capture and Prevent Checkbox un/check in DataGridView from being toggled automatically

I have a datagridview with a column checkbox enter image description here

What i want is if a checkbox click (i use CellContentClick Event) I want show a messageBox that if user press ok .. then checkbox is checked and new query start. Else press Annul or Close Messagebox -> unchecked checkbox .

But i have a problem to implements..

   private void dgvApprovazione_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        try
        {

            if (dgvApprovazione.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewCheckBoxCell)
            {
                CheckBox checkboxTmp = sender as CheckBox;

                checkboxTmp.AutoCheck = false;


            }


        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

EDIT--- I haven't access to design windows. Checkbox is a dinamyc column that is result of read DB. Fields in DB is a true/false type .. In datagridview i have checkbox with check or uncheck .

I want capture and prevent autocheck in 'code-time'




retrieve data from listview by checkbox listener

The Link below show my android project named Bulk messenger

http://ift.tt/230ILxZ

thanks for help advance..




Read values of checkboxes when the value has spaces in java /servlets

I have Check boxes in my Jsp who string value is not one word i.e two or three words:

<tr>
            <td> Change Password</td>
            <td><input type="checkbox" name="admin" value="Change Password" /></td>
        </tr>
         <tr>
            <td> Add User</td>
            <td><input type="checkbox" name="admin" value="Add User" /></td>
        </tr>
        <tr>
            <td> Modify Workclass</td>
            <td><input type="checkbox" name="admin" value="Modify Workclass" /></td>
        </tr>

In my servlet I am picking the values as such:

 String[] adminresources = request.getParameterValues("admin");
if (adminresources.length > 0) {
                for (String admin : adminresources) {
                    System.out.println(admin);
                }
            }

My Output Prints only the First Work of each value i.e:

Change
Add
Modify

I do not have the liberty to change the values as they are fetched from an external database (Not displayed in my example). How do I get the full values or what is it that I am doing wrong that I am getting only the first word?




Add event to checkbox[] in wordpress plugin contact form 7

I want to add a change, click or any other event to detect when checkbox change to show a hidden field. I achieved to reproduce this demo and it's working using a dropbox, now I want to customize with a checkbox.

If I use an accept checkbox it works like a charm in this way:

[acceptance name id:name]

Creates

<input type="checkbox" id="name" value="Value">

Then

$('#name').change(function() {
    if ($("#name")[0].checked == true) {

But as long as checkbox creates an array even with one option:

[checkbox name id:name "Value"]

Creates

<input type="checkbox" name="name[]" value="Value">

When I do same does not work. I can find checked value using this ugly path:

$("#name")[0].childNodes[0].childNodes[0].checked

But change, click or other events are not present to set up...

How can I access to event in the checkbox to show hidden field when checked?




mardi 29 mars 2016

bootstrap validation for dynamically generated checkboxs is not working ..

Here I wrote bootstrap validation for selecting at least 1 checkbox which is generated dynamically its applicale for only first checkbox, for other checkbox its does not work. plz give me solution.

      <div class="user-all-services-info">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="control-label">Select Services</label><br>
                                        <c:if test="${!empty servicesList}">
                                            <c:forEach items="${servicesList}" var="services">
                                                <!-- <div class="select-service-option">  -->
                                                <%-- <input type="checkbox" name="servicesId" value="${services.scServiceMstId }" style="margin-left: 10px;margin-top: 7px;">${services.serviceName } --%>

                                                <c:set var="id" scope="page" value="0"></c:set>
                                                <c:choose>
                                                    <c:when test="${!empty serviceMapperList}">
                                                        <c:forEach items="${serviceMapperList}"
                                                            var="serviceMapperList">
                                                            <c:if
                                                                test="${services.scServiceMstId == serviceMapperList[0]}">
                                                                <c:set var="id" value="1"></c:set>
                                                            </c:if>
                                                        </c:forEach>

                                                        <c:choose>
                                                            <c:when test="${id eq 1}">
                                                                <div class="checkbox">
                                                                    <label> <%-- <input type="checkbox"  name="servicesId"  value="${services.scServiceMstId}" style="margin-left: 10px;margin-top: 7px;">&nbsp;${services.serviceName } --%>
                                                                        <input type="checkbox" name="servicesId"
                                                                        value="${services.scServiceMstId}">&nbsp;${services.serviceName }
                                                                    </label>
                                                                </div>

                                                            </c:when>
                                                        </c:choose>

                                                    </c:when>

                                                </c:choose>
                                                <!-- </div>  -->
                                            </c:forEach>
                                        </c:if>
                                    </div>
                                </div>
                            </div>
                        </div>

Above is the code for craeting checkbox dynamically. Its validation code is given below.

        servicesId:{

                                                    validators: {

                                                          notEmpty: {
                                                           message: 'Please select at least 1 service.'
                                                         } 
                                                       /*  choice: {
                                                           min: 1,
                                                            max: 2,
                                                           message: 'Please select at least 1 service.'
                                                       }  */
                                                   }

                                                },




Toggle checkboxes with jQuery

I have a form with a random number of checkboxes. I' trying to toggle them on/off via jquery when the top one is checked/un-checked BUT skip any checkboxes that are disabled. The first checkbox has an id of "select_all" and the jquery is shown below. This works fine the FIRST time, but all subsequent attempts fail. I don't see any errors in Chrome's console. Any ideas? I don't care if I use this code or something else.

<script>
    $('#select_all').click(function() {
        var c = this.checked;
        if(c == true){
            $('input:checkbox:not(:disabled)').attr('checked','checked');
        } else {
            $('input:checkbox:not(:disabled)').removeAttr('checked');
        }
    });
</script>




NSIS installer nsDialog checkbox not appearing as I think it should

I'm adding a custom page to an NSIS installer and I'm having trouble adding a checkbox. All the examples I've seen look the same, which is what I'm doing, but I can't see what could be wrong. (I've only been using NSIS for an hour or so!).

!include MUI2.nsh
!include WordFunc.nsh
!insertmacro VersionCompare
!include LogicLib.nsh
!include InstallOptions.nsh
!include nsDialogs.nsh

Name "xxxxx"
;!define MUI_ICON "bcs.ico"
;!define MUI_HEADERIMAGE
;!define MUI_HEADERIMAGE_BITMAP "bcs.bmp"
;!define MUI_WELCOMEFINISHPAGE_BITMAP "bcs164.bmp"
;!define MUI_HEADERIMAGE_RIGHT

OutFile "nqcs_setup.exe"
InstallDir "$PROGRAMFILES\xxxx"
InstallDirRegKey HKLM "Software\xxxx" "InstallDir"
RequestExecutionLevel admin

Var Dialog
Var Heading
Var ServiceQuestion
Var SvcCheckBox

Function installOptionsPage

    nsDialogs::Create 1018
    Pop $Dialog

    ${If} $Dialog == error
        Abort
    ${EndIf}

    ${NSD_CreateLabel} 0 0 100% 50 "Installation Options"
    Pop $Heading
    CreateFont $0 "$(^Font)" "14" "500"
    SendMessage $Heading ${WM_SETFONT} $0 1

    ${NSD_CreateLabel} 0 50 100% 20 "Would you like to install as a service?"
    Pop $ServiceQuestion
    CreateFont $0 "$(^Font)" 11
    SendMessage $ServiceQuestion ${WM_SETFONT} $0 1

    ${NSD_CreateCheckbox} 50 50 100% 15 "Checkbox Test"
    Pop $SvcCheckBox
    ;GetFunctionAddress $0 OnCheckbox
    nsDialogs::OnClick $SvcCheckBox $0

    nsDialogs::Show

FunctionEnd

When the page appears the check box isn't there:

nsis nsdialog check box problem




How to get a list of checked boxes in grails

In grails, I am trying to get a list of checked check boxes. I have the list of check boxes, but my issues are two:

1) when I click on a single item in the list and click submit - I only get the value "on". If I click more than one check box item, I get something like this:

[Ljava.lang.String;@5a37f9f7

2). I do not get a list or the name of the item checked.

Here is my code for the check boxes in the gsp:

<g:form action="submitForm">
    <ul class="columns3">
        <g:each in="${name}" var="fileName" >
            <g:checkBox value="${false}" name="${ 'fileName'}" /> ${fileName.replaceFirst(~/\.[^\.]+$/, '')}<br>
        </g:each> 
    </ul>
    <br>
    <br>
    <g:submitButton name="Submit"/>
</g:form>   

and here is the controller code (groovy):

class Read_dirController {

    def index() { 

        def list = []

        def dir = new File("/home/ironmantis/Documents/business/test_files")
        dir.eachFileRecurse (FileType.FILES) { file ->
          list << file
        }

        list.each {
            println it.name.replaceFirst(~/\.[^\.]+$/, '')
          }

        render(view: "index",  model: [name:list.name])

        params.list('fileName')

    }

        def displayForm() { }

        def submitForm(String fileName) {
            render fileName
            //render(view: "tests_checked", fileName)
        }
}

I tried to bind an id to the check boxes, but I keep getting an exception error.

Any help you can give I truly appreciate it; I am new to grails.

ironmantis7x




Redirect to different pages based on which combination of checkboxes are checked

First, I've found a bunch of answers here that address individual aspects of my issue, but, for the life of me, I can't wrap my head around stitching them all together to function how I need them to.

Basically, I've got a single form with two groups of checkboxes -- the first containing 12 fruits (apples, oranges, kiwis, blueberries, etc) and the second containing 9 colors (red, yellow, blue, green, etc).

There are several combinations a user can create, but I'm only interested in whether a user selects 'apples' from the first group and/or 'red' or 'green' from the second group. There are three different landing pages that a user can reach based on their selections:

  • Users that select 'apples' from the first group AND ALSO 'red' AND/OR 'green' from the second group get redirected to page1a.html
  • Users that select ANYTHING BUT 'apples' from the first group AND ALSO select 'red' AND/OR 'green' from the second group get redirected to page1b.html
  • Users that select ANYTHING BUT 'apples' OR 'red' OR 'green' are redirected to page1c.html

I think I understand how to check to see if a single checkbox is checked:

var isChecked = $('input[name="apples"]:checked').length > 0;

I've given the 'apples,' 'red' and 'green' checkboxes unique classes and names so that I can target them:

<input type="checkbox" class="apples" name="apples" value="apples" />
<input type="checkbox" class="red" name="red" value="red" />
<input type="checkbox" class="green" name="green" value="green" />
etc.

I more or less know how to redirect the user to a location. What's beyond my capability is how to handle these combination scenarios.

Has anyone done something like this using js and care to share your knowledge? Thanks in advance!




is possible allow a user to select only one checkbox (bootstrap checkbox-x)?

I'm working with bootstrap checkbox-x plugin : http://ift.tt/1MvkvMq

How can I only allow a user to select only one checkbox?

Option 1
          <div class="col-md-12 has-success bottom-10 no-padding-left">
              <input class="form-control bottom-15" id="check-2" type="checkbox" data-toggle="checkbox-x" data-size="sm" data-three-state="false">
              <label class="cbx-label" for="check-2">Option 2 </label>
          </div>

          <div class="col-md-12 has-success bottom-10 no-padding-left">
              <input class="form-control bottom-15" id="check-3" type="checkbox"  data-toggle="checkbox-x" data-size="sm" data-three-state="false">
              <label class="cbx-label" for="check-3">Option 3 </label>
          </div>

Thanks!




How to capture values of checkboxes using Viewstate

I have 2 checkboxes, one is called the approve and the other one reject. The purpose of each of the checkboxes is: 1. When the Approve checkbox is checked the comments need to be filled in and same is the case with the Reject checkbox. (These comments are saved in a History grid on the same page) 2. When both approve and reject have been unchecked: (this is the case when the user decides to change his/her mind and unchecks the approve checkbox and save, then the approve should delete all the previous approve comments and upon selecting the reject option, it should delete the last updated reject comments only. I have the logic for both of them and they work fine individually, but when both of them are used at the same time, only reject unchecked option works. Please note that, Oracle database is used for backend. Here's the code:

On page_load:

if (!this.cbReturn.Checked && !this.cbApproved.Checked)
                {
                    ViewState["Return"] = null;
                    ViewState["Approve"] = null;
                }

On approve_checkchanged

ViewState["Approve"] = cbApproved.ToString();

On Submit_click

for approve uncheck:

 if (!this.cbReturn.Checked && !this.cbApproved.Checked)
                    {
                         cReporter_Review = "N";

                        string tRow = "";
                        if (ViewState["Approve"] != null)
                            tRow = ViewState["Approve"].ToString();
                        else
                            tRow = this.radTBAcceptComments.Text;

                        DbServices dbService = new DbServices();

                        string connectionString = dbService.Connection.ConnectionString;

                        string querystring = "Delete from HSIP.FY_ST_QUESTION_COMMENTS_INFO q where q.state_code = " + strStateCode + " and q.record_type='Y' and q.display_number= " + numDisplayNumber + " and q.FY='2015'";



                        using (OracleConnection connection = new OracleConnection(connectionString))
                        {
                            using (OracleCommand command = new OracleCommand(querystring, connection))
                            {

                                connection.Open();

                                DataSet ds = dbService.GetDataSet(querystring, CmdType.SQL);
                                connection.Close();
                            }
                        }

                          btnNextQue_Click(this, new EventArgs());

                    }

Please let me know if I have to add anything else to the viewstate. I have approve query only, for reject it works, so I didn't post the code. Please let me know the condition which needs to be added so that on approve check changed (when unchecked and also reject unchecked) it should enter into this part of the logic currently the breakpoint doesn't hit through the above logic for approve. Please help me with the condition.

Thanks, Dimpy




Change select to check boxes using javascript

The reason I would like to do this, is that it will be situational. If a user is logged in, they will see drop downs. If not, they will see a list of text. Ideally just plain text, but I don't know if that's possible, so I was thinking I could convert the < select > to checkboxes and hide the check boxes with CSS.

Basically we don't want a user who isn't logged in to feel they can select anything, because they won't be able to order and this could lead to frustration. But we would still like them to view what options are available for each product as unselectable text. If there is a better way to do this than what I'm thinking, I'd be grateful for suggestions. For now, this is what I've patched together, but it's not changing the select to checkboxes.

I grabbed some code from here to use as a starting point: http://ift.tt/1nwavY7

Also, I can't grab the < select > by id, because this will be on all < select >'s.

<select id="unique_id" class="unique_class"  data-attribute_name="unique_attribute_name" name="unique_name">
    <option value="" selected="selected">Choose an option</option>
    <option class="attached enabled" value="516">5/16"</option>
    <option class="attached enabled" value="38">3/8"</option>
</select>

Javascript:

function myFunction() {
    document.getElementsByTagName("SELECT")[0].setAttribute("type", "checkbox"); 
}

Here is a fiddle: http://ift.tt/1LXi7Sy




checkbox form field name is not submitted when form submits knockout js

I am trying to get the all form fields when user submits the form, the problem is with checkbox field that is when the checkbox is checked the name is submit to server but if this is unchecked then the checkbox is not submit to server, I am using knockout latest version Here is my working code:

<form data-bind="submit: submitForm">
    <input type="checkbox" name="checkboxTest" data-bind="checked : value" />
    <input type="text" name="textTest" value="Test" />
    <button type="submit"> Submit</button>
</form>

And here is my ViewModel:

function viewModel(data)
    {
        self.value = ko.observable(true);
        // when user submit the form
        self.submitForm =  function(fields)
        {
            var dataparams = $(fields).serialize();
            // The form fields name are showing here
            console.log(dataparams);
        }
    }
    ko.applyBindings(new viewModel);

Could anyone tell me how to get the checkbox even if that is unchecked using knockoutjs, thank you in advance.




form_checkbox() cannot input text between produced tag

im using form_helper to create my checkboxes.

<?php echo form_checkbox('test','test'); echo "test"; ?>

i always print it below the checkbox, and the code producing :

<input type="checkbox" name="test" value="test"></input>test

how can i make it so it looks like this :

<input type="checkbox" name="test" value="test">test</input>

or atleast make it so the text "test" is printed beside the checkbox, not in newline




Creating facet checkbox in Symfony with solr

I made a fulltext search, where I can search users for now. I want to build a facet with an checkbox for choosing results. Is there any example how I can do faceted search.

My searchController look like this:

<?php

namespace User\SearchBundle\Controller;


use User\DocumentBundle\Entity\DocumentRepository;
use User\SearchBundle\Helper\Array;
use User\SearchBundle\Helper\User;
use User\UserBundle\Entity\Role;
use User\UserBundle\Entity\RoleRepository;
use User\UserBundle\Entity\User;
use User\UserBundle\Entity\UserRepository;
use Symfony\Bundle\FrameworkBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\Request;


class DefaultController extends BaseController
{

/**
 * @param Request $request
 * @return string
 */
public function searchAction(Request $request)
{
    /** @var \User\SearchBundle\Service\SearchService $service */
    $service = $this->container->get('solr_search');

    $postfixs = [User::POSTFIX => "User"];

    /** get document structure */
    $documentOverall = array_merge(User::$document);

    /** get solr alias document structure */
    $documentAlias = Array::getSolrAlias($documentOverall);
    $searchQuery = "";
    $sources = [];


    $formData = $request->query->all();
    if (!empty($formData['search'])) {
        $searchQuery = trim($formData['search']);
        $searchQuery = strtolower($searchQuery);
    }

    $query = " ";
    $documents = [];

    /** build solr query */
    $query .= " ( {$documentAlias["title"]}:*{$searchQuery}*)";
    $resultSolr = $service->findInIndex($query);

    foreach ($postfixs as $documentPf => $name) {
        foreach ($resultSolr as $doc) {
            if ($documentPf == $doc["document"]) {
                $ids[$documentPf][] = $doc["id"];
            }
        }
    }


    $userResult = [];
    if (!empty($ids[User::POSTFIX])) {
        /** @var UserRepository $repoUser */
        $repoUser = $this->getDoctrine()->getRepository("UserBundle:User");
        $users = $repoUser->getByIds($ids[User::POSTFIX]);



        /** @var \User\UserBundle\Entity\User $user */
        foreach ($users as $user) {
            $userName = [];

            $fullName = $user->getFullName();
            if (!empty($fullName)) {
                $userName[] = "Name: " . $user->getFullName();
            }




            $userResult[$user->getId()] = [
                "userName" => substr(implode(", ", $userName), 0, 200),
            ];


        }
    }

    $resultArray = [];
    foreach ($resultSolr as $solr) {
        switch ($solr["document"]) {

          case UserHelper::POSTFIX:
              if (!empty($userResult[$solr["id"]])) {
                  $userResult[$solr["id"]]["score"] = $solr["score"];
                  $resultArray[] = $userResult[$solr["id"]];
              }
              break;
        }
    }

    return $this->render('SearchBundle:Default:searchResult.html.twig', array(
        'resultArray' => $resultArray,
        'searchQuery' => $searchQuery,
        'linkParam' => $this->generateUrl('searchBundle_searchResultPage', $formData),
        'menu' => Array('top' => 'Search'),
    ));
}

}

I would be thankful if there is any example how to create facet checkbox and how to build a facet query.

Thank you!




I need help showing and hiding data based on a checkbox.

Alright so I have a form... in the form I have a lot of check boxes... if a person clicks on the checkbox... it shows the field below the box... if they click on the checkbox again it makes the field below the checkbox disappear and makes the field have no value...

here is the code... I have JS running the show and hide. and Html calling it.

function ShowCutSewDescription() {
var select = $('#send_item_to_cutsew');
console.log(select)
//select = parseInt(select);
if (select.attr('checked', true)) {
    $('#cutsew-checked').show();
}
else {
    $('#cutsew-checked').hide();
}

}

<div class="form-group">
<label class="col-md-3 control-label">Sending item to Cut/Sew Manager</label>
<div class="col-md-9">
    <input type="checkbox" name="send_item_to_cutsew" class="form-control input-inline input-medium" placeholder="Enter text" onchange="ShowCutSewDescription()">
</div>




Exception when trying to SaveChanges with Entity Framework

I am building an MVVM WPF app in Visual Studio 2015 using Entity Framework 6. The app has a view with a few checkbox:

<TextBlock Grid.Row="0"
           Grid.Column="0"
           Style="{StaticResource FieldLabel}"
           Text="Inactive" />
<CheckBox Grid.Row="0"
          Grid.Column="1"
          IsChecked="{Binding IsSelectedEmployeeInActive,
                              Mode=TwoWay}" />
<TextBlock Grid.Row="1"
           Grid.Column="0"
           Style="{StaticResource FieldLabel}"
           Text="Leave of Absence" />
<CheckBox Grid.Row="1"
          Grid.Column="1"
          IsChecked="{Binding IsSelectedEmployeeLoa,
                              Mode=TwoWay}" />
<TextBlock Grid.Row="2"
           Grid.Column="0"
           Style="{StaticResource FieldLabel}"
           Text="Archived" />
<CheckBox Grid.Row="2"
          Grid.Column="1"
          IsChecked="{Binding IsSelectedEmployeeArchived,
                              Mode=TwoWay}" />

Each of these checkboxes is bound to a property, such as the following:

public bool IsSelectedEmployeeInActive
{
    get { return _isSelectedEmployeeInActive; }
    set
    {
        if (_isSelectedEmployeeInActive == value) return;

        _isSelectedEmployeeInActive = value;

        if (value)
        {
            var count = SelectedEmployee.EmployeeStatus.Count(x => x.validEmployeeStatusID.Equals(2));
            if (count.Equals(0))
            {
                SelectedEmployee.EmployeeStatus.Add(new EmployeeStatu
                {
                    employeeID = SelectedEmployee.employeeID,
                    validEmployeeStatusID = 2,
                    exitDate = DateTime.Now,
                    createdDate = DateTime.Now
                });
            }
        }
        else
        {
            var itemToRemove = SelectedEmployee.EmployeeStatus.Single(x => x.validEmployeeStatusID.Equals(2));
            Context.Entry(itemToRemove).State = EntityState.Deleted;
            SelectedEmployee.EmployeeStatus.Remove(itemToRemove);
        }
        RaisePropertyChanged(() => IsSelectedEmployeeInActive);
    }
}

The SelectedEmployee property gets set when the user clicks a row on a DataGrid. In the view model's constructor, the app has an event handler for changes to SelectedEmployee:

this.PropertyChanged += (o, e) =>
{
    if (e.PropertyName == nameof(this.SelectedEmployee))
    {
        IsSelectedEmployeeLoa = (SelectedEmployee.EmployeeStatus
                .Count(x => x.validEmployeeStatusID.Equals(2)) > 0);
        IsSelectedEmployeeArchived = (SelectedEmployee.EmployeeStatus
                .Count(x => x.validEmployeeStatusID.Equals(5)) > 0);
        IsSelectedEmployeeInActive = (SelectedEmployee.EmployeeStatus
                .Count(x => x.validEmployeeStatusID.Equals(4)) > 0);
    }
};

When the user clicks the Save button, it calls the following via a RelayCommand:

public void SaveEmployees()
{
    Context.SaveChanges();
}

If I change the CheckBox controls a few times between checked and unchecked and click Save, the app blows up with this exception on the Context.SaveChanges() line above:

{"Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://ift.tt/1yZ9b1v for information on understanding and handling optimistic concurrency exceptions."}

If I comment out the code in the event handler for SelectedEmployee that sets the checkbox properties, the error goes away; but then I'm not able to set the CheckBox properties to their initial values from the database.

How should I resolve this issue? Thanks.




check box not working with datatable.js pagination's second page

I am using datatable.js for pagination:

When I check a checkbox inside table row, I have to show Lock/Delete buttons which are out side the table. For this I have Done Below jQuery Code:

 $(document).ready(function () {      

    $('#tblID :input[type="checkbox"]').on('click',function () {
        var checkedBoxes = $('#tblID:input[type="checkbox"]:checked').length;

        if (checkedBoxes > 0) {
            alert(checkedBoxes);
            $("#lnkLock").show();
            $("#lnkDelete").show();

        }
        else {
            alert(checkedBoxes);
            $("#lnkLock").hide();
            $("#lnkDelete").hide();
        }
    });
 });

It is working Only on The First Page of table.When I navigate to second page of datatable /Table it stops working(Buttons (lock/delete)) are not shown.

On second, third...pages checkbox click event is also not fired.

How can I do it on other pages?




Change checkbox state to not checked when other checkbox is checked pyqt

I'm using Qt Designer and pyqt code to write an app.

I have a very simple question: in my UI I have 2 checkboxes and what I need is to set the first checkbox as always unchecked when the second checkbox is unchecked.

In other words the first checkbox can be checked only when the second checkbox is checked, but the second checkbox can be checked also if the first one is not checked.

In Qt Designer I have not find an easy way to do that with the Signals/Slots function.

I had a look in the Qt API and I tried to write some code:

class CreateRIVLayerDialog(QDialog, FORM_CLASS):
    def __init__(self, iface)

    # some more code here...

    if self.addCheckDB.isChecked():
        self.addCheck.setChecked(False)

but without results.

Does anybody have some hints?

Thanks




Send unchecked checkbox value through ajax

I have a complex problem due to the generic function I wrote to save form data in mySQL. All forms are send through ajax after being serialized:

$('.suggestSave, .buttonSave').on('submit', function(e) {
        e.preventDefault();
        var data = $(this).serialize();
        ...

I'm then fetching all POST values by looping through the values and creating the data saved in the database:

        $data = array();

        foreach ($_POST as $param_name => $param_val) {
          if($param_name != 'action' && $param_name != 'patient' && $param_name != 'jsaction') {
            $name = sanitize($param_name);
            $value = sanitize($param_val);
            $data[$name] = $value;
          }
        }

Naturally, an unchecked checkbox won't be sent through. The problem being that if it's empty, I'd like to store the Int value 0 instead of 1 for this checkbox.

On the HTML side, I have a classic syntax

<input type="checkbox" value="1" name="c_name1" checked/>
<input type="checkbox" value="1" name="c_name2"/>

Any suggestions on how to deal with that problem ? In a one-checkbox-situation, I would check if the post value isset(), but since I'm getting the names and values by looping through... I'm out of ideas...




lundi 28 mars 2016

ionicons replace checkbox and radion buttons with icons

I am using Ionicons on a project and have replaced the standard images for radio and checkbox with these icons.The issue I have is the actual default items are showing through the Ionicons when rendered.

I have the following HTML:

<input type="checkbox"
       name="client{!!  $client->uuid !!}"
       class="checkbox-icon ion-android-checkbox-outline-blank" checked>

I also have the following CSS:

.checkbox-icon:before,
.radio-icon:before {
  visibility: visible;
  font-size: 20px;
}

.checkbox-icon.ion-android-checkbox-outline-blank:checked:before {
  content: "\f374";     // icon for selected
  font-size: 20px;
  color: $brand-primary;
}

.radio-icon.ion-ios-circle-outline:checked:before {
  content: "\f120";     // icon for selected
  font-size: 20px;
  color: $brand-primary;
}

input[type=checkbox].checkbox-icon.ion-android-checkbox-blank,
input[type=radio].radio-icon.ion-record {
  visibility: hidden;
}

But although the checkboxes/radio buttons behave correctly, I can see the standard item below the ionicon. Is this due to the icon having a transparent background?

I tried changing opacity to 100% but it did not help.




How to create a series of checkboxes in HTML with PHP searching a MySQL database?

I want to create a series of checkboxes that the user can check off if they completed exercises that they have said that they have scheduled. So, for example, if a user of a website I am creating says that they will do a bench press and they schedule it, then it will appear in the schedule table in MySQL. But, after the date that they said they would complete the exercise passes, they will be alerted in PHP about the exercises to ask them if they really did complete it. If the user checks that they did complete the exercise, they check the box and the exercise will appear in their activity table in MySQL. If the user does not check the box, then the exercise will then go from being pending to being canceled.

My main problem is that I am just not sure how to create these series of checkboxes based on the exercises that the user has scheduled after the date has passed. I do not know how to create checkboxes without creating an arbitrary amount of them from the start.

Let's say the user said they would do a bench press on the date 01/01/2000 and the date has now passed. I have a date function in PHP that will only show the message if the date has passed. Here is the date function and what is followed is the if statement to check to see if the date is greater than or equal to the day variable from the table:

echo "Today is " . date("m/d/Y") . '<br>';
if(date("m/d/Y") <= 'day') {
echo "You have pending exercises: ";

and so on. But when I create checkboxes, I want them to only show up if the user has exercises, not just create a set number of them. So, if the user has 3 exercises that are pending, I want just 3 checkboxes for the user to click if they completed each exercise then click submit. If the user did not click any of them, they will appear in the schedule table as canceled via an SQL statement.

I have this just as a test statement, but it seems a bit convoluted at the moment:

if(empty($_POST['exercise1'])) {
    if(empty($_POST['exercise2'])) {
        if(empty($_POST['exercise3'])) {
            echo "Checkbox was left unchecked.";
        } else {
            echo "Checkbox was checked.";
        }
    }
}

Is there any way I can create a set number of checkboxes equal to the number of exercises that are in the schedule table and when the user clicks or does not click on them, they appear in the schedule table as either completed or canceled in PHP/SQL and HTML?

Sorry, I know this is a lot of information, but any tips would be appreciated. Thank you.




Telerik RADListBox with CheckBox - How to trigger a checked item in checkbox to call its RADListBox SelectedValue event

I am having a UI problem with RadListBox and checking items in a Checkbox. The issue is that my selection in the checkbox wont trigger an event since its the selection in the RADListBox that triggers it. And the user needs to check the Checkbox and then select (click) the item in the radlistbox to trigger the SelectedValue event of it. I would like to have it so that when the user checks a checkbox the Selectedvalue event of the RadListBox gets called too. Here is my WPF code:

<telerik:RadListBox  Grid.Row="1" x:Name="ExportersList" ItemsSource="{Binding Exporters}" Style="{StaticResource ModalListBoxStyle}"
           Visibility="{Binding ExportComplete, Converter={StaticResource InverseBoolToVisibilityConverter}}"
           SelectedValue="{Binding ExportFormatName, Mode=TwoWay}" SelectedValuePath="Name" SelectionMode="Multiple">
            <telerik:RadListBox.ItemTemplate>
                <DataTemplate DataType="{x:Type interfaces:BaseTourSheetExporterType}">
                    <StackPanel Orientation="Horizontal">
                        <CheckBox IsChecked="{Binding IsExporterChecked}" />
                        <TextBlock Text="{Binding Name}"  Margin="5" />
                    </StackPanel>
                </DataTemplate>
            </telerik:RadListBox.ItemTemplate>
        </telerik:RadListBox>

Please note that the event SelectedValue is bound to a property in my class and when it gets/sets I am enabling/disabling another button. I don't know how to get my Checkbox IsChecked event (when a user checks or unchecks the checkbox) to trigger the selectedvalue event of the radlistbox and basically allowing my user to just check/uncheck a Checkbox that triggers another get/set property (ExportFormatName). So this way the user can do it without selecting the item again in the radlistbox (clicking outside the checkbox) to trigger that get/set property event. Please help me with this WPF part.

Just to note aside of this, I'm purposely binding the CheckBox IsChecked to a class called BaseTourSheetExporterType that is holding a member Boolean value (IsExporterChecked). This determines whether its been checked or not (this class and member is required to remember my changes for when I'm re-opening the window).




save in one class load in another in java

currently i'm working on a app where i can save numbers in a database in one class and load in another class. i get the numbers by checking a checkbox and add them to an arrayList. now my problem. for example when i checked number 1 and number 2 and save it it works fine. only when i uncheck number 1 and number 2 and check number 3 and number 4 and then save it number 1 and 2 are still there. can somebody tell me what i am doing wrong.

if you need the code of the checkboxes please say it and i will add it.

save part

protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.preference_dart_throw_page);
        final Intent preferenceDartThrowPageOpened = getIntent();
        String previousActivity = preferenceDartThrowPageOpened.getExtras().getString("Pref");
        loadSingle = (Button) findViewById(R.id.savePreferenceTriple);

        save = (Button) findViewById(R.id.savePreferenceSingle);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Message = Practise.selectionSingle.toString();
                try {
                    FileOutputStream fou = openFileOutput("singleArrayNumbers.txt", MODE_WORLD_READABLE);
                    OutputStreamWriter osw = new OutputStreamWriter(fou);
                    try {

                        osw.write(Message);
                        osw.flush();
                        osw.close();
                        Toast.makeText(getBaseContext(), "Data Saved", Toast.LENGTH_SHORT).show();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                } catch (FileNotFoundException e) {

                    e.printStackTrace();
                }
            }
        }); 
}

load part

public class Practise extends AppCompatActivity{

Button save;
int data_block = 100;
static ArrayList<Integer> selectionSingle = new ArrayList<Integer>();
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.practise_page);

        Intent practisePageOpened = getIntent();
        String previousActivity = practisePageOpened.getExtras().getString("Practise");
            loadSingle = (Button) findViewById(R.id.buttonSingle);
       loadSingle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    FileInputStream fis = openFileInput("singleArrayNumbers.txt");
                    InputStreamReader isr = new InputStreamReader(fis);
                    char[] data = new char[data_block];
                    String final_data = "";
                    int size;
                    try {
                        while ((size = isr.read(data)) > 0) {
                            String read_data = String.copyValueOf(data, 0, size);
                            final_data += read_data;
                            data = new char[data_block];
                        }

                        String csv = final_data.replaceAll("\\[", "").replaceAll("\\]","").replaceAll(" ","");
                        String[] numbers = csv.split(",");
                        // Toast.makeText(getBaseContext(), "Message : " + final_data, Toast.LENGTH_SHORT).show();
                        Random doubleNumberRandom = new Random();
                        String number = numbers[doubleNumberRandom.nextInt(numbers.length)];
                        TextView myText = (TextView) findViewById(R.id.randomNumberDisplay);
                        if(number == ""){
                            Toast.makeText(Practise.this, "empty", Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(Practise.this, "numbers :" + final_data, Toast.LENGTH_SHORT).show();
                            myText.setText("D" + number);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });
}




How to makeStreamReader/Writer with check boxes to Save the Selected items and open the Selected items

My program is supposed to be able to allow the user to be able to select a flavor of icecreame and syrup using (comboboxes) and selecting the three check boxes if they want nuts, cherries or sprinkles. WHICH IS WORKING TO THE BEST OF MY KNOWLEGE

the Other part of the Program is supposed to allow the user to save there order and open it later using StreamReader/Writer (WHICH ISNT WORKING REALLY WELL I CANT GET IT TO WRITE DOWN WHAT IS SELECTED OUT OF BOTH COMBO BOXES AND CHECK BOXES DONT WRITE EITHER. SAMETHING WITH THE OPEN IT ONLY OPENS IF I CHANGE THE INDEX NUMBER AFTER THE EQUALS)

private void saveToolStripMenuItem_Click(object sender, EventArgs e)
   //THIS IS MY SAVE BUTTON USING STREAMWRITER
//flavorBox is the Name of the comboBox that holds 3 flavors of iceCream
//syrupBox is the name of the comboBox that holds 3 syrupFlavors inside the combobox
// my check boxes for the toppings are the IF else if else statments
    {
        SaveFileDialog sfd = new SaveFileDialog();

        if (sfd.ShowDialog() == DialogResult.OK)
        {
            StreamWriter sw = new StreamWriter(
                                            new FileStream(sfd.FileName,
                                                            FileMode.Create,
                                                            FileAccess.Write)
                                                            );
            if (!String.IsNullOrEmpty(syrupBox.Text))
            {
                sw.WriteLine(flavorBox.SelectedItem);
            }

           else if (!String.IsNullOrEmpty(syrupBox.Text))
            {
                sw.WriteLine(flavorBox.SelectedItem);
            }

           else if (Nuts.Checked)
            {
                this.Tag = "checked";
                sw.WriteLine(Nuts);


            }
            else if (Cherries.Checked)
            {
                this.Tag = "checked";
                sw.WriteLine(Cherries);

            }
           else if(Sprinkles.Checked)
            {
                this.Tag = "checked";
                sw.WriteLine(Sprinkles);

            }
            sw.Close();
        }


    }

private void openToolStripMenuItem_Click(object sender, EventArgs e)
//THIS IS MY OPEN METHOD WHERE IT IS SUPPOSED TO DISPLAY EVERYTHING THAT USE SAVED
    {
        OpenFileDialog ots = new OpenFileDialog();

        if (ots.ShowDialog() == DialogResult.OK)
        {
            StreamReader sr = new StreamReader(
                                            new FileStream(ots.FileName,
                                            FileMode.Open,
                                            FileAccess.ReadWrite)
                                            );
            String items;
// I tried coping my if else if statements for the save streamREader thinking that would work  it doesn't DUH. I'm out of IDEAS for this COULD USE SOME HELP WITH THIS
            while (!sr.EndOfStream)
            {
                items = sr.ReadLine();
                flavorBox.Items.Add(items);
                syrupBox.Items.Add(items);

                 if (Nuts.Checked)
                {
                    this.Tag = "checked";
              sw.WriteLine(Nuts);


                }
                else if (Cherries.Checked)
                {
                    this.Tag = "checked";
                 sw.WriteLine(Cherries);

                }
                else if (Sprinkles.Checked)
                {
                    this.Tag = "checked";


                }

            }
            flavorBox.SelectedIndex = 1;
            syrupBox.SelectedIndex = 1;

            sr.Close();
        }
    }




Check/uncheck a checkbox in the table row when any checkbox in the same row is clicked

I have a simple table as following which has checkboxes in the first and last columns of each row.

<table style="width:100%">
  <tr>
    <td><input type="checkbox" /></td>
    <td>Smith</td> 
    <td><input type="checkbox" /></td>
  </tr>
  <tr>
    <td><input type="checkbox" /></td>
    <td>Jackson</td> 
    <td><input type="checkbox" /></td>
  </tr>
</table>

Problem: When I check/uncheck the last column's checkbox in the first row, the first column's checkbox in the same row should be checked/unchecked. Similarly, if the check/uncheck the first column's checkbox, the corresponding last column checkbox should be checked/unchecked.

How can I achieve this in javascript? Any help or pointers would be really appreciated.

Thank you.




Update Entity Framework navigation property ICollection items

I'm using Entity Framework 6 in Visual Studio 2015 to build an MVVM Light WPF app. I need to bind a navigation property ICollection to some CheckBox controls. An Employee can have 0 to at most 3 EmployeeStatus entities, with employeeID serving as the key on the EmployeeStatus entity; EmployeeStatus in turn has a foreign key on the EmployeeStatusDescription table of employeeStatusID. The EmployeeStatusDescription provides the description of the status code (such as "Archived", "Inactive", "Leave of Absence"). Each EmployeeStatus corresponds to one EmployeeStatusDescription.

EmployeeStatus is defined this way in the Employee class:

public virtual ICollection<EmployeeStatu> EmployeeStatus { get; set; }

EmployeeStatusDescription is defined in the EmployeeStatus class as:

public virtual EmployeeStatusDescription EmployeeStatusDescription { get; set; }

I'd like to show 3 CheckBox controls and bind each to the value from the EmployeeStatus ICollection values. For example, if an employee does not have status "Inactive" and the user checks that, I need to add that to the EmployeeStatus collection; if the user unchecks that item, I'd like to have it removed from the EmployeeStatus collection.

I've created the following StackPanel to hold the checkboxes; they're bound to properties on my view model:

<StackPanel Grid.Row="12"
            Grid.Column="1"
            Orientation="Vertical">
    <StackPanel Orientation="Horizontal">
        <TextBlock HorizontalAlignment="Left"
                   VerticalAlignment="Top"
                   Text="Inactive" />
        <CheckBox IsChecked="{Binding IsSelectedEmployeeInActive}" />
    </StackPanel>
    <StackPanel Orientation="Horizontal">
        <TextBlock HorizontalAlignment="Left"
                   VerticalAlignment="Top"
                   Text="Leave of Absence" />
        <CheckBox IsChecked="{Binding IsSelectedEmployeeLoa}" />
    </StackPanel>
    <StackPanel Orientation="Horizontal">
        <TextBlock HorizontalAlignment="Left"
                   VerticalAlignment="Top"
                   Text="Archived" />
        <CheckBox IsChecked="{Binding IsSelectedEmployeeArchived}" />
    </StackPanel>                                    
</StackPanel>

Here's an example property bound to one of the CheckBox controls' IsChecked dependency property:

private bool _isSelectedEmployeeInActive;

public bool IsSelectedEmployeeInActive
{
    get { return _isSelectedEmployeeInActive; }
    set
    {
        if (_isSelectedEmployeeInActive == value) return;

        _isSelectedEmployeeInActive = value;
        RaisePropertyChanged(() => IsSelectedEmployeeInActive);
    }
}   

I'm doing a search to get the entity collection:

var query = (from e in Context.Employees
             .Include("EmployeeStatus.EmployeeStatusDescription")
             .Where(comparison)
             select e);

SearchResults = new ObservableCollection<Employee>(query);




Contact Form 7: How to make 4 checkboxes in 1 ques a required field?

I have Wordpress Contact Form 7 Plug-in on my site. Need 4 checkboxes in 1 question to be a required field. As long as user ticks at least 1 checkbox, then the message will be sent successfully. Below will be the questions:

Which brand appeals to you?
[checkbox] cho [checkbox] ogpo
[checkbox] lho [checkbox] aico

Btw I can't group the checkbox together: (e.g)[checkbox* your-fruit exclusive "Apple" "Banana" "Grape"] because I need them separately for messaging syntax and styling purposes.

Below are the code that does not work:

<div class="col-lg-10 col-lg-offset-1 footer_cheakbox required"
style="margin-left:55px"> 

<div class="form-group col-xs-6 col-md-6
 marg_b" id="CH"> [checkbox  cho   id:ch  exclusive "cho" ] </div>

<div class="form-group col-xs-6 col-md-6 marg_b" id="OGP"> [checkbox
ogpo id:ogp use_label_element exclusive "ogpo"] </div>

<div class="form-group col-xs-6 col-md-6 marg_b" id="LH"> [checkbox
lho   id:lho   use_label_element exclusive "lho"] </div>

<div class="form-group col-xs-6 col-md-6 marg_b" id="AIC"> [checkbox
aico id:aico use_label_element exclusive "aico"] </div> </div> <div
class="clr"></div>

</div></div><div class="clr"></div>

Any help will be greatly greatly appreciated! Thanks!




How to use Checkbox inside Select options in Knockout

Hi I want to add checkbox for all the options in dropdown.

My HTML is like this -

<div class="multi-select-dd-list"> 
            <div id="checkboxes" class="patient-list-selection">                
               <select class="patient-list-select specialty-list-left" data-bind="options : specialtiesList, optionsText : 'name'"></select>
            
        </div> 
    </div>

So here I am binding specialtiesList.

What I want is a way to use checkbox before each option of the dropdown. Any suggestions?




How to call JS function with in HTML

I am working in view File of opencart. I have 2 text boxes which set date and time respectively. I have a checkbox, its value is 1 when checked and 0 when not checked.What i want is that date and time fields should be hidden if above check box is checked (Done till now).If checkbox is unchecked, show these fields as they are now(Done till now). Current code.

HTML

<tr id="row_ship_date">
    <td>
        Shipment Date:
    </td>
    <td>
        <input type="text" id="ship_date" name="ship_date" class="date" onchange="getServices();" />
    </td>
</tr>
<tr id="row_ship_time">
    <td>
        Shipment Time:
    </td>
    <td>
        <input type="text" id="ship_time" name="ship_time" class="time" />
    </td>
</tr> 

<?php   
    if (isset($current_date_shipment) && $current_date_shipment == 1) // check box value check{?>
        <script type="text/javascript">
            document.getElementById('row_ship_date').style.display='none';
            document.getElementById('row_ship_time').style.display='none';
            getServices();
    <?php }
?>

JS:

function getServices()      {
    alert('test');
    var ship_date = $('#ship_date').val();
    var ship_time = $('#ship_time').val();
    // code so on..
}

Current issues

1) Iam unable to call getservices() function if checkbox check is true (php check of if statement) because if its false it gets call onchange event of date and works fine.

2) how can i set current date and current time respectively for both text fields if this function is called under if statement (when both fields are hidden), some thing like

function getServices()      {
    alert('test');
    var ship_date = new Date();
    var ship_time = currentTime();
    // code so on..
}