vendredi 31 juillet 2015

Assign value to Checkbox and Select fields

I'm having a small issue and not sure how to proceed . I have a modify item page where i want all the values for the item to be preselected based on its specifications in the db .

For the text input boxes , it was simple . i just used :

value = "itemno"

However for the select and checkbox - i have no idea what to do .

<select name="day">

        <option disabled selected>Day</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>

</select>

<input name="type" type="radio" value="box">

<input name="type" type="radio" value="square">

let's say the values for that item from the db are :

type : square day : 5

How can i populate the form for these values ?

I tried :

 <select name="day" value="5">

but it does not work .

For the checkbox - i have no idea either . Any help would be greatly appreciated . Thank you




I want to create a custom function in jquery with few controls as parameters. How can I achieve this?

Have a checkbox and want to enable disable many ddl according to its onchecked >functionality. I have atleast 14 checkboxes I need to accomplish this in.. Is >it possible to do this using jquery?


enter code here

");" Checked="false" />

enter code here $(function enablecheck(chk,ddl) { $('[id$=chk]').on('click', function () { if ($(this).is(":checked")) {

               ddl.prop("disabled", false);

            } else {
                ddl.prop("disabled", true);

            }
        })
    });




Several checkboxes and validation jQuery

I am doing a questionnaire with several checkboxes (yes, no) and if all are ´no´ the below fields should be readonly and disabled, but if there are any ´yes´, the fields should be required. All the questionnaire is inside a table and two checkboxes for each tr.

I´m trying many things but I´m sure someone has better ideas than me.

The HTML code is the following:

<table class="table questionnaire">
                <thead>
                    <tr>
                        <th>Is required?</th>
                        <th>YES</th>
                        <th>NO</th>
                    </tr>
                </thead>
                <tbody>
                    <tr id="quest" class="quest">
                        <td>Q1</td>
                        <td><input type="checkbox" id="ques_Q1y" name="ques_Q1y" class="table quest_q"></td>
                        <td><input type="checkbox" id="ques_Q1n" name="ques_Q1n" class="table quest_q"></td>
                    </tr>
                    <tr id="quest" class="quest">
                        <td>Q2</td>
                        <td><input type="checkbox" id="ques_Q2y" name="ques_Q2y" class="table quest_q"></td>
                        <td><input type="checkbox" id="ques_Q2n" name="ques_Q2n" class="table quest_q"></td>
                    </tr>
                    <tr  id="quest" class="quest">
                        <td>Q3</td>
                        <td><input type="checkbox" id="ques_Q3y" name="ques_Q3y" class="table quest_q"></td>
                        <td><input type="checkbox" id="ques_Q3n" name="ques_Q3n" class="table quest_q"></td>
                    </tr>
                    <tr  id="quest" class="quest">
                        <td>Q4</td>
                        <td><input type="checkbox" id="ques_Q4y" name="ques_Q4y" class="table quest_q"></td>
                        <td><input type="checkbox" id="ques_Q4n" name="ques_Q4n" class="table quest_q"></td>
                    </tr>
                </tbody>
            </table>

                <div id="fields" class="fields">
                     <select class="pos" id="pos" name="pos"></select>
                     <input type="number" step="1" class="len" id="len" name="len">
                     <input type="number" step="1" class="he" id="he" name="he">
                     <select class="perm" id="perm" name="perm"></select>
                </div>

I want to make the fields below (input and selects) readable or required, depends on the checkboxes. My Jquery script is active when change checkboxes as follows:

  $("input[type='checkbox'][name^='ques_']:checkbox").change(function() {
//Code
});

That´s my way to check when checkboxes are selected, but I don´t know how to know if there are a yes or no and how to count it to make the other fields required or readable.

If any of you have some idea, thank for the help




Excel 2010 Checkboxes

I have a spreadsheet that will display options depending on a predetermined question. There may be as few as 1 option up to 25. I want the user to select only 2 of these options via a checkbox. My question is can I have a checkbox only show up if data is displayed in a particular cell.

For Example:

X John Smith

X Sally Jones

X Fred Kelly

X George Jones

[no box available since no data]

[no box available since no data]

X Mary Lamb

Is it possible to not show a checkbox if a cell is empty?




filling checkbox in html form with python

i want filling html form with python. in html form use checkbox for check all without name attribute. 1- how to fill this checkbox? 2- after submit form process for 20 sec and response,is this pass in python?




ListView CheckBox getting multi selected on just clicking only one time

I'm trying to use checkbox in my listview with a arrayAdapter. When I select any checkbox onlytime in the list, multiple entries are selected automatically in a random order. Can anyone please tell how I can avoid this.




check box issue using UltimateListCtrl in vitural mode to display data in wxPython

OK, Bear with me, I have a application in python , that display result, from Database query, when can return 100 rows, or 100000+, so I am using UltimateListCtrl as part of wxPython lib, I can get it to display Data, no issue, but one of the requirements, is to have on every row on the data for an certain Colum, a checkbox, so user can select or not but this is what I am having trouble with, I know you can add wxWidgets, to UltimateListCtrl rows , but not sure how to do it in Virtual mode , as I scroll around data Below is my code

any help, adive, examples, is welcome, as it been doing my head in for a few weeks.

import wx from wx.lib.agw import ultimatelistctrl as ULC

class clsVCList00(ULC.UltimateListCtrl):

def __init__(self, parent):
    #
    self.cols = ["Select","Index","Research Key","Results"]   
    self.hdr_index = 0
    #
    ULC.UltimateListCtrl.__init__(self, parent , -1, agwStyle=wx.LC_REPORT|wx.LC_VIRTUAL|wx.LC_VRULES)
    #
    for hdr in self.cols:
        res = self.InsertColumn(self.hdr_index, hdr, width=150)
        if hdr == "Select":
           chk = ULC.UltimateListItem()
           chk._mask = wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT | ULC.ULC_MASK_CHECK
           chk._image = []
           chk._format = wx.LIST_FORMAT_LEFT
           chk._text = "Select"
           chk._kind = 1      
           self.SetColumn(res,chk)
        self.hdr_index = self.hdr_index + 1 
    #
    #    
    self.attr1 = ULC.UltimateListItemAttr()
    self.attr1.SetBackgroundColour(wx.NamedColour("yellow"))
    self.attr2 = ULC.UltimateListItemAttr()
    self.attr2.SetBackgroundColour(wx.NamedColour("light blue"))
    self.SetItemCount(10000)


def OnGetItemAttr(self, item):
    if item % 3 == 1:
        return self.attr1
    elif item % 3 == 2:
        return self.attr2
    else:
        return None

def OnGetItemImage(self, item):
    return []

def OnGetItemText(self, item, col):
    return "Item %d, column %d" % (item, col)

def OnGetItemToolTip(self, item, col):
    if item == 0:
        return "Tooltip: Item %d, column %d" % (item, col)
    return None

def OnGetItemTextColour(self, item, col):
    if item == 0 and col == 0:
        return wx.Colour(255,0,0)
    elif item == 0 and col == 1:
        return wx.Colour(0,255,0)
    elif item == 0 and col == 2:
        return wx.Colour(0,0,255)
    else:
        return None




DataGridCheckBoxColumn binding Mode twoWay my database is not updated

I am trying to do to a Bingding from my database to my DataGridCheckBoxColumn. If i do some change in my DataGridCheckBoxColumn my databse is not updated.

XAML code Binding="{Binding Path= TLV, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" IsReadOnly="False"/>

viewModel public bool? TLV { get { return _terminal.TLV; }

        set
        {
            if (_terminal.TLV != value)
            {
                _terminal.TLV = value;
                //RaisePropertyChanged("TLV");
                NotifyPropertyChanged("TLV"); 
            }
        }
    }




How can I tie input checkbox to Javascript function?

I can't bind my checkbox result to Javascript code. How can I do this correctly? The script doesn't react to this.

application.js

$(document).on('ready page:load', function () {
 function setCheckbox() {
    $('.check').on('click', function complete(){
      alert("alert");
    }) }
})

view file

 <input type="checkbox" value="<% article.complete %>" class='check' data-remote="true" >




Bootstrap table - sort event

I have bootstrap table. In first col I have checkbox styled with Switchery plugin. I'm not able to reinitialize switchery checkbox after table sort event. I found this event:

onSort: function (name, order) {
   $result.text('Event: onSort, data: ' + name + ', ' + order);
},

But it looks like the event is called before sort is done... Search event, page event works but sort no. Can anybody help me?

Other question is how can I reinitialize Switchery instances, because everytime I call new ones :)




How to get value of each checkbox placed in list

List is dynamically placed inside this div:

  <div id="SymptomSection"></div>

List is built here:

 function listSymptoms(pObject) {
    var r = new Array();
    var j = -1;
    var after_i = -1;
    var name;
    r[++j] = '<ul class="list-group" id="no-dot-list">';
    for (var i in array) {
        var d = array[i];
        if (d.FettleType == pObject.value) {
            after_i++;
            name = d.Type.toString();
            r[++j] = '<li class=" my-symptom-list">'
            r[++j] = '<input name="SymptomList['
            r[++j] = after_i
            r[++j] = '].IsChecked" id="fettleControl" type="checkbox" value="false"'
            if (d.IsChecked&& firstLoadOnPage)
            r[++j] = ' checked '
            r[++j] = '>'
            r[++j] = d.DisplayName
            r[++j] = '</input>'
            r[++j] = '<input name="SymptomList['
            r[++j] = after_i
            r[++j] = '].IsChecked" type="hidden" value="false">'
            r[++j] = '</li>';
        }
    }
    r[++j] = '</ul>';
    //for(var b in r)
    //{ alert(r[b]);}
    firstLoadOnPage = false;
    var list = document.getElementById('SymptomSection');
    list.innerHTML = r.join('');
};

Function code:

function validateFettleSymptoms() {
var after_i = 0;
$("#SymptomSection li").each(function () {
    var isChecked = $(this).find('#fettleControl'+after_i).first().attr("checked");
    alert($(this).find('#fettleControl' + after_i).first().val);
    if (isChecked)
        return true;
    after_i++;
});
return false;
}

Problem is How do I correctly get the checked value? I've tried many options (with finding through id, classname, etc) and it did not work, alert was saying "undefined". Now it says a huge portion of code

I can't post pictures, so here's a link for screenshot of an alert http://ift.tt/1OF7NL8




Ember.js checkbox and Promise

I have an issue when trying to use a checkbox to work out if a one-to-many relationship exists.

I have a userPrivilege table with userId, modelId, privilegeId and scopeId.

I am trying to display checkboxes which show whether the user has privileges. To do this, I need to check multiple conditions, not just a simple boolean field.

I can use asynchronous functions to determine whether the user has privileges, but I just don't know how to assign this to the checkbox 'selected'. Returning the promise means the checkbox is always checked. Returning the value from within the promise always leaves it unchecked.

See below a snippet of something I was attempting...

Checkbox Component:

    export default Ember.Component.extend({
          user: null,
          model: null,
          privilege: null,
          scope: null,
          selected: function() {
            return this.get('authorization').hasAuthorization(
              this.get('user.id'), 
              this.get('model'), 
              this.get('privilege'), 
              this.get('scope')).then(function(result) {
              return result;
            });
          }.property()
        })

Service:

export default Ember.Service.extend({
  hasAuthorization: function(userId, model, privilege, scope) {
    var store = this.get('store');

    return new Ember.RSVP.Promise(function (resolve, reject) {
      store.find('user', userId).then(function (user) {
        user.get('userPrivileges').then(function (userPrivileges) {
          userPrivileges.find(function (userPrivilege, index, userPrivileges) {
            userPrivilege.get('model').then(function (_model) {
              if (_model.get('name') === model) {
                userPrivilege.get('privilege').then(function (_privilege) {
                  if (_privilege.get('name') === privilege) {
                    userPrivilege.get('scope').then(function (_scope) {
                      if (_scope.get('name') === scope) {
                        resolve(true);
                      }
                    });
                  }
                });
              }
            });
          });
        });
      });
    });
  }
});




Making checkboxes checked using same id using Javascript

This is my code to make check boxes checked with same id

<input type="checkbox" name="MassApprove" value="setuju2"  />
<input type="checkbox" name="MassApprove" value="setuju3"  />
<input type="checkbox" name="MassApprove" value="setuju4"  />
<input type="checkbox" name="MassApprove" value="setuju5"  />
<input type="submit" value="Next Step" name="next" />

And This is my javascript code. I need to make this checkboxes as checked when am trigger this function. Help me!..

    function doMassApprove(massApproveFlag) {
        var confirmAlert = confirm("Do You Need Mass Approve !..");
        var massApprove = document.getElementById("MassApprove").length();
        if (confirmAlert == true) {
            //alert(massApproveFlag);
            for (var i = 0; i < massApprove; i++) {
                document.getElementById("MassApprove").checked = true;
            }
        } else {
            document.getElementById("headerMassApprove").checked = false;
        }
    }




Query after multiple checkbox list items fails

I have a checkboxList

var checkBoxListAllStates = (CheckBoxList)PanelDeliveryState.GetAllControls().First(y => y.GetType() == typeof(CheckBoxList));

And a ListItem which will contain only the selected checkboxes

var onlySelectedStates = checkBoxListAllStates.Items.Cast<ListItem>().

Where (y => y.Selected).Select(y=>y.Value);

A database context variable : var query = _dbContext.Deliveries;

The problem is that when I want to query in the database for each value in the onlySelectedStates the query will not function in the for each and it will retrieve only the list containing the first value.

The query is like this :

query = query.Where(y => y.State == (ExternalProductState)Enum.Parse(typeof(ExternalProductState), eachSelectedState).

Tried a lot but did not found a solution. Any idea ?




Knockout.js two-way binding for checkbox not working

I'm new to knockout.js and I have some trouble with two-way binding of a checkbox.

I have a table that's bound to a list of "companies".

<table>
    <thead>
        <tr>
            <th>...</th>
            <th>...</th>
            <th>...</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: companies">
        <tr>                
            <td>...</td>
            <td><input type="checkbox" data-bind="checked:isCompanyForCommunication, click:$root.checkedNewCompanyForCommunication" /></td>
            <td>...</td>
        </tr>
    </tbody>
</table>

But there should only be 1 company with isCompanyForCommunication = true in the table. So when another checkbox is checked, I have to set all other companies to isCompanyForCommunication = false. Therefore I created a method in the viewModel to uncheck all other companies.

    // Definition of Company
    var Company = function (crmAccountObject, contactId, companyForCommunicationId) {

        this.isCompanyForCommunication = ko.observable(false);
    }

    // Definition of the ViewModel
    var ViewModel = function () {
        var self = this;

        // ...

        // Lists
        this.companies = null; // This observableArray is set somewhere else

        // Events
        this.checkedNewCompanyForCommunication = function (company, event) {

            // Set all companies to False
            for (var i = 0; i < self.companies().length; i++) {
                self.companies()[i].isCompanyForCommunication = ko.observable(false);
            }

            // Set the "checked" company to TRUE
            company.isCompanyForCommunication = ko.observable(true);
            return true;
        }
    }

However, the changes are not reflected in the HTML page. All other checkboxes remain checked.

I created a simplyfied example in jsfiddle to show what exactly I want to achieve with the checkbox http://ift.tt/1IwP3gH

Someone has any idea what I'm doing wrong? Thanks in advance!




jeudi 30 juillet 2015

jQuery action on HTML Checkbox

I am having a little bit of trouble understanding why my checkbox is not producing any action. I would appreciate any suggestion as to where my mistake occurred. Thank you!

Best, Ray

<!DOCTYPE html>

<head>
</head>

<body>
<form>
        <div id = "canada1"> <input type ="checkbox" name ="location" value ="canada"> Canada <br><div>
    <div id = "central_america1"> <input type ="checkbox" name ="location" value ="central_america"> Central America <br></div>
</form>

<script type = "text/javascript" src='http://ift.tt/1APuVEV'></script>

<script type = "text/javascript">

        $(document).ready(function(){
                alert("this appears")

                $('#canada1').click(function() {

                        if ($('#canada1').is(':checked')) {
                                alert("Canada is checked");
                                console.log("is this working?")
                        };

                });
        });
</script>
</body>
</html>



checkBox checked not working

i'm having some trouble working with there checkbox. So in my app the user as 2 check boxes, and then a button, that button opens a new intent, and i need to pass the information through the intent to know if the checkbox is checked or not. I'm passing that information with the .putExtra() but then in the new intent when i do a if statement my app always crashes here because it gives me always a null pointer exception. Here's the code for the button and pass the information:

final CheckBox sabado = (CheckBox) findViewById(R.id.checkBoxSabado);
    final CheckBox domingo = (CheckBox) findViewById(R.id.checkBoxDomingo);

    //Clique no botao "PROCURAR"
    buttonProcurar.setOnClickListener(
            new Button.OnClickListener(){
                @Override
                public void onClick(View v) {
                    if(deTextPartida.getText().toString().equals(paraTextDestino.getText().toString())){
                        Toast.makeText(getBaseContext(), "Partida e destino nao podem ser iguais, escolha de novo!", Toast.LENGTH_LONG).show();
                    }
                    else{
                        Intent i = new Intent(horariosMenu.this, mostraHorario.class);
                        i.putExtra("Partida", deTextPartida.getText().toString());
                        i.putExtra("Destino", paraTextDestino.getText().toString());
                        i.putExtra("Sabado", sabado.isChecked());
                        i.putExtra("Domingo", domingo.isChecked());
                        startActivity(i);
                    }
                }
            }
    );

And here's the code to get it:

Bundle data = getIntent().getExtras();
    if(data == null){
        return;
    }
    String Partida = data.getString("Partida");
    String Destino = data.getString("Destino");
    String Sabado = data.getString("Sabado");
    String Domingo = data.getString("Domingo");

    if(Sabado.equals("true")){
        Toast.makeText(getBaseContext(), "Sabado", Toast.LENGTH_LONG).show();
    }

What am i doing wrong guys ? :X




JavaFx - get text value from a ListView of CheckBox

I cannot manage to get the text values of the selected CheckBox i have inside the ListView list.

(a)->{
        ObservableList<CheckBox>l=list.getSelectionModel().getSelectedItems();
        String text="";
        for(CheckBox y:l)text+=y.getText()+" ";
        label.setText(text);
    }

All i have is an empty label.




Symfony2 save checkbox multiple

I try to save a multiple checkbox into my db.

this my code:

...
->add('typz', 'choice', array(
            'choices' => array('val1' => 'val1', 'val2' => 'val2', 'val3' => 'val3', 'val4' => 'val4'),
            'empty_value' => false,
            'expanded' => true,
            'required' => false,
            'multiple'  => true
        ))
...

In the entity i already tried field type simple_array, array, string. but i get always the error "The value you selected is not a valid choice".

Any help. thanks




Getting the value of a checkbox

This is code I found when searching to understand and learn about Tkinter, but it gives an error on check box toggle.

from Tkinter import * 
    class Example(Frame):


        def __init__(self, parent):
            Frame.__init__(self, parent)   
            self.parent = parent
            self.initUI()

        def initUI(self):      
            self.parent.title("Windows")


            Label(text="Contact List").grid(row=0,column=0,columnspan=2)
            Text(width=30,height=15).grid(row=1,rowspan=9, column=0,columnspan=2,padx=20)
            Button(text="Display Contact").grid(row=10, column=0,columnspan=2,pady=10)
            Label(text="Last Name:").grid(row=11, column=0,pady=10)
            Entry().grid(row=11,column=1)
            Button(text="Search").grid(row=12,column=0,columnspan=2)
            Label(text="New Contact").grid(row=0,column=2,columnspan=2)
            Label(text="First Name:").grid(row=1,column=2,sticky=E)
            Entry().grid(row=1,column=3)
            Label(text="Last Name:").grid(row=2,column=2,sticky=E)
            Entry().grid(row=2,column=3)
            Label(text="Phone #:").grid(row=3,column=2,sticky=E)
            Entry().grid(row=3,column=3)

            friend_check = IntVar()
            Checkbutton(variable=friend_check, command = self.friend_box, onvalue=1, offvalue=0, text = "Friend").grid(row=4,column=3,sticky=W)

            #Label(text="Friend").grid(row=4,column=3,padx=20,sticky=W)
            Label(text="Email:").grid(row=5,column=2,sticky=E)
            Entry().grid(row=5,column=3)
            Label(text="Birthday:").grid(row=6,column=2,sticky=E)
            Entry().grid(row=6,column=3)
            Button(text="Add Contact").grid(row=7,column=3,sticky=E)


        def friend_box(self):

            if self.friend_check.get() == 1:
                print '1'
            else:
                print '0'


    def main():

        root = Tk()

        root.geometry("600x450+900+300")
        root.resizable(0,0)
        app = Example(root)
        root.mainloop()  


    if __name__ == '__main__':
        main()  

This is the error mentioned above:

AttributeError: Example instance has no attribute 'friend_check'

Exception in Tkinter callback

How can I avoid this error?




Insert checkboxes values(name) into input with jQuery

I'm working with Symfony and I have a lot of checkboxes with different id and value, so when I check one, i want to automatically insert its value (name) into an input and when I check other insert its value in the same input:

<input type="checkbox" name="{{ent.username}}" value="{{ent.username}}">

Thanks everyone




lc_switch change backgroud color on error

I use the jquery plugin lc_switch http://ift.tt/1DSuO7u for toggle checkboxes.

HTML CODE :

    <input type="checkbox" name="relation_cse" id="relation_cse" <?php echo $disabled; if ($relation_cse == "1") { echo " checked='checked' "; } ?>value="1" class="lcs_check " autocomplete="off" />

JS CODE on dom ready

    $("#relation_cse").lc_switch('Oui', 'Non');

When i have an error i try to change the backgound color like this but this does not works

   $(".lcs_cursor").css( "background", "red" );
   $('.lcs_switch').css( "background", "red none repeat scroll 0 0" );
   $('.lcs_on').css( "background", "red none repeat scroll 0 0" );

The plugin generate the class over in javascript copy of generated code :

    <div class="lcs_wrap">
    <input id="relation_cse" class="lcs_check " type="checkbox" autocomplete="off" value="1" checked="checked" name="relation_cse">        
    <div class="lcs_switch lcs_on lcs_checkbox_switch">
    <div class="lcs_cursor"></div>
    <div class="lcs_label lcs_label_on">Oui</div>
    <div class="lcs_label lcs_label_off">Non</div>
    </div>
    </div>      

Thanks if someone have an idea !!!




Javascript to select all but the first checkbox on a page?

I want to be able to automatically mark all the checkboxes on a page EXCEPT the first one.

I have found a javascript snippet that selects all the checkboxes, that is currently working for that purpose, but I don't want it to select the first checkbox...

[].forEach.call(document.querySelectorAll('input[type="checkbox"]'), function (el) {el.checked = true});

I've tried various If statements within the above snippet, all of which break the process.

Any help will be appreciated. Note:(I am implementing this as a bookmarklet.)




How to organize checkboxes in a neat way in my html code?

How to organize checkboxes in a neat way in my html code?I want the 10 boxes to appear one over one in 2 lines,Is there a specific methd to arrange them.This is the code I'm working on. HTML 5

    <body>
        <form name="myForm" method="post" action="form2.html">
            <table>             
                <tr>
                    <td>Completed Subjects  :</td>
                    <td>
                        <input type="checkbox" value="IPE">IPE 
                        <input type="checkbox" value="CF ">CF
                        <input type="checkbox" value="MIT">MIT
                        <input type="checkbox" value="DCCN-I">DCCN-I
                        <input type="checkbox" value="ELS-I">ELS-I
                        <br/>
                        <input type="checkbox" value="ST-I">ST-I
                        <input type="checkbox" value="ITA">ITA
                        <input type="checkbox" value="FCS">FCS
                        <input type="checkbox" value="DBMS-I">DBMS-I
                        <input type="checkbox" value="ELS-II">ELS-II
                    </td>
                </tr>                       
            </table>
        </form>                         
    </body>
</html>




create dynamic checkbox in wordpress editor button pop-up using window manager wordpress

I am trying to create dynamic checkbox in tinymce wordpress editor button. below is code. can anyone help me where i am doing mistake.

 editor.windowManager.open({    
                title: 'Property Listing For Multiple Selection',
                 popup_css : false, // Disable TinyMCE's default popup CS

for (var n = 0; n < P_name.length; n++) {

body: [
    {
        type: 'checkbox',
        //name: 'checkboxes',
        text:"MyCheckbox",
        value:"abcll",

                 onclick: function( b ) {
                     //if(b.data.title ==vine) {
                     alert(this.text());
                     alert(this.value());
                    //}
                 },
     },

  ]

 }
  },            
 }); //window manager close




How to check array value in dyamically in AngularJS?

Consider selected array have two values $scope.selected = ["Show Activated","Show InActivated"]

This below source code is working fine because here i am checking the value manually for example: i am checking whether "Show Activated"* or " Show InActivated" then i am assign isActive value true or false

My requirement is dynamically i have to do this. if it is "Show Activated" assign isActive value is True. Please check this plunker link... http://ift.tt/1ItLgkf

This below source code in plunker won't work because it's my real code for understanding purpose added in that link. But selection part working fine.

 // Object Filteration 
     $scope.objectFilterSubmit = function () {  
        if($scope.selected.length>1) {
             $scope.IsActive = "";
             $scope.selectedObjectDatas = $scope.getCustomObjectsBasedOnObjectTypeSelection($scope.IsActive);
             clearPartialElement();
             $scope.objectCreationPage();
        } else {
            angular.forEach($scope.selected, function(value,key){
                if(angular.equals(value, "Show Activated")) {   
                   $scope.IsActive = "true";   
                   $scope.selectedObjectDatas = $scope.getCustomObjectsBasedOnObjectTypeSelection($scope.IsActive);
                   clearPartialElement();
                   $scope.objectCreationPage();  
                }   
                else if(angular.equals(value, "Show InActivated")) {    
                     $scope.IsActive = "false";              
                     $scope.selectedObjectDatas = $scope.getCustomObjectsBasedOnObjectTypeSelection($scope.IsActive);
                     clearPartialElement();
                     $scope.objectCreationPage();   
                }
                else {
                     $scope.IsActive = "";
                     $scope.selectedObjectDatas = $scope.getCustomObjectsBasedOnObjectTypeSelection($scope.IsActive);
                     clearPartialElement();
                     $scope.objectCreationPage();
                }
            });
       }
      };

Please anyone help me to achieve this.




retrieving value of dynamically built set of checkboxes

I have a set of dynamically built checkboxes (sub-categories of main-category).

<input type="checkbox" name="SubCats" class="subcat-checkbox" value="18001700">first</input>
<input type="checkbox" name="SubCats" class="subcat-checkbox" value="18001700">second</input>
<input type="checkbox" name="SubCats" class="subcat-checkbox" value="18001700">third</input>
<input type="checkbox" name="SubCats" class="subcat-checkbox" value="18001700">forth</input>

Now when I submit the form, when I return back to the form from Server (if didn't pass validation, for example) I would like to be able to reconstruct that list of checkboxes with their values. Assume that the first two checkboxes were checked by the user I would like to have something like this:

<input type="checkbox" name="SubCats" class="subcat-checkbox" value="18001700" checked>first</input>
<input type="checkbox" name="SubCats" class="subcat-checkbox" value="18001700" checked>second</input>
<input type="checkbox" name="SubCats" class="subcat-checkbox" value="18001700">third</input>
<input type="checkbox" name="SubCats" class="subcat-checkbox" value="18001700">forth</input>

I assume that I do that as one of the first things here:

(document).ready(function () {

    loadSubCategories();
}

I am using ASP.NET MVC and I can't figure out how do I deliver that information into the View (the HTML). I assume this is a common task in web development. How is it done in general?




Draw/delete (show/hide) specific lines on checkbox C# winForms Graphics

I created an app in C#, windows forms where I draw all my objects on panel. I created grid, lots of lines, rectangle, filled elipses etc...

I want to create checkbox where I can control which lines should be shown and when. For instance if checkbox is checked, show lines and if it is not checked, hide them or remove them from panel.

How to do this? I can only delete all objects from panel, not specific ones... How to iterate through program since there are no ID's?

Example how the objects are added.

e.Graphics.DrawLine(pen, x1, y1, x2, y2);

e.Graphics.FillEllipse(Brushes.Red, x1, y1, 10, 10);

Is there a way to group them somehow? I could rewrite whole code just with/without lines I want but since there is alot of code that's not a great idea.




How to store checkbox values in a field of type Array in mongo

I am creating checkboxes with a loop in angular:

<span ng-repeat="role in roles">
      <label class="checkbox" for="{{$index}}">
        <input type="checkbox" ng-model="formData.selected.ids[$index]" ng-value="role" ng-required="!formData.selected" id="{{$index}}" />
        {{sport}}
      </label>
    </span>

schema looks like this :

var UserSchema = new Schema({
  name: String,
  email: { type: String, lowercase: true },
  role: [{
    type: String,

    default: 'user'
  }],
  hashedPassword: String,
  provider: String,
  salt: String
});

At backend, we call:

exports.create = function (req, res, next) {
  var newUser = new User(req.body);
  newUser.provider = 'local';
  console.log(req.body);
  newUser.role = req.body.role;
  newUser.save(function(err, user) {
    if (err) return validationError(res, err);
    var token = jwt.sign({_id: user._id }, config.secrets.session, { expiresInMinutes: 60*5 });
    res.json({ token: token });
  });
};

How do we save checkbox values in the role array ?




How to disable the checkbox in angularjs

I have a list of checkboxes on view page for to send notifications for different roles.I want to disable some checkboxes in unchecked state initially.

I am working with following code in view

<div ng-repeat="notification in NotificationList  | filter:{Media: item.Media}" ng-if="!collapsedNotification" ng-class="{'pad-top-4':($first)}" >
                                    <label for="NotificationLabel" class="col-sm-4 col-md-4 col-lg-4 control-label font-normal" title="{{notification.NotificationLabel}}">{{notification.NotificationLabel}}</label>
                            <div class="col-sm-1 col-md-1 col-lg-1"  style="line-height:35px;">
                                <span  class="col-lg-2 col-md-2 col-sm-2 item-padding ">
                                    <span class="default-pointer" ng-checkbox  ng-init="ToAdmin=false" ng-model='ToAdmin' ng-click="disableClick()" ng-disabled="ToAdmin"></input>

                                </span>

                            </div>
                            <div class="col-sm-1 col-md-1 col-lg-1" style="line-height:35px;">
                                <span  class="col-lg-2 col-md-2 col-sm-2 item-padding ">
                                    <span class="default-pointer" ng-checkbox ng-model='notification.ToNutritionist'></span>                                        
                                </span>
                            </div>
                            <div class="col-sm-1 col-md-1 col-lg-1"  style="line-height:35px;">
                                <span  class="col-lg-2 col-md-2 col-sm-2 item-padding ">
                                    <span class="default-pointer"  ng-checkbox ng-model='notification.ToPatient'></span>                                        
                                </span>
                            </div>
                                   </div>

How can i disable the checkboxes(in unchecked state) for specific roles in controller using angularjs?




Ajax Serialize passing two different check box

i created a 2 tables with checkboxes each row those 2 tables uses 2 different checkboxes how can i pass it to another page using ajax?

<td><span class="wrapper1"><input type="checkbox" name="sendmeso[]" id="cbUnreg" value="<?php echo $row["id"] ?>"/></span></td>

<td><span class="wrapper2"><input type="checkbox" name="sendmesa[]" id="cbReg" value="<?php echo $row["id"] ?>"/></span></td>

those are the properties of the checkboxes this is my ajax can you please check if am i doing it right?

var formData = $( "input[name^=sendmeso]:checked" ).serialize() + $( "input[name^=sendmesa]:checked" ).serialize() + "&imgurl="+ $("#festival").val() + "&message=" + $("textarea").val();    
    $.ajax({
        type: "POST",
        data: formData, 
        url: "processmessage.php", 
        success:function(res){
            $(".greetblock").slideUp(1000);
            $(".serverresponse").prepend(res).hide().fadeIn(2000);
        }
    });

please help me thanks




CheckBox Not Sending Checked Value to Database C# Asp

Note: I need complete solution as soon as possible because I am Stuck in my Project. I am making a Attendance System in which I get Student Record from student table in a Gridview with a check box. tick the check box for present and leave unchecked for absent. submit my record to attendance. Problem: If I Check or left unchecked it will show the Absent in Database Results after submission of attendance please check my code please.

HTML

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="RecordTablesss.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://ift.tt/lH0Osb">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Label ID="LabelSr" runat="server" Text=<%#Eval("Sr_Number") %>></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Label ID="LabelName" runat="server" Text=<%#Eval("Name") %>></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Label ID="LabelFN" runat="server" Text=<%#Eval("F_Name") %>></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckAttendence" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:Button ID="ButtonSubmit" runat="server" Text="Submit" OnClick="SaveAttendence" style="width: 61px" />
    </div>
    </form>
</body>
</html>

Code Behind:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;

namespace RecordTablesss
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            loadData();
        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void loadData()
        {
            SqlConnection con = new SqlConnection("Data Source=HammadMaqbool;Initial Catalog=FYP_Demo;Integrated Security=True");
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter("Select Sr_Number,Name,F_Name From Registerd_Student",con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds.Tables[0];
            GridView1.DataBind();
        }

        protected void SaveAttendence(object sender, EventArgs e)
        {
            foreach (GridViewRow row in GridView1.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    string sta = "";
                    CheckBox chkVar_ = row.FindControl("CheckAttendence") as CheckBox;
                    if (chkVar_.Checked)
                        sta = "P";
                    sta = "A";

                    string StudentName = (row.FindControl("LabelName") as Label).Text;
                    string F_Name = (row.FindControl("LabelFN") as Label).Text;
                    int Number = int.Parse( (row.FindControl("LabelSr") as Label).Text);
                    //From Here to onword Database Operations. ..  
                    SqlConnection conn = new SqlConnection("Data Source=HammadMaqbool;Initial Catalog=FYP_Demo;Integrated Security=True");
                    conn.Open();
                    SqlCommand cmd = new SqlCommand("Insert into Attendance_B values('"+Convert.ToInt32(Number)+"','"+StudentName+"','"+F_Name+"','"+sta+"')",conn);
                    cmd.ExecuteNonQuery();
                }
            }
        }

        protected void ButtonSubmit_Click(object sender, EventArgs e)
        {

        }
    }
}




CheckBox setSelected not working when using android:drawableRight property

My Checkbox inside xml layout:

<CheckBox
                        android:id="@+id/cb1"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:layout_marginTop="15dp"
                        android:button="@null"
                        android:drawableRight="?android:attr/listChoiceIndicatorMultiple"
                        android:paddingLeft="6dp"
                        android:paddingRight="5dp"
                        android:text="Trending Stores"
                        android:textColor="@color/black"
                        android:textSize="18sp" />

Inside onCreate() method of the related activity:

CheckBox cb1 = (CheckBox) findViewById(R.id.cb1);
cb1.setSelected(true);

This doesn't show a selected state when I run the app instead checkbox appears unselected. Can't figure out how to solve this issue. Also i need to show the checkbox on the right side and so I am using the property android:drawableRight. I have tried with using custom drawable xml file too, but I am still stuck with the same problem. Please help.




mercredi 29 juillet 2015

How to click on image which then go to another page and auto-check specific checkbox

I have page 1 which has 3 images. On the next page, there are 3 check boxes with the same id as the images. Roughly like this:

Page 1

[image1] [image2] [image3]

Page 2

[ ] Checkbox for image1

[ ] Checkbox for image2

[ ] Checkbox for image3

When I click on [image1] , I was hoping to auto-check the checkbox for image1 on page 2. How do I do this?

I tried to apply these codes but it didn't work. Where do I get it wrong? Any helpful suggestion is highly appreciated. Thanks!

php for Page 1:

<a href="page2.php?id=image1">image1</a>
<a href="page2.php?id=image2">image2</a>
<a href="page2.php?id=image3">image3</a>

Page2:

<input type="checkbox" name="checkbox" id="image1" <?php if($id == 'image1'){echo "checked";} ?> value="Image 1" /> Image 1
<input type="checkbox" name="checkbox" id="image2" <?php if($id == 'image2'){echo "checked";} ?> value="Image 2" /> Image 2
<input type="checkbox" name="checkbox" id="image3" <?php if($id == 'image3'){echo "checked";} ?> value="Image 3" /> Image 3




Html5 form validation checkboxes.

I want to made only one checkbox for group of checkboxes mandatory for user to check without usage of JavaScript. I have the following (quite simple) code:

  <input type="checkbox" class="checkbox_condition" name="checkboxGroupName" id="first" required>
  <input type="checkbox" class="checkbox_condition" name="checkboxGroupName" id="first" required>

I want to compel visitor to select one checkbox from group. How can I do that without JavaScript? I would appreciate any recommendations.




Applying value of checkbox to API request URL

I have a checkbox which, based on its checked status, will append either "subscribed" or "unsubscribed" to the end of a request URL. The issue is that I can't get it to apply to the end of the URL, but it is going to the query string(no helpful).

<input type="checkbox" id="status" name="status" />

var input = document.querySelector('input[type=checkbox]');
var status = input.checked ? "subscribed" : "unsubscribed";

request url:

dataStore({
   callback:callback,
   cacheExp: 0,
   apiUrl: "region/"+ (options.req.query.region ? options.req.query.region : "US") + "/duration/" + (options.req.query.duration ? options.req.query.duration : "5")
});

I need to add "?subscribed=" + status to the end of the request url, but it is breaking my code.

The end results should look like this: region/US/duration/15?subscribed=true

When I apply the checkbox status to the end of the url like so:

"region/"+ (options.req.query.region ? options.req.query.region : "US") + "/duration/" + (options.req.query.duration ? options.req.query.duration : "5") + "?subscribed=" + status

I get ReferenceError: status is not defined in the terminal.




Form control checkbox linkedcell reference failing

I've devised a linked cell reference for a form control checkbox, .LinkedCell = Worksheets("sheet1").Range("D" & myCell.Row & "").Value, that will unfortunately not link to the specified cell. Although, the caption reference does work. I've placed the entire macro below:

Sub test()

    Dim myBox As CheckBox
    Dim myCell As Range

    Dim cellRange As String

    With ActiveSheet
        For Each myCell In .Range("B10:B12").Cells
            With myCell
                Set myBox = .Parent.CheckBoxes.Add(Top:=.Top, Width:=.Width, Left:=.Left, Height:=.Height)

                With myBox
                    .LinkedCell = Worksheets("sheet1").Range("D" & myCell.Row & "").Value
                    .Caption = Worksheets("sheet1").Range("B" & myCell.Row & "").Value
                    .Name = "checkbox_" & myCell.Address(0, 0)
                End With

                .NumberFormat = ";;;"
            End With

        Next myCell
    End With
End Sub

I've tried to reference the cell in this way also: .Range("sheet1!B" & myCell.Row).Value. This method fails completely.

Thanks for any suggestions.

Regards,




Can't check and uncheck checkboxes after first click

In my button click I have some logic that sets checkboxes to checked/unchecked

It works after the first check but after that it doesn't check any of the checkboxes. The button text still changes on each click but not the checkboxes

Here is my logic in the click event

var buttonText = $('button.btn.btn-default.check-all').text();
if (buttonText == "Check All") {
  $('button.btn.btn-default.check-all').text('Uncheck All');
  $('#Users').find(":checkbox").attr("checked", true);
} else {
  $('button.btn.btn-default.check-all').text('Check All')
  $('#Users').find(":checkbox").attr("checked", false);
}



Align checkbox with text in comments form

I have added a wee "notify me of new comments" checkbox on my comment form, but cannot get the box to align with the text; it is always centred on the line below.

Is there a way that I can get the checkbox to show up next to the text?

Example page here: http://ift.tt/1gmjonN

<div class="commentform">
{exp:comment:form channel="blog" entry_id="{structure:page:entry_id}" parse="inward"}
<label for="name">Your name</label>
<input type="text" name="name" value="{name}">
<label for="email">Your email address</label>
<input type="email" name="email" value="{email}">
<label for="url">Your website (if you have one)</label>
<input type="url" name="url" value="{url}">
<label for="comment">Your comment</label>
<textarea name="comment" id="comment" value="comment" rows="8"></textarea>
<label for="checkbox">Notify me of follow-up comments?</label>
<input type="checkbox" name="notify_me" value="yes" {notify_me}/>
<input type="submit" name="submit" value="Submit" id="comment-submit">
{/exp:comment:form}
</div>




Excel Application.Caller Error 2023

I created a long column of check boxes in Column M, and I would like to have a macro that displays the username in Column N and the date in Column O. Here's what I have thus far:

Sub CheckBox_Click()

    Dim cb As CheckBox
    Set cb = ActiveSheet.CheckBoxes(Application.Caller)

    Set NLoc = cb.TopLeftCell.Offset(0, 1)
    Set OLoc = cb.TopLeftCell.Offset(0, 2)

    If cb.Value = xlOn Then
        NLoc.Value = Application.UserName
        OLoc.Value = Now()
    Else
        NLoc.Value = Null
        OLoc.Value = Null
    End If
End Sub

This works fine if I replace Application.Caller with the name of each check box, but, as I have many check boxes, I would like to be able to do this generically. However, when I try to compile, I get:

Run-time error '91':
Object variable or With block variable not set

When I hover over Application.Caller, it says

Application.Caller = Error 2023

How do I fix this?




Using checkboxes to exclude certain results using javascript

I have a list of things in an array the array consists of arrays of things, like lets say a recipe book or a dvd collection. so you would have an array containing your dvds which contain an array (array... title, length, genre...).

  1. I have a checkbox system that allows you to pick required fields and the javascript scans the checked checkboxes and if the value of the checkbox matches that of a dvd it will output it in the answer / submit.

  2. I need to however be able to select things i dont want and eliminate them from the output list. like choosing an actor you dont like, films with them in will not be outputted. ^ this is what I am struggling with. How do I combine 1. and 2. to run in one query.

I need the code to scan through the checkboxes checked and remove the results containing them from the list that will be outputted using the items they do want!

Yes, that is the best I can explain.

Any help or examples of code that will help would be greatly appreciated! Minds on the prize team! Thanks, J.

function myFunction() {
    $('#answer').toggle();
    $('#questions').toggle();

    var cb=$("input[type='checkbox']:checked");
    var foundCount=0;
    for(var i=0;i<dvds.length;i++){
        var found=false;
        var foundAct=0;
        var recp=dvds[i];

        for(var j=0;j<cb.length;j++){
            if( recp.actors.indexOf( cb[j].value ) > -1 ) {
                found=true;
                foundAct++;
            }
        }

        window.scrollTo(0, 0);
        recp.foundActCount=foundAct;

    }

    //http://ift.tt/19P8X1H
    dvds=dvds.sort( function(a,b){
        if( a.foundActCount>b.foundActCount ) {
            return -1;
        }
        if( a.foundActCount<b.foundActCount ) {
            return 1;
        }
        if( a.foundActCount==b.foundActCount ) {
            return 0;
        }
    } );

    for(var i=0;i<dvds.length;i++){
        var recp=dvds[i];

        if( recp.foundActCount > 0 ){
            foundCount++;
            $('#answer').append   ........

for(var k=0;k<recp.actors.length;k++){
                found=false;
                for(var j=0;j<cb.length;j++){
                    if( recp.actors[k] == cb[j].value ) {
                        found=true;
                    }
                }   

                if( found ){
                $('#'+recp.name.replace(//g,'_')).append(''+recp.actors[k]+' : &nbsp; <input class="ing roundedOne" type="checkbox" checked="checked"><br>');
                }else{     $('#'+recp.name.replace(//g,'_')).append(''+recp.actors[k]+' : &nbsp; <input class="ing roundedOne" type="checkbox"> <br>');
                }
            }
        }   
    }

    if( foundCount== 0 ){
        $('#noanswer').append   ......  .toggle();

Theres the code i have so far. now i need to remove the excluded checkboxes...




jquery get array values from query string url [duplicate]

This question already has an answer here:

I have a URL as http://ift.tt/1OBmBKI.

I want to get all the values of SubIndustry[] parameter and check the checkbox depending on their values.




Mark all checkboxes in UITableView with a Button Click

In my UITableView "tableview" I added checkboxes in each row using UITableView default functionality.

- (void)viewDidLoad {
     [tableview setEditing:YES animated:YES];
       }
 -(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
 {
    return 3;
 }

I can select only Multiple checkboxes.But I want to select all the checkboxes using a button click.I can use didSelectRowAtIndexPath to loop through all the rows and get the contents but the checkboxes stays unchecked.

- (IBAction)selectallbutton:(id)sender {

   NSInteger nRows=[arr count];

    for(int i=0;i<nRows;i++){
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        [self tableView:tableview didSelectRowAtIndexPath:indexPath];


    }
 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
    NSLog(@"%@",[arr objectAtIndex:indexPath.row]);
}

Is it possible to check them all using this approach or should I try another way?




How to automatically uncheck a checkbox with javascript if other is already checked?

How to automatically uncheck a checkbox with javascript if a user checks another one? I have this script:

<input type="checkbox" name="use_ssh" value="yes">SSH
<input type="checkbox" name="use_vpn" value="yes">VPN

if a user checks SSH but he also tries to check VPN then a javascript code will automatically uncheck SSH and leave VPN checked and the otherwise. How can I do that with javascript? Basically I just want one checkbox checked instead of two. Please don't ask me why I use checkbox instead of other methods, I will have to rewrite the whole script if I use other methods and I don't have enough time to do that.




mardi 28 juillet 2015

Angularjs checkbox confirmation

I want to confirm when someone unchecks a checkbox. The following function only works every other time. When it first loads its fine. It calls the confirm and if you cancel it leaves the checkbox checked. But if you click it again nothing happens. I'm sure it something simple that I'm missing:

$scope.check = function(clickedid) { 
  if (document.getElementById(clickedid).checked === true) {
    return false;
  } else {
   var box= confirm("Are you sure you want to do this?");
    if (box===true){   // yes sure
        return true;
    }
    else{   // cancel
       document.getElementById(clickedid).checked = true;
    }
  }
};

and here is the html

<lable>Checkbox
<input type="checkbox" id="check1" ng-model="active" ng-change="check('check1')">
</label>

Here is a jsfiddle




Checkbox onclick change row color

Here is my fiddle:

http://ift.tt/1KxaxMD

Once I click on a checkbox, it should change that particular tr's background color using the highlight class below:

.ui-table-highlight {
    background-color:#ffefbb;
}

I tried several solutions on stackoverflow but I think it perhaps is a problem in my css?




How to add or remove list of values in Array based on checkbox selection in AngularJS?

Please check this link. `http://ift.tt/1I8WW8i`

Whenever i am clicking first "Show Activated" and "Show Inactivated" in that list it's adding to the array(selected). But if i am clicking " Show InActivated " as first. It's not adding to the array.

Same process for removing.

Please any one help to acheive this requirement.




Ajax: convert checkbox function to input field and update button in Wordpress

The checkbox has only 2 values: 0 and 1. But what i'm trying to do is to put date and time in the text input (instead of the checkbox) and than to update it with submit button Update with Ajax. Any help please to convert a checkbox to input field and update button like this:

<input id="post_author_credit_update" name="post_author_credit" value="2015-08-22 11:00 PM" type="text"/>';
<input id="post_author_credit_update" name="post_author_credit" type="submit" class="button updatemeta button-small"  value="Update"/>

The actual checkbox

<input id="post_author_credit_update" name="post_author_credit" value="1" type="checkbox"<?php checked( get_post_meta( $post->ID, 'post_author_credit', true ), 1, false ); ?>/>

And the script responsible for saving the value:

 function ajax_save_post_author_credit() {

    // Verify that the incoming request is coming with the security nonce
    if( wp_verify_nonce( $_REQUEST['nonce'], 'ajax_post_author_credit_nonce' ) ) {

        // Set the value of the post meta based on the post data coming via the JavaScript
        $post_author_credit = '';
        if( isset( $_POST['post_author_credit'] ) && 'true' == $_POST['post_author_credit'] ) {
            $post_author_credit = 1;
        } // end if

        // Attempt to update the post meta data. If it succeeds, send 1; otherwise, send 0.
        if( update_post_meta( $_POST['post_id'], 'post_author_credit', $post_author_credit ) ) {
            die( '1' );
        } else {
            die( '0' );
        } // end if/else

    } else {

        // Send -1 if the attempt to save via Ajax was completed invalid.
        die( '-1' );

    } // end if 

 } // end ajax_save_post_author_credit
} // end class
new Post_Author_Credit();

../plugins/post-author/js/admin.js:

(function($) {
$(function() {
    $('#post_author_credit_update').click(function(evt) {

        $.post(ajaxurl, {
            action:             'save_post_author_credit',
            nonce:              $('#ajax_post_author_credit_nonce').text(),
            post_id:            $('#post_ID').val(),
            post_author_credit: $(this).is(':checked')

            }, function(response) {
                $( "#ajax_response" ).text( "UPDATED" ).show().fadeOut( 1000 );
        });
    });
});
})(jQuery);

Thanks in advance.




bootstrap checkbox changes class when checked

I'm using bootstrap's checkbox and currently looking for a way with jQuery that will allow my checkbox to change class when checked.

<form>
  <div class="checkbox">
    <input type="checkbox" name="checkbox">
    <label for="checkbox">I am not a Robot!</label>
  </div> <!-- //.checkbox -->
</form>

I've tried the following...it's not working as I wanted. Have I made a mistake somewhere?

(document).ready(function() {
  if ($('.checkbox').is(':checked')) {
    $(".checkbox").removeClass('has-error').addClass('has-success'); // checked
  } else {
    $(".checkbox").addClass('has-error'); //unchecked
  }
});

JsFiddle: http://ift.tt/1HZq3wR

If there's a better way to do this, please comment! Any help will be appreciated. :)




Get checkbox checked state using JQuery

I am assigned to get the boolean value of a checkbox.

I couldn't find a way to get the boolean value of the checkbox. e.g: true,false.

Is there a way to do this?

Link: http://ift.tt/1IH8TaY

    <body>

    <div >

    <table border=1px>

  <thead>
    <tr>
        <th colspan="5">Description</th>
        <th>Comment</th>
        <th>User</th>
        <th>Feedback</th>
        <th>Status</th>
    </tr>
    </thead>
        <tbody style="border-top : 1px solid black" id = "1">
    <tr>
        <td class="partition"><label class="label">Title:</label><label class="label ">A</label></td>
        <td class="sip" style="border-left:none"><label class="label">Author:</label><label class="label">James</label></td>
        <td rowspan="4"><input type="checkbox"><label class="label" style="padding-left:0px" id="bookstore">BookStore</label></td>
        <td rowspan="4"><input type="checkbox"><label class="label" style="padding-left:0px" id="ebook">Ebook</label></td>
        <td rowspan="4"><input type="checkbox"><label class="label" style="padding-left:0px" id="library">Library</label></td>
        <td rowspan="4"><textarea maxlength="180" class="animated" id="usercomment" name="comment" style="overflow: hidden; word-wrap: break-word; resize: horizontal;  height: 80px; width:280px;">The book is ..........</textarea></td>
        <td rowspan="4" align="center">Adam<br><button class="label label-primary" id="submit">Submit</button></td>
        <td rowspan="4" align="center">Feedback Goes Here<br></td>
            <td rowspan="4" align="center"><br>No Feedback Yet</td>
    </tr>
    <tr>
        <td colspan="2" class="def"><label class="label">Genre:</label><label class="label">Fiction</label></td>
    </tr>
    <tr>
        <td colspan="2" class="path"><label class="label label-primary" style="margin-left:5px">BookURL</label><label class="label label-primary " style="margin-left:40px">DownloadLink</label></td>
    </tr>
    <tr>
        <td colspan="2" class="path"><a style="display:none">http://ift.tt/1exCEwF;
    </tr>
</tbody>

JQuery

$("#submit").click(function() {
var $row = $(this).closest("tbody");   
var $text = $row.document.getElementById("#emulation").checked(); // 
alert($text);
});




Angularjs checkbox like gmail

Im newbie in angularjs. Now im having issues with a checkbox. First: my web are paging , sorting and change page size by call api to get data from server in factory:

this.getData = function(page , sortColumm, sortType , pageSize, searchText){
$http({
        method = get;
        url = "api/data?page="+page +"&sortColumm=" +sortColumm +"&sortType="+sortType +"&pagesize="+pageSize+"&search="+searchText;
    }).success(function (data) {
    }).error(function (error) {
    });
}

now i have a page using angularjs to bind data using funciton getData. html:

<thead>
    <tr>
        <th><input type="checkbox" ng-model="selectedAll" ng-click="checkAll()"></th>
        <th>Administrator Name</th>
        <th >Administrator Type</th>
        <th>Roles</th>
    </tr>
</thead>
<tbody>
    <tr ng-repeat="gladmin in gladmins" ng-switch on="gladmin.isEnabled"
        on-finish-render="resizetable">
        <td><input type="checkbox" ng-model="gladmin.Selected" value="{{gladmin.id}}" ng-click="selectionAdmin(gladmin.id)"></td>
        <td><a href="javascript:void(0)" title="">{{gladmin.name}}</a></td>
        <td>{{gladmin.type}}</td>
    </tr>
</tbody>

controller

app.controller('adminPage',function(){
   // call getData
   $scope.checkAll=function(){
       // what should i write here?
       // i want check all is for current page, next page checkall = fall, 
       // same GMAIL
   }
   $scope.selectionAdmin = function(id){
       // what should i do here
   }
})

All i want is the checkall same the checkall in gmail ? anyone help me ? please, i am new bie in this!

i find some link here : http://ift.tt/1KwCeSL http://ift.tt/1lmEPlk

but it work not same i want !




use text in cell as check box caption

I'm trying to alter this line of code, .Caption = .Range("Key6!B" & myCell.Row & "").Value, in the below macro to display the corresponding value on key6 as the check box caption. None of my alterations seem to be working.

With ActiveSheet
        For Each myCell In .Range(cellRange).Cells
            With myCell
                Set myBox = .Parent.CheckBoxes.Add(Top:=.Top, Width:=.Width, Left:=.Left, Height:=.Height)

                With myBox
                    .LinkedCell = linkedColumn & myCell.Row
                    .Caption = .Range("Key6!B" & myCell.Row & "").Value
                    .Name = "checkbox_" & myCell.Address(0, 0)
                End With

                .NumberFormat = ";;;"
            End With

        Next myCell
    End With

Any help is greatly appreciated.

Regards,




replace checkboxes with text input (select while typing)

I'd like to hide my (very long) list of checkboxes and show a single text input where I'd like to type the labels. When the label I typed has been found, it should be confirmed (that is selected).

It should work as wordpress let the user choose the tags. I'm thinking about something with jquery, but I didn't found anything until now.

Any idea?




How to use Nested Rules in LESS for Custom Checkbox

I have used custom Check-Box with simple css rules and Font Awesome Icon:

Custom Check Box JSFiddle

But these rules applies to all checkbox in a page.

For this problem, I found that, .LESS file can produce nested css rules.

So I have made a LESS file and put custom check box rules under one class custom-checkbox.

But it does not working.

Here is my sample code for LESS file:

/*** Custom Checkboxes START ***/
.custom-checkbox {
  input[type=checkbox] {
    display: none;
  }
  /* to hide the checkbox itself */
  input[type=checkbox] + label:before {
    font-family: FontAwesome;
    display: inline-block;
  }

  input[type=checkbox] + label:before {
    content: "\f096";
  }
  /* unchecked icon */
  input[type=checkbox] + label:before {
    letter-spacing: 10px;
  }
  /* space between checkbox and label */

  input[type=checkbox]:checked + label:before {
    content: "\f046";
  }
  /* checked icon */
  input[type=checkbox]:checked + label:before {
    letter-spacing: 8px;
  }
  /* allow space for check mark */
}
/*** Custom Checkboxes END ***/

I want to apply only single custom-checkbox class defined in LESS file. which customize that check box only. How can achieve the same thing given in my JSFiddle?




CodenameOne - GUI values from checkboxes, comboboxes and save captured photo to Cloud

I'm using NetBeans with CodenameOne and the theme GUI builder. I have created a Main Form with checkboxes in a container, and comboboxes in another container. How can I use a GUI value from the checkboxes and the comboboxes in the StateMachine to save in Cloud Storage? I have also captured a photo to the Main Form and want to save all in Cloud Storage.

Thanks in advance.




Submit multiple dynamic checkbox values in webforms

I am searching for a way to solve this situation:

  • I have a webforms page (.aspx) that has a table on it
  • The rows of the table are generated in the codebehind file (.vb/.cs)
  • each of these dynamic rows has a checkbox, that is added to cell 0 of each row
  • the page has a submit button, that submits the page (postback to same .aspx file)

The idea of the form is like this:

"Please select which of these rows you want to import, by checking those checkboxes"

The problem is that when I press the submit button, the values are lost, probably because the checkboxes (and table rows do not exist when the page loads). Can you suggest how to solve this scenario, so that my checkboxes can be read in the btnImport_Click event after being submitted?




X-Editable Huge Checklist

Im having a small problem with x-editable: I am loading a MySQL table via Ajax into a JavaScript Array and then I'm using this array as a source for my xeditable checklist input, everything works fine so far but I'm having an issue with displaying this "huge" list of data (31 Elements) and I want to ask if there is a way to split this checklist in half?

http://ift.tt/1giJjwA

I hope someone can think of a solution for this problem...

Best Regards: Dave




exclude answers from javascript query

I have a list of things in an array the array consists of arrays of things, like lets say a recipe book or a dvd collection. so you would have an array containing your dvds which contain an array (array... title, length, genre...).

1. I have a checkbox system that allows you to pick required fields and the javascript scans the checked checkboxes and if the value of the checkbox matches that of a dvd it will output it in the answer / submit.

2. I need to however be able to select things i dont want and eliminate them from the output list. like choosing an actor you dont like, films with them in will not be outputted. ^ this is what I am struggling with. How do I combine 1. and 2. to run in one query.

I need the code to scan through the checkboxes checked and remove the results containing them from the list that will be outputted using the items they do want!

Yes, that is the best I can explain.

Any help or examples of code that will help would be greatly appreciated! Minds on the prize team! Thanks, J.




android check box on listview

please tell me how to set the check box on my listview i am already write code for checkbox but it cant show me on my listview

Spinner spin;
    ListView lvl;
    ArrayAdapter<String> adapter;
    Context context;
    ArrayList<String> data;
    ArrayList<String> ItemsList;
    String selectedFromList;
    ArrayAdapter<String> adapter_subjects;
    private ProgressDialog pDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.selection);

        data = new ArrayList<String>();
        spin = (Spinner) findViewById(R.id.spinners);
        context = this;

        adapter_subjects = new ArrayAdapter<String>(spin.this,
                android.R.layout.simple_spinner_item, data);
        adapter_subjects
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin.setAdapter(adapter_subjects);

        adapter_subjects.clear();
        new asynctaskLoadsubjects().execute();

        /* lvl =(ListView)findViewById(R.id.list); */

        ItemsList = new ArrayList<String>();
        adapter = new ArrayAdapter<String>(spin.this,
                android.R.layout.simple_list_item_1, ItemsList);
        lvl = (ListView) findViewById(R.id.list);

        lvl.setAdapter(adapter);

        adapter.clear();
        new asyncFetchAllItems().execute();

        lvl.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                selectedFromList = (String) (lvl.getItemAtPosition(position));

                Intent i = new Intent(getApplicationContext(),orders.class);
                i.putExtra("Item name", selectedFromList);
                startActivity(i);

                Toast.makeText(getApplicationContext(), selectedFromList,
                        Toast.LENGTH_SHORT).show();

            }
        });

    }

    public class asynctaskLoadsubjects extends
            AsyncTask<Void, JSONObject, ArrayList<hotelitem>> {
        ArrayList<hotelitem> hotelitem = null;

        @Override
        protected ArrayList<hotelitem> doInBackground(Void... params) {
            // TODO Auto-generated method stub
            RestAPI api = new RestAPI();
            try {
                JSONObject jsonObject = api.Getitem();
                JSONParser parser = new JSONParser();
                hotelitem = parser.parseItemss(jsonObject);
            } catch (Exception e) {
                Log.d("AsyncLoadVehicleCompanies", e.getMessage());
            }

            return hotelitem;
        }

        @Override
        protected void onPostExecute(ArrayList<hotelitem> result) {

            for (int i = 0; i < result.size(); i++) {
                data.add(result.get(i).getItemtype());
            }

            adapter_subjects.notifyDataSetChanged();
        }

    }

    public class asyncFetchAllItems extends
            AsyncTask<Void, JSONObject, ArrayList<ItemTable>> {
        ArrayList<ItemTable> ItemTable = null;



        @Override
        protected ArrayList<ItemTable> doInBackground(Void... params) {
            // TODO Auto-generated method stub
            RestAPI api = new RestAPI();
            try {

                JSONObject jsonObject = api.Getallitems();
                JSONParser parser = new JSONParser();
                ItemTable = parser.parseitemdetails(jsonObject);
            } catch (Exception e) {
                Log.d("AsyncLoadVehicleCompanies", e.getMessage());
            }

            return ItemTable;
        }

        @Override
        protected void onPostExecute(ArrayList<ItemTable> result) {

            pDialog.dismiss();

            for (int i = 0; i < result.size(); i++) {
                ItemsList.add(" \n Item Name :" + result.get(i).getItemname()
                        + "\n" + "\n price            :"
                        + result.get(i).getItemprice() + "\n");
            }

            adapter.notifyDataSetChanged();

            Toast.makeText(context, "Loading Completed", Toast.LENGTH_SHORT)
                    .show();
        }

    }

    public class MyCustomAdapter extends ArrayAdapter<checkTable> {

        public ArrayList<checkTable> itemsList;

        public MyCustomAdapter(Context context, int textViewResourceId,ArrayList<checkTable> itemsList) {
            super(context, textViewResourceId, itemsList);
            this.itemsList = new ArrayList<checkTable>();
            this.itemsList.addAll(itemsList);
        }

        private class ViewHolder {
            TextView code;
            CheckBox name;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder = null;
            Log.v("ConvertView", String.valueOf(position));

            if (convertView == null) {
                LayoutInflater vi = (LayoutInflater)getSystemService(
                        Context.LAYOUT_INFLATER_SERVICE);
                convertView = vi.inflate(R.layout.abb_list, null);

                holder = new ViewHolder();
                holder.code = (TextView) convertView.findViewById(R.id.code);
                holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
                convertView.setTag(holder);

                holder.name.setOnClickListener( new View.OnClickListener() { 
                    public void onClick(View v) { 
                        CheckBox cb = (CheckBox) v ; 
                        checkTable country = (checkTable) cb.getTag(); 
                        Toast.makeText(getApplicationContext(),
                                "Clicked on Checkbox: " + cb.getText() +
                                " is " + cb.isChecked(),
                                Toast.LENGTH_LONG).show();
                        country.setSelected(cb.isChecked());
                    } 
                }); 
            }
            else {
                holder = (ViewHolder) convertView.getTag();
            }

            checkTable checkTable = itemsList.get(position);
            holder.code.setText(" (" +  checkTable.getitemprice() + ")");
            holder.name.setText(checkTable.getitemname());
            holder.name.setChecked(checkTable.isSelected());
            holder.name.setTag(checkTable);
            return convertView;
        }
    }
}

i am using reference of this site

please help me dear friends i am using this example for my example




How to add a checkbox in a combo(Drop down) in java swt?

I want to have checkboxes in a combo(Drop down) so that I can select more than one elements of combo at once. Can this be done? If yes, can you please explain or provide any link if possible.

Thank you.




Android: Can't get Checkbox OnClickListener to work in ListFragment

I've looked through a few posts, but can't get the checkbox to acknowledge clicks. I think I'm 90% there but falling over the last hurdle.

I have a ListFragment where each item has a CheckBox and a TextView. When users click on the TextView they're taken to a new fragment. But when they click the CheckBox I want the value to be ticked/unticked directly in the list.

Here's my code, kept it so that only classes relevant to the ListView are shown, let me know if you need to see others.

I did follow this guide but can't really understand why it's not working on my code: http://ift.tt/1t3dGG2

TaskListFragment.java

package com.laytonlabs.android.todotoday;

import java.util.ArrayList;

import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.drawable.LayerDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;

public class TaskListFragment extends ListFragment {
    ArrayList<Task> mTasks;
    private boolean mSubtitleVisible;
    private Callbacks mCallbacks;
    private static final String TAG = "TaskListFragment";
    private int touchPositionX;

    public interface Callbacks {
        void onTaskSelected(Task task);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mCallbacks = (Callbacks)activity;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCallbacks = null;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        getActivity().setTitle(R.string.crimes_title);
        mTasks = TaskLab.get(getActivity()).getTasks();

        TaskAdapter adapter = new TaskAdapter(mTasks);
        setListAdapter(adapter);
        setRetainInstance(true);
        mSubtitleVisible = false;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.fragment_crime_list, menu);
        MenuItem showSubtitle = menu.findItem(R.id.menu_item_show_subtitle);
        if (mSubtitleVisible && showSubtitle != null) {
            showSubtitle.setTitle(R.string.hide_subtitle);
        }
    }

    @TargetApi(11)
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_item_new_crime:
                Task task = new Task();
                TaskLab.get(getActivity()).addTaskToFirst(task);
                ((TaskAdapter)getListAdapter()).notifyDataSetChanged();
                mCallbacks.onTaskSelected(task);
                return true;
            case R.id.menu_item_show_subtitle:
                if (getActivity().getActionBar().getSubtitle() == null) {
                    getActivity().getActionBar().setSubtitle(R.string.subtitle);
                    mSubtitleVisible = true;
                    item.setTitle(R.string.hide_subtitle);
                } else {
                    getActivity().getActionBar().setSubtitle(null);
                    mSubtitleVisible = false;
                    item.setTitle(R.string.show_subtitle);
                }
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        getActivity().getMenuInflater().inflate(R.menu.crime_list_item_context, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
        int position = info.position;
        TaskAdapter adapter = (TaskAdapter)getListAdapter();
        Task task = adapter.getItem(position);

        switch (item.getItemId()) {
        case R.id.menu_item_delete_crime:
            TaskLab.get(getActivity()).deleteTask(task);
            adapter.notifyDataSetChanged();
            return true;
        }
        return super.onContextItemSelected(item);
    }

    @TargetApi(11)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
        View v = super.onCreateView(inflater, parent, savedInstanceState);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            if (mSubtitleVisible) {
                getActivity().getActionBar().setSubtitle(R.string.subtitle);
            }
        }       

        ListView listView = (ListView)v.findViewById(android.R.id.list);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            //Use floating context menus on Froyo and Gingerbread
            registerForContextMenu(listView);
        } else {
            //Use contextual action bar on Honeycomb and higher
            listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
            listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {

                @Override
                public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                    // TODO Auto-generated method stub
                    return false;
                }

                @Override
                public void onDestroyActionMode(ActionMode mode) {
                    // TODO Auto-generated method stub

                }

                @Override
                public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                    MenuInflater inflater = mode.getMenuInflater();
                    inflater.inflate(R.menu.crime_list_item_context, menu);
                    return true;
                }

                @Override
                public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                    switch (item.getItemId()) {
                    case R.id.menu_item_delete_crime:
                        TaskAdapter adapter = (TaskAdapter)getListAdapter();
                        TaskLab taskLab = TaskLab.get(getActivity());
                        for (int i = adapter.getCount() - 1; i >= 0; i--) {
                            if (getListView().isItemChecked(i)) {
                                taskLab.deleteTask(adapter.getItem(i));
                            }
                        }
                        mode.finish();
                        adapter.notifyDataSetChanged();
                        return true;
                    default:
                        return false;
                    }
                }

                @Override
                public void onItemCheckedStateChanged(ActionMode mode, int position,
                        long id, boolean checked) {
                    // TODO Auto-generated method stub

                }
            });

        }


        return v;
    }

    @Override
    public void onResume() {
        super.onResume();
        ((TaskAdapter)getListAdapter()).notifyDataSetChanged();
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        Task t = ((TaskAdapter)getListAdapter()).getItem(position);
        mCallbacks.onTaskSelected(t);
    }

    private class TaskAdapter extends ArrayAdapter<Task> {
        public TaskAdapter(ArrayList<Task> tasks) {
            super(getActivity(), 0, tasks);
        }

        private class ViewHolder {
            TextView titleTextView;
            CheckBox completedCheckBox;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            //If we wern't given a view, inflate one
            if (convertView == null) {
                convertView = getActivity().getLayoutInflater().inflate(R.layout.list_item_task,  null);

                holder = new ViewHolder();
                holder.titleTextView = (TextView)convertView.findViewById(R.id.task_list_item_titleTextView);
                holder.completedCheckBox = (CheckBox)convertView.findViewById(R.id.task_list_item_completedCheckBox);
                convertView.setTag(holder);

                holder.completedCheckBox.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        CheckBox cb = (CheckBox) v;
                        Task task = (Task) cb.getTag();
                        task.setCompleted(cb.isChecked());
                        Log.d(TAG, "Clicked on checkbox for: " + task.getmTitle());
                    }
                });
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            //Configure the view for this Task
            Task t = getItem(position);
            holder.titleTextView.setText(t.getmTitle());
            holder.completedCheckBox.setChecked(t.isCompleted());
            holder.completedCheckBox.setTag(t);

            return convertView;
        }
    }

    public void updateUI() {
        ((TaskAdapter)getListAdapter()).notifyDataSetChanged();
    }

}

list_item_task.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://ift.tt/nIICcg"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <CheckBox 
        android:id="@+id/task_list_item_completedCheckBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:enabled="false"
        android:focusable="false"  
        android:focusableInTouchMode="false"  
        android:padding="4dp" />

    <TextView 
        android:id="@+id/task_list_item_titleTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:paddingLeft="4dp"
        android:paddingRight="4dp"
        android:text="Task title" />


</LinearLayout>

Thanks in Advance!




Adding/Joining Values into Codemirror from a Checkbox

If I check normalize I want to add normalize library into Codemirror.

<link rel="stylesheet" href="http://ift.tt/1zN1Hmq" />

Then if I check jquery after I want to add jquery after normalize...

<link rel="stylesheet" href="http://ift.tt/1zN1Hmq" />
<script src="http://ift.tt/J5OMPW"></script>

but if I uncheck normalize and then check it again I want to add normalize after jquery...

<script src="http://ift.tt/J5OMPW"></script>
<link rel="stylesheet" href="http://ift.tt/1zN1Hmq" />

Though this is just a basic example as my app has a lot more checkbox's (38 to be exact) adding and removing libraries for my IDE.

Does anyone know how to do this in Codemirror?

Any help is greatly appreciated.

$(document).ready(function() {
  // Add Normalize to Codemirror
  $(".norm").on("change", function() {
    if ( $(".norm").is(":checked") ) {
      editor.setValue('<link rel="stylesheet" href="http://ift.tt/1zN1Hmq" />\n');
    }
  });
  // Add Normalize to Codemirror
  $(".jq").on("change", function() {
    if ( $(".jq").is(":checked") ) {
      editor.setValue('<script src="http://ift.tt/J5OMPW"><'+'/script>\n');
    }
  });
  // Add Angular JS to Codemirror
  $(".ang").on("change", function() {
    if ( $(".ang").is(":checked") ) {
      editor.setValue('<script src="http://ift.tt/1fxqwat"><'+'/script>\n');
    }
  });
});

var delay;

// Initialize CodeMirror editor
var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
  mode: 'text/html',
  tabMode: 'indent',
  styleActiveLine: true,
  lineNumbers: true,
  lineWrapping: true,
  autoCloseTags: true,
  foldGutter: true,
  dragDrop : true,
  gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter']
});

// Live preview
editor.on('change', function() {
  clearTimeout(delay);
  delay = setTimeout(updatePreview, 300);
});

function updatePreview() {
  var previewFrame = document.getElementById('preview');
  var preview =  previewFrame.contentDocument ||  previewFrame.contentWindow.document;
  preview.open();
  preview.write(editor.getValue());
  preview.close();
}
setTimeout(updatePreview, 300);
.CodeMirror {
  float: left;
  width: 50%;
  border: 1px solid black;
}

iframe {
  width: 49%;
  float: left;
  height: 300px;
  border: 1px solid black;
  border-left: 0;
}
<link rel='stylesheet' href='http://ift.tt/1zN1Hmq'/>
<script src='http://ift.tt/J5OMPW'></script>
<script src='http://ift.tt/1dmRy6L'></script>
<link rel='stylesheet' href='http://ift.tt/1BYO7Md'>
<link rel='stylesheet' href='http://ift.tt/1FCWaEb' />
<script src='http://ift.tt/1FCWaEd'></script>
<script src='http://ift.tt/1BYO82z'></script>
<script src='http://ift.tt/1EAg5S3'></script>
<script src='http://ift.tt/1FCW7Z8'></script>
<script src='http://ift.tt/1BYO82B'></script>
<script src='http://ift.tt/1BYO82D'></script>
<script src='http://ift.tt/1FCW7Zd'></script>
<script src='http://ift.tt/1BYO6YD'></script>
<script src='http://ift.tt/1BYO82H'></script>
<script src='http://ift.tt/1FCWaEj'></script>
<script src='http://ift.tt/1BYO6YJ'></script>
<script src='http://ift.tt/1FCWaEp'></script>
<script src='http://ift.tt/1FCWaEr'></script>
<script src='http://ift.tt/1BYO82P'></script>
<script src='http://ift.tt/1FCWaUF'></script>
<script src='http://ift.tt/1BYO8j5'></script>

<p>
  <input class="norm" type="checkbox"> Normalize<br>
  <input class="jq" type="checkbox"> Jquery<br>
  <input class="ang" type="checkbox"> Angular JS<br>
</p>

<textarea id='code' name='code'></textarea>

<iframe id='preview'></iframe>



How to get selected checkbox values and based on that values dynamically need to check that value in angularjs?

As per the link - http://ift.tt/1LP9q9K
It's working now. Thank you very much.

Now i have another requirement based on this.

How to get the selected values in array and need to perform filtration, below the source code for each selected value i am checking manually but i need to check dynamically.
Please any one help to achieve this.

$scope.objectFilterSubmit = function () {    
         $scope.selectedObject = [];
        if($scope.selected.length>1) {
             $scope.IsActive = "";
             $scope.selectedObjectDatas = $scope.getCustomObjectsBasedOnObjectTypeSelection($scope.IsActive);
             clearPartialElement();
             $scope.objectCreationPage();
        } else {
            angular.forEach($scope.selected, function(value,key){
                if(angular.equals(value, "Show Activated")) {   
                   $scope.IsActive = "true";   
                   $scope.selectedObjectDatas = $scope.getCustomObjectsBasedOnObjectTypeSelection($scope.IsActive);
                   clearPartialElement();
                   $scope.objectCreationPage();  
                }   
                else if(angular.equals(value, "Show InActivated")) {    
                     $scope.IsActive = "false";              
                     $scope.selectedObjectDatas = $scope.getCustomObjectsBasedOnObjectTypeSelection($scope.IsActive);
                     clearPartialElement();
                     $scope.objectCreationPage();   
                }
                else {
                     $scope.IsActive = "";
                     $scope.selectedObjectDatas = $scope.getCustomObjectsBasedOnObjectTypeSelection($scope.IsActive);
                     clearPartialElement();
                     $scope.objectCreationPage();
                }
            });
       }
      };




lundi 27 juillet 2015

Adding and deleting items through checkboxes using javascript

I have a javascript file ... it is basically a shopping cart As the user inputs the the items.. the cart should add and delete items. how should one delete a specific item from the cart?

Using checkboxes?




MVC4 Checkbox ensure check at least one?

i'm implementing a checkbox question for let user to choose. However, if admin set the question mandatory to true, the checkbox must select at least 1 to submit, else a message will prompt user to select. I was try added the 'required = "required" ' but it need to check all checkbox just can submit :(

Is it need javascript or jquery to do such validation?

My View:

for (int x = 0; x < Model[i].Choice_SubQuestion.Count(); x++)
     {
         if (Model[i].Mandatory == true)
        {
           // Need to check all only can submit :(                                 
              <input type="checkbox" name="[@i].MultiAnswer[@x]" value="@Model[i].Choice_SubQuestion[x]" required="required"/>
               @Html.HiddenFor(m=>m[i].MultiAnswer[x])
         }
           else
        {
               <input type="checkbox" name="[@i].MultiAnswer[@x]" value="@Model[i].Choice_SubQuestion[x]" />
               @Html.HiddenFor(m => m[i].MultiAnswer[x])
        }

               @Html.LabelFor(m => m[i].MultiAnswer[x], Model[i].Choice_SubQuestion[x].ToString(), new { @class = "questionlist1" })
          <br />

          }




Posting dynamic inputs and inserting into MySQL database

This is my schedule.php page, an example of the user selecting the specific day for the time.

enter image description here

Once the user clicks on to add, the confirmation page will show up. But unfortunately i got these errors.

enter image description here

In mySQL database, the values that suppose to belong to "1700 - 1800" appeared on the "1400 - 1600" row.

enter image description here

This is my code for the schedule.php page,

            <form name="Create New schedule"  class="form-horizontal" method="post" action="handleSchedule.php">
                <div class="form-group">
                    <div class="col-sm-4">
                        <label for="AcadInst">Academic Institution</label>

                        <select class="form-control" id="AcadInst" type="text" class="form-control" placeholder="Institution Name" name="academicInstitution">
                            <option>Institution Name</option>
                            <option>Singapore Polytechnic (SP)</option>
                            <option>Ngee Ann Polytechnic (NP)</option>
                            <option>Temasek Polytechnic (TP)</option>
                            <option>Republic Polytechnic (RP)</option>
                            <option>Nanyang Polytechnic (NYP)</option>
                            <option>Others(Please specify)</option> 
                        </select>
                    </div>
                    <div class="col-sm-4">
                        <label>Level of Teaching</label>
                        <input list="LvTeaching" type="text" class="form-control" placeholder="Teaching Stage" name="levelofteaching">
                        <datalist id="LvTeaching">
                            <option value="Undergraduate Teaching">
                            <option value="Postgraduate Teaching">
                            <option value="Continuing Education">
                            <option value="Others (Please specify)"> 
                        </datalist>
                    </div>
                    <div class="col-sm-4">
                        <label>Type of Teaching</label>
                        <input list="TyTeaching" type="text" class="form-control" placeholder="Mode of Teaching" name="typeofteaching">
                        <datalist id="TyTeaching">
                            <option value="Clinical Teaching">
                            <option value="Academic Teaching">
                            <option value="Talk">
                            <option value="Others (Please specify)"> 
                        </datalist>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-4">
                        <label for="startdate">Start Date</label>
                        <input type="date"  class="form-control" placeholder="Select Date" name="startdate">
                    </div>
                    <div class="col-sm-4">
                        <label for="enddate">End Date</label>
                        <input type="date"  class="form-control" placeholder="Select Date" name="enddate" id="noEndDate">
                        <input onclick="document.getElementById('noEndDate').disabled = true;" type="checkbox" name="type">No end date
                    </div>
                </div>

                <div class="form-group">
                    <div class="panel-body table-responsive">
                        <table class="table table-hover table-bordered">
                            <thead>
                                <tr>
                                    <th>Start Time</th>
                                    <th>End Time</th>
                                    <th>Mon</th>
                                    <th>Tue</th>
                                    <th>Wed</th>
                                    <th>Thu</th>
                                    <th>Fri</th>
                                    <th><input type="button" class="btn btn-warning" value="Add Timeslot" onClick="addRow('dataTable')" /></th>
                                </tr>
                            </thead>
                            <tbody id="dataTable">
                                <tr>
                                    <td><input type="text" class="form-control" name="startTime[]"></td>
                                    <td><input type="text" class="form-control" name="endTime[]"></td>
                                    <td><input type="checkbox" name="Monday[]" value="1"></td>
                                    <td><input type="checkbox" name="Tuesday[]" value="1"></td>
                                    <td><input type="checkbox" name="Wednesday[]" value="1"></td>
                                    <td><input type="checkbox" name="Thursday[]" value="1"></td>
                                    <td><input type="checkbox" name="Friday[]" value="1"></td>
                                    <td><input type="button" class="btn btn-danger" value="Delete" onClick="deleteRow('dataTable')" /></td>
                                </tr>
                            </tbody>
                        </table>
                        <br/>

                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-4">
                        <input type="submit"  value="Add" class="btn btn-success">
                    </div>
                </div>
            </form> 

My codes for handleSchedule.php,

<?php

    $con = getDbConnect();

    $academicInstitution = $_POST['academicInstitution'];
    $levelofteaching = $_POST['levelofteaching'];
    $typeofteaching = $_POST['typeofteaching'];
    $startdate = $_POST['startdate'];
    $enddate = $_POST['enddate'];

                if (mysqli_connect_errno($con)) {
                    echo "Failed to connect to MySQL: " . mysqli_connect_error();
                } else {
                    if ($_POST['startTime']) {
                    foreach ($_POST["startTime"] as $key => $value) {

                            $endTime = $_POST["endTime"][$key];
                            $monday = $_POST["Monday"][$key];
                            $tuesday = $_POST["Tuesday"][$key];
                            $wednesday = $_POST["Wednesday"][$key];
                            $thursday = $_POST["Thursday"][$key];
                            $friday = $_POST["Friday"][$key];
                           

                            $sql = "INSERT INTO timetableschedule (academicInstitution, lvteaching, tyteaching, startdate, endate, startTime, endTime, Monday, Tuesday, Wednesday, Thursday, Friday) " .
                                    "VALUES ('$academicInstitution', '$levelofteaching', '$typeofteaching', '$startdate', '$enddate', '$value', '$endTime', '$monday', '$tuesday', '$wednesday', '$thursday', '$friday')";
                            mysqli_query($con, $sql);
                    }
                    }

                    echo "1 record added";
                    mysqli_close($con);
                }
                ?>

I am suspecting that the unchecked checkbox are causing the problem. Do anyone have any idea to solve it?