lundi 31 juillet 2017

Struts 1.x to Struts 2.x Migration issues in passing Java Method Parameters from JSP to Action Class

I am working on Struts 1.x to Struts 2.x migration and I am facing issues where some method is not able to pass parameter to setter method written in Action Form class from JSP page.

For your reference please find the POJO class :

import java.io.Serializable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * The Class ShareFeedbackForm.
 */

    public class ShareFeedbackForm implements Serializable {


        /**
         * 
         */
        private static final long serialVersionUID = 5070305198069278831L;

        private static final Log LOG = LogFactory.getLog(ShareFeedbackForm.class);

        /** The section. */
        private String section;

        /** The department. */
        private String department;

        /** The kst. */
        private String kst;

        /** The physical path. */
        private String physicalPath;

        /** The dfs path. */
        private String dfsPath;

        /** The share owner. */
        private String shareOwner;

        /** The share mgr. */
        private String shareMgr;

        /** The share id. */
        private String shareId;

        /** The revision id. */
        private String revisionId;

        private String revisionName;

        private String revisionDate;

        private String writeAccess; 

        private String headerCheck;

        private String reviewer ;

        private String reviewedOn;

        private String orderId ;

        private String uamTeamAccess;

        private String completed;

        private String lockedRev;

        private String sharePath;

        private String isSent;

        private String errorInfo;

        /**
         * @return the isSent
         */
        public String getIsSent() {
            return isSent;
        }


        /**
         * @param isSent the isSent to set
         */
        public void setIsSent(String isSent) {
            this.isSent = isSent;
        }


        public String getSharePath() {
            return sharePath;
        }


        public void setSharePath(String sharePath) {
            this.sharePath = sharePath;
        }


        /**
         * @return the lockedRev
         */
        public String getLockedRev() {
            return lockedRev;
        }


        /**
         * @param lockedRev the lockedRev to set
         */
        public void setLockedRev(String lockedRev) {
            this.lockedRev = lockedRev;
        }


        /**
         * @return the completed
         */
        public String getCompleted() {
            return completed;
        }


        /**
         * @param completed the completed to set
         */
        public void setCompleted(String completed) {
            this.completed = completed;
        }


        /**
         * @return the headerCheck
         */
        public String getHeaderCheck() {
            return headerCheck;
        }


        /**
         * @param headerCheck the headerCheck to set
         */
        public void setHeaderCheck( String headerCheck ) {
            this.headerCheck = headerCheck;
        }


        /** The Attachment List to String. */
        private String strAttachment;

        /** The Attachment Report. */
        private List<String> attachmentReport = new ArrayList<String>();

        /** The LstSecWin Report. */
        private List<String> lstSecWinReport;

        /** The String LstSecWin Report */
        private String strLstSecWinReport;

        /** The additional comments. */
        private String additionalComments;

        /** The sfhf lst. */
        private List<ShareFeedbackHelperForm> sfhfLst;

        private Set<String> checkedAllIds = new HashSet<String>();

        private Map<Long,String> checkedRemarks = new HashMap<Long, String>();

        public Set<String> getCheckedAllIds() {
            return checkedAllIds;
        }


        public void setCheckedAllIds( Set<String> checkedAllIds ) {
            this.checkedAllIds = checkedAllIds;
        }


        public Map<Long, String> getCheckedRemarks() {
            return checkedRemarks;
        }


        public void setCheckedRemarks(Map<Long, String> checkedRemarks) {
            this.checkedRemarks = checkedRemarks;
        }

        public String getCheckAll( String id ) {
            String h = "";
            try {
                h = String.valueOf( this.checkedAllIds.contains( id ) );
            } catch ( Exception e ) {
               LOG.error(" Exception in getting the checked check boxes :",e);
            }
            return h;
        }


        public void setCheckAll( String id, String value ) {
            this.checkedAllIds.add( id );
        }

        public String getCheckAllRemarks( String id ) {
            String h = "";
            try {
                h = String.valueOf( this.checkedRemarks.get(Long.valueOf(id)) );
            } catch ( Exception e ) {
               LOG.error(" Exception in getting the checked remarks :"+e);
            }
            return h;
        }


        public void setCheckAllRemarks( String id, String value ) {
            this.checkedRemarks.put(Long.valueOf(id), value);
        }



        public String getRevisionDate() {
            return revisionDate;
        }


        public void setRevisionDate(String revisionDate) {
            this.revisionDate = revisionDate;
        }


        /**
         * Gets the revision id.
         *
         * @return the revision id
         */
        public String getRevisionId() {
            return revisionId;
        }

        /**
         * Sets the revision id.
         *
         * @param revisionId the new revision id
         */
        public void setRevisionId(String revisionId) {
            this.revisionId = revisionId;
        }



        public String getWriteAccess() {
            return writeAccess;
        }


        public void setWriteAccess(String writeAccess) {
            this.writeAccess = writeAccess;
        }


        /**
         * Gets the share id.
         *
         * @return the share id
         */
        public String getShareId() {
            return shareId;
        }

        /**
         * Sets the share id.
         *
         * @param shareId the new share id
         */
        public void setShareId(String shareId) {
            this.shareId = shareId;
        }

        /**
         * Gets the section.
         *
         * @return the section
         */
        public String getSection() {
            return section;
        }

        /**
         * Sets the section.
         *
         * @param section the section to set
         */
        public void setSection(String section) {
            this.section = section;
        }

        /**
         * Gets the department.
         *
         * @return the department
         */
        public String getDepartment() {
            return department;
        }

        /**
         * Sets the department.
         *
         * @param department the department to set
         */
        public void setDepartment(String department) {
            this.department = department;
        }

        /**
         * Gets the kst.
         *
         * @return the kst
         */
        public String getKst() {
            return kst;
        }

        /**
         * Sets the kst.
         *
         * @param kst the kst to set
         */
        public void setKst(String kst) {
            this.kst = kst;
        }

        /**
         * Gets the physical path.
         *
         * @return the physicalPath
         */
        public String getPhysicalPath() {
            return physicalPath;
        }

        /**
         * Sets the physical path.
         *
         * @param physicalPath the physicalPath to set
         */
        public void setPhysicalPath(String physicalPath) {
            this.physicalPath = physicalPath;
        }

        /**
         * Gets the dfs path.
         *
         * @return the dfsPath
         */
        public String getDfsPath() {
            return dfsPath;
        }

        /**
         * Sets the dfs path.
         *
         * @param dfsPath the dfsPath to set
         */
        public void setDfsPath(String dfsPath) {
            this.dfsPath = dfsPath;
        }

        /**
         * Gets the share owner.
         *
         * @return the shareOwner
         */
        public String getShareOwner() {
            return shareOwner;
        }

        /**
         * Sets the share owner.
         *
         * @param shareOwner the shareOwner to set
         */
        public void setShareOwner(String shareOwner) {
            this.shareOwner = shareOwner;
        }

        /**
         * Gets the share mgr.
         *
         * @return the shareMgr
         */
        public String getShareMgr() {
            return shareMgr;
        }

        /**
         * Sets the share mgr.
         *
         * @param shareMgr the shareMgr to set
         */
        public void setShareMgr(String shareMgr) {
            this.shareMgr = shareMgr;
        }

        /**
         * Gets the additional comments.
         *
         * @return the additionalComments
         */
        public String getAdditionalComments() {
            return additionalComments;
        }

        /**
         * Sets the additional comments.
         *
         * @param additionalComments the additionalComments to set
         */
        public void setAdditionalComments(String additionalComments) {
            this.additionalComments = additionalComments;
        }

        /**
         * Gets the sfhf lst.
         *
         * @return the sfhfLst
         */
        public List<ShareFeedbackHelperForm> getSfhfLst() {
            return sfhfLst;
        }

        /**
         * Sets the sfhf lst.
         *
         * @param sfhfLst the sfhfLst to set
         */
        public void setSfhfLst(List<ShareFeedbackHelperForm> sfhfLst) {
            this.sfhfLst = sfhfLst;
        }

        /**
         * Gets the str attachment.
         *
         * @return the strAttachment
         */
        public String getStrAttachment() {
            return strAttachment;
        }

        /**
         * Sets the str attachment.
         *
         * @param strAttachment the strAttachment to set
         */
        public void setStrAttachment(String strAttachment) {
            this.strAttachment = strAttachment;
        }

        /**
         * Gets the attachment report.
         *
         * @return the attachmentReport
         */
        public List<String> getAttachmentReport() {
            return attachmentReport;
        }

        /**
         * Sets the attachment report.
         *
         * @param attachmentReport the attachmentReport to set
         */
        public void setAttachmentReport(List<String> attachmentReport) {
            this.attachmentReport = attachmentReport;
        }



        public String getRevisionName() {
            return revisionName;
        }


        public void setRevisionName(String revisionName) {
            this.revisionName = revisionName;
        }



        /**
         * @return the reviewer
         */
        public String getReviewer() {
            return reviewer;
        }


        /**
         * @param reviewer the reviewer to set
         */
        public void setReviewer(String reviewer) {
            this.reviewer = reviewer;
        }



        /**
         * @return the reviewedOn
         */
        public String getReviewedOn() {
            return reviewedOn;
        }


        /**
         * @param reviewedOn the reviewedOn to set
         */
        public void setReviewedOn(String reviewedOn) {
            this.reviewedOn = reviewedOn;
        }


        /**
         * @return the orderId
         */
        public String getOrderId() {
            return orderId;
        }


        /**
         * @param orderId the orderId to set
         */
        public void setOrderId(String orderId) {
            this.orderId = orderId;
        }


        /**
         * @return the lstSecWinReport
         */
        public List<String> getLstSecWinReport() {
            return lstSecWinReport;
        }


        /**
         * @param lstSecWinReport the lstSecWinReport to set
         */
        public void setLstSecWinReport(List<String> lstSecWinReport) {
            this.lstSecWinReport = lstSecWinReport;
        }


        /**
         * @return the strLstSecWinReport
         */
        public String getStrLstSecWinReport() {
            return strLstSecWinReport;
        }


        /**
         * @param strLstSecWinReport the strLstSecWinReport to set
         */
        public void setStrLstSecWinReport(String strLstSecWinReport) {
            this.strLstSecWinReport = strLstSecWinReport;
        }


        /**
         * @return the uamTeamAccess
         */
        public String getUamTeamAccess() {
            return uamTeamAccess;
        }


        /**
         * @param uamTeamAccess the uamTeamAccess to set
         */
        public void setUamTeamAccess(String uamTeamAccess) {
            this.uamTeamAccess = uamTeamAccess;
        }


        /**
         * @return the errorInfo
         */
        public String getErrorInfo() {
            return errorInfo;
        }


        /**
         * @param errorInfo the errorInfo to set
         */
        public void setErrorInfo(String errorInfo) {
            this.errorInfo = errorInfo;
        }

    }

Please find the JSP Snippet where the method is called in s:checkbox and s:textarea name attribute :

<s:checkbox name="webform.checkAll(%{#attr.shrFeedbackHelperForm.groupId})" cssClass="grpCheckBox" id="idchk%{#attr.shrFeedbackHelperForm.groupId}"
                                onclick="javascript:changeColor('rowidchk%{#attr.shrFeedbackHelperForm.groupId}','idchk%{#attr.shrFeedbackHelperForm.groupId}')"></s:checkbox>

Textarea :

<s:textarea  name="webform.checkAllRemarks(%{#attr.shrFeedbackHelperForm.groupId})" style="height:50px;" rows="1" cols="20" value ="%{#variable}" id="%{#shrFeedbackHelperForm.groupId}"></s:textarea>

As per the POJO class, these setter variables are never set in Struts 2.x where its happening fine in Struts 1.x. Googling does not yield my requirements. Any help providing good pointers and suggestions will be much appreciated.

Thanks




Check Excel VBA Checkbox with Python 2.7

I am using Python 2.7 to attempt to check VBA checkboxes in an Excel document. I generally use pywin32 in order to do this, but these checkboxes seem to be purely VBA objects not tied to a cell. I have used the following script to attempt to read the names of the checkboxes so I can assign Value:

import win32com.client as win32
import os
import ctypes.wintypes


CSIDL_PERSONAL = 5       
SHGFP_TYPE_CURRENT = 0
buf= ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
ctypes.windll.shell32.SHGetFolderPathW(None, CSIDL_PERSONAL, \
                                       None, SHGFP_TYPE_CURRENT, buf)
dirstart = buf.value
changedir = dirstart + '\Xcel Docs'
os.chdir(changedir)
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.Interactive = False
excel.Visible = False
wb = excel.Workbooks.Open(r'\\dv-panzura\dv-home$\jswordy\Documents\Xcel 
Docs\Copy of Work Order InfoSheetEx - 2-16-16.xls')
ws = wb.Worksheets("WO Cover Sheet")
for cb in ws.CheckBoxes():
    print cb.Name

Unfortunately this returns an error only:

Traceback (most recent call last): File "C:\Python27\ArcGIS10.3\Scripts\infosheet.pyw", line 18, in ws = wb.Worksheets("WO Cover Sheet") File "C:\Users\jswordy\AppData\Local\Temp\gen_py\2.7\00020813-0000-0000-C000-000000000046x0x1x9\Sheets.py", line 120, in call ret = self.oleobj.InvokeTypes(0, LCID, 2, (9, 0), ((12, 1),),Index com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)

Which seems to indicate it cannot locate these items (probably because they are not linked to cells). Would anyone have any idea how to check these checkboxs? Perhaps editing the VBA to have the objects checked? Any ideas would be appreciated.




Searching by checkboxes with if statements in SQL not bringing back correlated results

I am working on an application with about 20 text boxes and 26 checkboxes which is quite a load I know , but is necessary for the task.Currently I am struggling to be able to search by multiple checkboxes at the same time. I was wondering if there would be any easier way to go about this logically without a ton of if statements.

Here is my current SQL select statement:

`string str = "select * from engineering where JobNumber like '%' + @search + '%' AND DateOrdered like '%' + @search1 + '%' AND Title like '%' + @search2 + '%' AND PhysicalAddressComplete like '%' + @search3 + '%' AND County like '%' + @search4 + '%' AND Client like '%' + @search5 + '%' AND Contact like '%' + @search6 + '%' AND ContactTitle like '%' + @search7 + '%' AND MailingAddressComplete like '%' + @search8 + '%' AND BusinessPhone like '%' + @search9 + '%' AND CellPhone like '%' + @search10 + '%' AND Email like '%' + @search11 + '%' AND OpenStatus like '%' + @search12 + '%' AND CloseStatus like '%' + @search13 + '%' AND Cabinet like '%' + @search14 + '%' AND Roll like '%' + @search15 + '%' AND Drawer like '%' + @search16 + '%' AND ConstructionDrawings like '%' + @search17 + '%' AND Fee like '%' + @search18 + '%' AND ConstructionCost like '%' + @search19 + '%' AND ProjectDescription like '%' + @search20 + '%' ";
            if (chkEducational.Checked)
                str += "AND Education = @Education";
            else if (chkMedical.Checked)
                str += "AND Medical = @Medical";
            else if (chkReligious.Checked)
                str += "AND Religious = @Religious";
            else if (chkMulti.Checked)
                str += "AND MultiFamily = @MultiFamily";
            else if (chkStudent.Checked)
                str += "AND Student = @Student";
            else if (chkAssisted.Checked)
                str += "AND Assisted = @Assisted";
            else if (chkSingleFamily.Checked)
                str += "AND Single = @Single";
            else if (chkBridge.Checked)
                str += "AND Bridge = @Bridge";
            else if (chkIntersection.Checked)
                str += "AND Intersection = @Intersection";
            else if (chkRoadway.Checked)
                str += "AND Roadway = @Roadway";
            else if (chkDesign.Checked)
                str += "AND DesignBuild = @DesignBuild";
            else if (chkTransOther.Checked)
                str += "AND TransportationOther = @TransportationOther";
            else if (chkRetailSmall.Checked)
                str += "AND SmallRetail = @SmallRetail";
            else if (chkRetailLarge.Checked)
                str += "AND LargeRetail = @LargeRetail";
            else if (chkParks.Checked)
                str += "AND Parks = @Parks";
            else if (chkIndustrial.Checked)
                str += "AND Industrial = @Industrial";
            else if (chkUtility.Checked)
                str += "AND Utility = @Utility";
            else if (chkGCSmall.Checked)
                str += "AND GCSmall = @GCSmall";
            else if (chkGCLarge.Checked)
                str += "AND GCLarge = @GCLarge";
            else if (chkOffice.Checked)
                str += "AND Office = @Office";
            else if (chkOther.Checked)
                str += "AND Other = @Other";
            else if (chkMunicipal.Checked)
                str += "AND Municipal = @Municipal";
            else if (chkPrivate.Checked)
                str += "AND Privates = @Privates";
            else if (chkInstitutional.Checked)
                str += "AND Institutional = @Institutional";
            else if (chkMilitary.Checked)
                str += "AND Military = @Military";
            else if (chkArchive.Checked)
                str += "AND Archived = @Archived";`

This statement works as I am able to search by any amount of text as well as checkboxes however when it comes to checkboxes some records do not correlate to the searches. For example if I was to check the Archive checkbox along with the Military Checkbox , I would want the results to be only those with BOTH of those boxes checked, however when I do this with my code I also get the records with only the military box checked as well. It seems as if the Else If statement acts as a pecking order. Any help would be appreciated.




Dynamic Checkbox in JFrame/Swing

I want to populate List of tables as a dynamic checkbox using Jframe/Swing in netbeans. The count of table is not known as i am giving USER to select DB as well. Please help, below is code which is for populating list of tables as combo box

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here: String dbValue=(String)jComboBox2.getSelectedItem(); String Connection = jTextField1.getText(); String User = jTextField2.getText(); char[] pwd = jPasswordField1.getPassword(); // TODO Auto-generated method stub //bt2.setEnabled(false); Object ob=evt.getSource(); if (ob == jButton2) {

           /* String Connection = tf1.getText();
            String User = tf2.getText();
            char[] pwd = p1.getPassword();*/
            System.out.println("**************");
            try
               {
                String passwrd=String.valueOf(pwd);
                    Class.forName("oracle.jdbc.driver.OracleDriver");
                    Connection con = DriverManager.getConnection(Connection,User,passwrd);
                    Statement st=con.createStatement();
                        ResultSet rs2= st.executeQuery("SELECT Count(*) FROM DBA_TABLES where owner='"+dbValue+"'");
                    if(rs2.next()){
                         count=rs2.getInt(1);

                    }
                    generateCheckboxesDynamically(count);
                    System.out.println("Count="+count);
                    ResultSet rs1=st.executeQuery("select table_name from dba_tables where owner='"+dbValue+"'");

                    while(rs1.next())
                    {
                           for(int i=1;i<=count;i++){ 
                           JCheckBox jCheckBoxMenu=new JCheckBox("check"+i);

                           jCheckBoxMenu.setText(rs1.getString(1));
                           add(jCheckBoxMenu);
                           checks.add(jCheckBoxMenu); 
                           jCheckBoxMenu.setVisible(true);
                           }
                           pack();
                            //JCheckBox ma=new JCheckBox; 
                        String name = rs1.getString(1);
                        if (name.equals("")) {
                                        jComboBox1.removeAll();
                        jComboBox1.addItem("");
                        jComboBox1.setVisible(false);
                        } 
                        else {
                        jComboBox1.addItem(rs1.getString(1));

                        System.out.println(rs1.getString(1));
                        jComboBox1.setVisible(true);
                        }
                            jTextField1.setEnabled(false);
                            jTextField2.setEnabled(false);
                            //tf3.setEnabled(false);
                          jButton1.setEnabled(false); 
                     }
                    //String dbValue=(String)jComboBox1.getSelectedItem();
                    System.out.println("Selected DB=="+dbValue);
                    //bt2.setEnabled(true);
                    //bt1.removeActionListener(this);
               } 
                    catch (Exception ex) 
                    {
                        System.out.println(ex);
                    }
               }

}                                        




Do you know a pretty way to show/disable input by check one radio and one/several checkboxes with jQuery?

I get a lot of extra code, please give me link at least.

<input type="radio" name="first" value="1">
<input type="radio" name="first" value="2">
<input type="checkbox" name="second" value="1">
<input type="checkbox" name="second" value="2">
<input name="text">




check box with tableview in swift

I am new to swift programming

enter image description here

Tableview with two check boxes [out ,Absent] check /uncheck working fine.

Note1: out/absent any one of the check box checked after array data append and pass the data to function,

out =>checked==> Array data append ==> Data pass to function

absent =>checked==> data append ==> Data pass to function

individival working well.

note 2: if I can click the Out box, out box data append to array and pass to function
immediately I want change the check box of Absent then clear the Appended out Data and send the Absent data to the function

out==>checked===>data append==>changetoAbsent==>cleartheoutdata=>>append the Absent data

pls help me .....!

this is the code

var InCheckec = [Bool]()

var OutCheckec = [Bool]()

var AbsentCheckec = [Bool]()

var upStudentId = [String]()

var upAttendanceID = [String]()

var upStatus : String = ""

var upStaffId : String  = ""

var UPstatusTest = [String]()

var inButtoncount : Int = 0

@IBAction func InButttonClick(_ sender: UIButton) {

        status = "1"

        snackbar.backgroundColor = UIColor(red: CGFloat(0x00)/255
            ,green: CGFloat(0xB1)/255
            ,blue: CGFloat(0xB1)/255
            ,alpha: 1.0)

        let prefs:UserDefaults = UserDefaults.standard
        StaffID = prefs.value(forKey: "STAFFID") as! String


        let position: CGPoint = sender.convert(CGPoint(x: 10, y: 20), to: self.TableView)
        let indexPath = self.TableView.indexPathForRow(at: position)
        let _: UITableViewCell = TableView.cellForRow(at: indexPath!)!

        _ = (indexPath! as NSIndexPath).row

        let buttontag = sender.tag

        if (sender.isSelected == true)
        {
            InCheckec[buttontag] = false

            inButtoncount -= 1

            if(inButtoncount == 0)
            {
                snackbar.dismiss()
                upStaffId.removeAll()
                upStudentId.removeAll()
                upAttendanceID.removeAll()

            }
            else{

                upStudentId.removeLast()
                upAttendanceID.removeLast()
                UPstatusTest.removeLast()

            }
        }

        else
        {

            snackbar.backgroundColor = UIColor(red: CGFloat(0x00)/255
                ,green: CGFloat(0xB1)/255
                ,blue: CGFloat(0xB1)/255
                ,alpha: 1.0)

            InCheckec[buttontag] = true

            inButtoncount += 1
            currentSnackbar = snackbar
            snackbar.show()


            let kid = attendanceInfo[(indexPath?.row)!] as AttendanceInfo


            upStudentId.append(kid.studentId!)
            upAttendanceID.append(kid.attendanceId)
            UPstatusTest.append(status)
            upStaffId = StaffID

        }

        self.TableView.reloadRows(at: [indexPath!], with: UITableViewRowAnimation.none)

    }

    @IBAction func OUTBUTTON(_ sender: UIButton) {
        snackbar.backgroundColor = UIColor(red: CGFloat(0x00)/255
            ,green: CGFloat(0xB1)/255
            ,blue: CGFloat(0xB1)/255
            ,alpha: 1.0)


        status = "2"

        let buttontag = sender.tag

        let position: CGPoint = sender.convert(CGPoint(x: 10, y: 20), to: self.TableView)
        let indexPath = self.TableView.indexPathForRow(at: position)



        if (sender.isSelected == true)

        {

            OutCheckec[buttontag] = false
            inButtoncount -= 1


            if(inButtoncount == 0)
            {
                snackbar.dismiss()
                upStudentId.removeAll()
                upAttendanceID.removeAll()
                UPstatusTest.removeAll()
            }
            else{

                upStudentId.removeLast()
                UPstatusTest.removeLast()
                upAttendanceID.removeLast()

            }

        }
        else
        {


            OutCheckec[buttontag] = true
            AbsentCheckec[buttontag] = false
            print("buttontab value",buttontag)


            inButtoncount += 1
            snackbar.show()

            let kid = attendanceInfo[(indexPath?.row)!] as AttendanceInfo

            upStudentId.append(kid.studentId!)
            upAttendanceID.append(kid.attendanceId)
            UPstatusTest.append(status)
            upStaffId = StaffID

        }



        self.TableView.reloadRows(at: [indexPath!], with: UITableViewRowAnimation.none)

    }


    @IBAction func ABSENTBUTTON(_ sender: UIButton) {

        status = "3"
        snackbar.backgroundColor = UIColor(red: CGFloat(0x00)/255
            ,green: CGFloat(0xB1)/255
            ,blue: CGFloat(0xB1)/255
            ,alpha: 1.0)

        let buttontag = sender.tag
        let position: CGPoint = sender.convert(CGPoint(x: 10, y: 20), to: self.TableView)
        let indexPath = self.TableView.indexPathForRow(at: position)



        if (sender.isSelected == true)

        {

            AbsentCheckec[buttontag] = false

            inButtoncount -= 1


            if(inButtoncount == 0)
            {
                snackbar.dismiss()
                upStudentId.removeAll()
                upAttendanceID.removeAll()
                UPstatusTest.removeAll()
            }
            else{

                upStudentId.removeLast()
                UPstatusTest.removeLast()
                upAttendanceID.removeLast()

            }


        }
        else
        {
            AbsentCheckec[buttontag] = true

            OutCheckec[buttontag] = false

            inButtoncount += 1
            snackbar.show()

            let kid = attendanceInfo[(indexPath?.row)!] as AttendanceInfo


            upStudentId.append(kid.studentId!)
            upAttendanceID.append(kid.attendanceId)
            UPstatusTest.append(status)
            upStaffId = StaffID



        }
        self.TableView.reloadRows(at: [indexPath!], with: UITableViewRowAnimation.none)

    }

snack bar for perform send Action data pass to function

 lazy var snackbar = TTGSnackbar(message: "Attendance Update !", duration: .long, actionText: "SEND") { (snackbar) in

        self.activityIndicatorView.startAnimating()

        self.updateArray(_upstatus:UPstatusTest,UPStudentId:upStudentId,UPAttendanceID:upAttendanceID,UPStaffId:upStaffId,inBcount:inButtoncount)

        UPstatusTest.removeAll()
        upStudentId.removeAll()
        upAttendanceID.removeAll()
        inButtoncount = 0


    }

After append data pass to function

func updateArray(_upstatus:[String],UPStudentId:[String],UPAttendanceID:[String],UPStaffId:String,inBcount:Int)
{

    for i in 0..<inBcount

    {

        var errorCode = "1"

        _ = "Failed"



        var request = URLRequest(url: URL(string: "updateattendance",
                                          relativeTo: URL(string: serverURL+"/rkapi/api/"))!)

        let session = URLSession.shared


        request.httpMethod = "POST"

        let bodyData = "status=\(_upstatus[i])&staffId=\(UPStaffId)&studentId=\(UPStudentId[i])&attendanceId=\(upAttendanceID[i])"

        print("body data \(bodyData)")

        request.httpBody = bodyData.data(using: String.Encoding.utf8);
        let task = session.dataTask(with: request, completionHandler: { (data, response, error) in

            do {

                if data != nil {

                    if let jsonData = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary {


                        errorCode = String(describing: jsonData["errorCode"]!)


                        if(errorCode == "0")
                        {

                            self.getAttendances()

                        }


                    }


                }

                else {

                    self.displayAlert("Raksha Data", message: "Data Not Available. Please try again")

                }

            } catch _ as NSError {

            }

        })

        task.resume()

    }

}




Check whether a list of checkboxes are all disabled

I have a list of checkboxes List<CheckBox> checkBoxesList = new List<CheckBox>(); and I am having trouble figuring out how to figure out when all 4 checkboxes, that I have, are all disabled.

Here is what I have.

        public void CheckIfBoxHasBeenSelected()
    {
        List<CheckBox> checkBoxesList = new List<CheckBox>();
        checkBoxesList.Add(checkBox1);
        checkBoxesList.Add(checkBox2);
        checkBoxesList.Add(checkBox3);
        checkBoxesList.Add(checkBox4);


        foreach (CheckBox item in checkBoxesList)
        {
            if (item.Checked)
            {
                item.Enabled = false;
            }
        }
    }

Thank you for advice




Show on 'checked'

Explain me please what's wrong with this example: http://ift.tt/2hh4XXk

<label id="formSecondPhone"><input type="checkbox" name="secondContact" value="1"> Phone</label> 
<label id="formSecondPhoneField" class="form-item">Enter your number: <input type="number" name="secondPhone"></label>

#formSecondPhoneField { display: none; }

$('label#formSecondPhone:first-child').change(function() {
    var id = $('#formSecondPhoneField');
    $(this).attr('checked') ? $(id).show() : $(id).hide();
});

It's just add display:none; to my field and do nothing else, but i need a toggle effect.




WPF: Limit clickable area of checkbox to the checkbox only

I am using a checkbox as follows:

<CheckBox Content="Reload Code Table Rules"
          IsChecked="{Binding ReloadCodeTableRules, UpdateSourceTrigger=PropertyChanged}"
          VerticalAlignment="Center" />

Currently the checked state will change if I click on either the checkbox or the label. Is it possible to limit this to only change when the checkbox is checked?




PHP form, input values and check box to mysql table

I am trying to create sign up form, where it has input values (name, email, phone, ..) and have multiple checkbox option.

I also create table in mysql database for each checkbox. My goal is to values entered in input will only go to selected checkbox database.

At first, I had perfectly working input values to go table in database, but when I added checkbox and try to direct by selected checkbox, I mess everything up.

input.php

<html>
<head>
  <title>post submit</title>    
</head>
<script type="text/javascript">
function toggle(source) {
  checkboxes = document.getElementsByName('chk1[]');
  for(var i=0, n=checkboxes.length;i<n;i++) {
    checkboxes[i].checked = source.checked;
  }
}
</script>
<body>
<h2><font color="white">Welcome to Cars and Coffee</h2>
<p>Sign up to receive if you are interested in 
    receiving information from Cars and Coffee.</p>
<p>Please select at least one option</p>
<form name="newEntry" action="page.php" method="POST">
name<input type=text length=60 size=30 name="name"><br>
email<input type=text length=60 size=30 name="email"><br>
car<input type=text length=60 size=30 name="car"><br>
phone<input type=text length=60 size=30 name="phone"><br>
<input type="submit" name="submit" email="add" car="add" phone="add" >

</form>

<form action="checkbox.php" method="POST">

<input type="checkbox" name="chk1[]" value="MT">Cars  & Coffee<br>
<input type="checkbox" name="chk1[]" value="MT">Kentucky Derby Party<br>
<input type="checkbox" name="chk1[]" value="MT">July 4th<br>
<input type="checkbox" name="chk1[]" value="MT">Labor Day<br>
<input type="checkbox" name="chk1[]" value="MT">New Years Day<br>
<input type="checkbox" name="chk1[]" value="MT" onClick="toggle(this)">Select All<br>

</form>
<?php
mysql_connect("localhost", "db", "pw");
mysql_select_db("hpfarmne_events");
$qh = mysql_query("select * from  new_email_list order by id desc");
if (@mysql_num_rows($qh)) { /* the if(@...) syntax makes PHP supress any
warnings that might come out of that function. */
        /* mysql_fetch_object(query handle);
         * returns an object whose contents are that of one rotw in the
database. */
        while ($obj = mysql_fetch_object($qh)) {
                echo "
<p>
$obj->email<br>
$obj->name<br>
$obj->car<br>
$obj->phone<br>
<p>
<hr>
";
       }
}
?>  
</body>
</html>

page.php

<?php
mysql_connect("localhost", "db", "pw");
mysql_select_db("hpfarmne_events");
mysql_query("insert into new_email_list (name, email, car, phone) values ('".$_POST['name']."','".$_POST['email']."','".$_POST['car']."', '".$_POST['phone']."' )");
?>
<html>
<head>
<meta http-equiv=refresh content="0; URL=./input.php">
</head>
</html>

checkbox.php

<?php
include("page.php");
$checkbox1 = $_POST["chk1"];

if($_POST["Submit"] == "Submit") {

    for (i=0; $<sizeof($checkbox1); $i++){
        $query = "INSERT INTO  (name) VALUES( '".$checkbox1[i].'")";
        mysql_query($query) or die(mysql_error());
    }
    echo "Record  is inserted";
}
?>




Input text multi value

I want to make an website, and to write something in one text input and when a checkbox is checked and the submit button is pressed to write in textarea the checkbox + input text + the same checkbox text, I want to make this with an variable.My script is:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
<script>
    function myPing() {
    var coffee = document.forms[0];
    var txt = "";
    var i;
    for (i = 0; i < coffee.length; i++) {
        if (coffee[i].checked) {
            txt = txt + coffee[i].value + " ";
        }
    }
    var variabilamea123 = document.getElementById("prefix12343242342")
    var theprefix = variabilamea123.value;
    var myvariable12345 = `Hello guys ` + theprefix + ` This was the prefix!`

document.getElementById("order").value = txt + theprefix;
}
</script>
</head>
<div>
<body>
    <center><h1>Discord Easy bot maker</h1></center>
<center>
    <form>
        <h3>Write here your prefix:</h3>
        <input type="text" maxlength="23" name="prefix123" id="prefix12343242342"><br>
        <input type="button" onclick="myPing()" value="Update the prefix"></input>
        <br>
<input type="checkbox" name="coffee" value= myvariable12345>Playing a game<br>
<input type="checkbox" name="coffee" value="                                                                                                                                                                                               client.on('ready', () =>  { 
    client.user.setGame('d!help')
});
});">Playing a game!<br>
<br>
<textarea id="order" rows="40" cols="200">
</textarea>
<br>
</form>
</center>
</div>    
</body>
<style>
    body {
    background-color: #8493f4;
}
h1 {
    font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
}
    </style>
</html>



Validate checkbox that which are required

I'd like to create terms and conditions form in my angularjs project.

From multiple checkboxes only several are required, and I'd like to enable submit button, only when all required checkboxes are checked.

Here is my checkboxes:

<label class="agreement-label control-label required">Zgoda</label>
<input class="agreements ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required" id="agreement_1" name="agreement" required="" ng-model="client.agreement[0]" type="checkbox">

<label class="agreement-label control-label">Zgoda 2</label>
<input class="agreements ng-pristine ng-untouched ng-valid ng-not-empty" id="agreement_2" name="agreement" ng-model="client.agreement[1]" type="checkbox">

<label class="agreement-label control-label">Zgoda 4</label>
<input class="agreements ng-pristine ng-untouched ng-valid ng-not-empty" id="agreement_5" name="agreement" ng-model="client.agreement[4]" type="checkbox">

<label class="agreement-label control-label required">Zgoda 5</label>
<input class="agreements ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required" id="agreement_6" name="agreement" required="" ng-model="client.agreement[5]" type="checkbox">

<button class="btn btn-success" id="ticketFormSubmit" ng-disabled="isAgreementsInvalid()" ng-click="changeButtonValue()" type="submit" disabled="disabled">Zapisz</button>

And in my angular controller:

$scope.isAgreementsInvalid = function() {
    return $scope.ticketForm.agreement.$invalid;
}

The problem is, only last required checkbox is validating.




Positioning checkboxes inline in ionic

I need to position two checkboxes inline next to each other with their belonging label on the left of each checkbox. Here is picture for better understanding: (on picture there is an e-mail checkbox which does not exist in app so just ignore it, there should be only two checkboxes)

enter image description here

Everything I tried so far didn't gave me wanted output so this is a code which I have now in the app. This is in my form element:

  <ion-item>
    <ion-label text-uppercase>Phone Calls</ion-label>
    <ion-checkbox name="receive_calls"
      [ngModel]="(contact$ | async).receive_calls">
    </ion-checkbox>
  </ion-item>
  <ion-item>
    <ion-label text-uppercase>Text Messages</ion-label>
    <ion-checkbox name="receive_messages"
      [ngModel]="(contact$ | async).receive_messages">
    </ion-checkbox>
  </ion-item>

I won't provide style code because it does not work at the moment.




PHP prechecked check boxes from a String

Hello
I would like to tell you that I know there are lots of solved example on stack overflow regarding the same issues.But mine is different and complex.

I have Php Variable that has comma separated values like "car_ferrari,car_jaguar,car_lamborghini" and I have multiple check-boxes
enter image description here     name='car [ ] '      value = ' car_ferrari '   
enter image description here     name='car [ ] '      value = ' car_lamborghini '   
enter image description here     name='car [ ] '      value = ' car_hummer '   
enter image description here     name='car [ ] '      value = ' car_jaguar '   
enter image description here     name='car [ ] '      value = ' car_aston '   

I want to checked the checbox if this variable has the same value of string.
Like checkbox with the value of car_ferrari,car_jaguar,car_lamborghini should be checked
I have large number of these types of variables as well as large number of checkboxes array.I know I can use explode and then in_array() but it is really time consuming to put condition in for each and every checkbox for around 400 checkboxes.

if Jquery will help to sort it out ,I will use it but give me the appropriate answer.Ask me incase of query.
Thanks in advance.




dimanche 30 juillet 2017

I want to to set checkbox status in state parameter in angular js?

I am implementing checkbox and also I want to set status(true, false) in url as a parameter But only false value is set in url parameter. But When I click on checkbox then true value is not set in url as a parameter. I am using $location.search. I not able to find out what is the issue with true value.

var app = angular.module('demo', ['rzModule', 'ui.bootstrap']);
app.controller('MainCtrl', function($scope, $rootScope, $timeout) {    
  $scope.confirm = function(){
  alert($scope.checkboxModel.value);
  $location.search({checkbox: $scope.checkboxModel.value});           
}          
})
<link href="http://ift.tt/1FHelXo" rel="stylesheet"/>
   
<script src="http://ift.tt/1MeTcXW"></script>
<script src="http://ift.tt/2vbLpZF"></script>
<script src="http://ift.tt/2rcl0tm"></script>
   
<div ng-app="demo">
  <div ng-controller="MainCtrl" class="wrapper">
  checkbox status should set in url as parameter
    <label>
              <input type="checkbox" ng-model="checkboxModel.value" data-ng-change="confirm()"/>
            </label>
  </div>
</div>



Sending checked checkbox ids to the database using jquery [duplicate]

This question already has an answer here:

I have a checklist that users need to check more than one checkbox and then I should calculate the total price of each chechbox and display it. The problem is I should insert the checked checkbox into the database. So when I am using isset() function I am having an error. So I am thinking to use jquery instead and sending the ids checked to the database but I don't know how to do it.




samedi 29 juillet 2017

How to pass state from checkboxes to a parent component?

I have a class (Cookbook) that passes a click handler "handleOnChange" to a child component (Filter). Filter renders checkboxes. On those checkboxes, I execute the handleOnChange. I want to update the state that exists in Cookbook, but even though handleOnChange is declared in Cookbook, it does not recognize this.state.selectedStaples. The error takes place in the handleOnChange function on the first non-console.log line. How do I update the state of selectedStaples in Cookbook?

Here is Cookbook

class Cookbook extends React.Component {
    constructor(){
        super(); 
        this.state ={
            cookbook: data,
            selectedStaples: [],
        }   
    }

    getStapleList(recipes){
        let stapleList = [];
        recipes.forEach(function(recipe){
            recipe.ingredient_list.forEach(function(list){
                stapleList.push(list.needed_staple);
            });
        });

        let flattenedStapleList = stapleList.reduce(function(a,b){
            return a.concat(b);
        })

        return flattenedStapleList
    }

    handleOnChange(staple, isChecked, selectedStaples) {
        console.log(staple);
        console.log(isChecked);
        console.log(selectedStaples);
        const selectedStaples = this.state.selectedStaples;
        // if (isChecked) {
        //     this.setState({
        //         selectedStaples: selectedStaples.push(staple)
        //     })
        // } else {
        //     this.setState({
        //         selectedStaples: selectedStaples.filter(selectedStaple => selectedStaple !== staple)
        //     })
        // }
    }

    render(){
        const selectedStaples = this.state.selectedState;
        const cookbook = this.state.cookbook;
        const stapleList = this.getStapleList(cookbook.recipes);
        return(
            <div className="cookbook">
                <div className="filter-section">
                    <h1>This is the filter section</h1>
                    <Filter stapleList = {stapleList} onChange={this.handleOnChange}/>
                </div>
                <div className="recipes">
                    <h1>This is where the recipes go</h1>
                    <div className="recipe">    
                        <Recipe cookbook = {cookbook}/>
                    </div>

                </div>
            </div>
        );
    }
}

and Filter

class Filter extends React.Component {


    render(){
        const stapleList = this.props.stapleList;
        const checkboxItems = stapleList.map((staple, index) => 
            <div key = {index}>
                <label>
                    <input
                        type="checkbox"
                        value="{staple}"
                        onClick={e => this.props.onChange(staple, e.target.checked)}
                    />
                    {staple}
                </label>
            </div>
        );
        return (
            <form>
                {checkboxItems}
            </form>
        );
    }
}




Argument 1: cannot convert from 'method group' to 'ListViewItem'

I am trying to add a checked-box to a listview using C#. Something that seems to be straight forward has stopped me dead for the last few days. All is well until I want to add an event handler to the change of the check box.

    private void InitializeComponent()
    {
            this.components = new System.ComponentModel.Container();
            // more componets....
            // more componets.......
            // more componets.......

            this.listView1.SelectedIndexChanged += new System.EventHandler(this.listView1_SelectedIndexChanged);
            this.listView1.ItemChecked += new ItemCheckedEventArgs(this.listView1_ItemCheckChanged);
            // more componets....
    }

    private void listView1_ItemCheckChanged(object sender, System.Windows.Forms.ItemCheckedEventArgs e)
    {

        ListViewItem item = e.Item as ListViewItem;

        if (item != null)
        {
            if (item.Checked)
            {
                item.Checked = false;

            }
            else
            {
                item.Checked = true;

            }
        }
    }




Create a custom Pop Up - Android

I looking for a lib or a way to create a custom pop up in android like the image in description. Pop up must have a checkbox, an image icon, a textview if possible searchable. There's a way to create that or a lib like that?

pop up




I have to send checkbox values to my email

I have to send checkbox values to my email. Now, I'm really, really, REALLY new to php, so I need help. On the page where checkboxes are I have a basic form (your name, last name, phone number, and address) that is also sent to an email, using PHPMailer. But now I have to send that form and checkbox values as a one mail. I already have HTML code for checkboxes and that basic form, and php code to send that form, but I don't know how to include checbox values to that php code. Can anybody help?

My HTML:

<?php
session_start();
require_once'helpers/security.php';
$errors=isset($_SESSION['errors'])?$_SESSION['errors']:[];
$fields=isset($_SESSION['fields'])?$_SESSION['fields']:[];
?>
<!doctype html>
<html>
<head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="css.css">
        <script src="jquery-3.1.1.min.js"></script>
        <title>Top Food-Smuti sam svoj smoothie</title>
    </head>
    <body>
    <header class="header">
<img src="tel.png" class="tel"><span class="broj">060 399 333 6</span> | <img src="email.png" class="mail"> <span class="email">topfoodbgd@gmail.com | <img src="lokacija.png" class="lokacija"> <span class="ulica">Knjeginje Zorke 2</span> | <img src="clock.png" class="sat"><span class="vreme"> 11:00-19:00 | </span> <span class="follow">Pratite nas:</span> <a href="http://ift.tt/2tMRkRa"><img src="facebook3.png" class="fb"></a>  <a href="http://ift.tt/2v9MpNW"><img src="instagram3.png" class="in"></a>  <a href="https://twitter.com/TopFoodBGD"><img src="twitter3.png" class="tw"></a>
</header>
    <div class="a">
     <div class="b"> 
         <ul>
             <li><a href="index.php">Dostava obroka</a></li>
             <li><a href="Dostava firme.html">Dostava obroka firmama</a></li>
             <li><a href="ketering za svecane prilike.html"> Ketering za svečane prilike</a></li>
             <li><a href="Kontakt.html">Kontakt</a></li>
         </ul>
     </div>
</div>
<input type="checkbox" name="Djumbir" value="Djumbir" class="sam">Đumbir<br/>
<input type="checkbox" name="Spanac" value="Spanac" class="sam">Spanać<br/>
<input type="checkbox" name="Brokoli" value="Brokoli" class="sam">Brokoli<br/>
<input type="checkbox" name="Kelj" value="Kelj" class="sam">Kelj<br/>
<input type="checkbox" name="Crveni pasulj" value="Crveni pasulj" class="sam">Crveni pasulj<br/>
<input type="checkbox" name="Cvekla" value="Cvekla" class="sam">Cvekla<br/>
<input type="checkbox" name="Celer" value="Celer" class="sam">Celer<br/>
<input type="checkbox" name="Sargarepa" value="Sargarepa" class="sam">Šargarepa<br/>
<input type="checkbox" name="Limeta" value="Limeta" class="sam">Limeta<br/>
<input type="checkbox" name="Krastavac" value="Krastavac" class="sam">Krastavac</br>
<input type="checkbox" name="Zelena jabuka" value="Zelena jabuka" class="smoothie">Zelena jabuka<br/>
<input type="checkbox" name="Avokado" value="Avokado" class="smoothie">Avokado<br/>
<input type="checkbox" name="Banana" value="Banana" class="sam">Banana<br/>
<input type="checkbox" name="Malina" value="Malina" class="sam">Malina<br/>
<input type="checkbox" name="Pomorandza" value="Pomorandza" class="sam">Pomorandža<br/>
<input type="checkbox" name="Mango" value="Mango" class="sam">Mango<br/>
<input type="checkbox" name="Aronija" value="Aronija" class="sam">Aronija<br/>
<input type="checkbox" name="Ananas" value="Ananas" class="sam">Ananas<br/>
<input type="checkbox" name="Badem" value="Badem" class="sam">Badem<br/>
<input type="checkbox" name="Orah" value="Orah" class="sam">Orah<br/>
<input type="checkbox" name="Ovsene pahuljice" value="Ovsene pahuljice" class="sam">Ovsene pahuljice<br/>
<input type="checkbox" name="Semenke bundeve" value="Semenke bundeve" class="sam">Semenke bundeve<br/>
<input type="checkbox" name="Chia seme" value="Chia seme" class="sam">Chia seme<br/>
<input type="checkbox" name="Lan" value="Lan" class="sam">Lan<br/>
<input type="checkbox" name="Cimet" value="Cimet" class="sam">Cimet<br/>
<input type="checkbox" name="Mirođija" value="Mirođija" class="sam">Mirođija<br/>
<input type="checkbox" name="Rukola" value="Rukola" class="sam">Rukola<br/>
<input type="checkbox" name="Nana" value="Nana" class="sam">Nana<br/>
<input type="checkbox" name="Cimet" value="Cimet" class="sam">Cimet<br/>
<input type="checkbox" name="Kokosovo ulje" value="Kokosovo ulje" class="sam">Kokosovo ulje<br/>
<input type="checkbox" name="Agava sirup" value="Agava sirup" class="sam">Agava sirup<br/>
        <div class="container">
            <div class="contact">
                <div class="panel">
                    <?php if(!empty($errors)):?>
                    <div class="panel">
                        <ul><li><?php echo implode('</li> <li>', $errors)?></li></ul>
                    </div>
                <?php endif; ?>
                </div>
                    </p>Zelite da porucite nesto od ovih proizvoda? Popunite formu i mi cemo pozvati vas!</p>
                <form action="contact4.php" method="post">
                    <div class="form-group">
                        <label for="name">Ime *</label>
                        <input type="text" name="name" autocomplete="off" class="form-control" placeholder="Upisite ime" <?php echo isset ($fields['name'])? 'value="'.e($fields['name']).'"':''?>>
                    </div>
                    <div class="form-group">
                        <label for="email">Prezime *</label>
                    <input type="text" name="email" autocomplete="off" class="form-control" placeholder="Upisite prezime"<?php echo isset ($fields['email'])? 'value="'.e($fields['email']).'"':''?>>
                    </div>
                     <div class="form-group">
                     <label for="email">Broj telefona *</label>
                    <input type="text" name="comment" autocomplete="off" class="form-control" placeholder="Upisite broj telefona"<?php echo isset ($fields['comment'])? 'value="'.e($fields['comment']).'"':''?>>
                    </div>
                    <div class="form-group" >
                        <label for="message">Adresa* </label>
                    <input type="text" name="message" autocomplete="off" class="form-control" placeholder="Upisite adresu"<?php echo isset ($fields['message'])? 'value="'.e($fields['message']).'"':''?>>
                     <br>

                        <input type="submit" value="Naruci" class="form-control" class="btn btn-primary">
                    </div>
                    <p class="muted">* oznacava obavezno polje</p>
                </form>
            </div>
        </div>
    </body>
</html>

<?php
unset($_SESSION['errors']);
unset($_SESSION['fields']);
?>

My PHP:

<?php
session_start();
require_once 'libs/phpmailer/PHPMailerAutoload.php';

$errors =[];

if(isset($_POST['name'],$_POST['email'],$_POST['message'],$_POST['comment'])){
    $fields=[
        'ime'=>$_POST['name'],
        'prezime'=>$_POST['email'],
        'broj telefona'=>$_POST['comment'],
        'adresa'=>$_POST['message']
    ];
    foreach($fields as $field=>$data){
        if(empty($data)){
            $errors[]='Polje '.$field . ' je obavezno ';
        }
    }
    if(empty($errors)){
        $m=new PHPMailer;
        $m->isSMTP();
        $m->SMTPAuth=true;
        $m->Host='smtp.gmail.com';
        $m->Username='';//replace with your email address
        $m->Password='';//replace with your password
        $m->SMTPSecure='ssl';
        $m->Port=465;

        $m->isHTML();
        $m->Subject ='Porudzbina';
        $m->Body='Od: '.$fields['ime'].' '.$fields['prezime'].'<p>Adresa: '.$fields['adresa'].'</p> <p>Broj telefona: '.$fields['broj telefona'].'</p>';

        $m->FromName='Musterija';
        $m->AddAddress('pavles643@gmail.com','Some one');
        if ($m->send()) {
            header('Location:thanks.php');
            die();
        }else{
            $errors[]="Zao nam je sada ne mozemo da pošaljemo porudžbinu, molimo pokušajte kasnije.";
        }
    }
}else{
    $errors[]= 'Nešto je pošlo naopako.';
}
$_SESSION['errors']=$errors;
$_SESSION['fields']=$fields;
header ('Location:smuti sam svoj smoothie.php');




ModelForm + ModelMultipleChoiceField can't validate populated list of checkboxes

everybody. I'm trying to build some checklist application. Basically, I have list of checkboxes with states stored in db. I need to load and display their initial state, made changes (select/deselect some of them) and store new checkboxes state back to db.

First phase is done - I've got a view that load checkboxes and states, but when I'm trying to put it back via calling ModelForm with request.POST data (), it fails due some fields\types incompatibility. I've tried to modify my model and POST results, but no result.

Here is my views.py:

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_infinibox_list'
    def get_queryset(self):
        return Infinibox.objects.all()
def detail(request,infinibox_id):
    # print(request.GET)
    if request.POST:
        print('-=posting data=-',request.POST)
        form=ChoiceForm(request.POST)
        print(form.is_valid()) #Here I constanty get False
        return HttpResponseRedirect(reverse('polls:detail', args=(infinibox_id,)))
    else:
        try:
            infinibox = Infinibox.objects.get(pk=infinibox_id)
        except Infinibox.DoesNotExist:
            raise Http404('Infinibox does not exist')
        choice = Choice.objects.filter(infinibox_id=infinibox_id)
        votes = [ch.id for ch in choice if ch.votes == 1]
        choice_text=[ch.choice_text for ch in choice if ch.votes == 1]
        form = ChoiceForm(initial={'infinibox':infinibox,'votes':votes,'choice_text':choice_text},q_pk=infinibox_id)
        return render(request, 'polls/detail.html', {'form': form, 'infinibox': infinibox,})

Here is my models.py:

from django.db import models
from django.utils import timezone
import datetime
class Infinibox(models.Model):
    infinibox_name = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __str__(self):
        return self.infinibox_name

    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now

class Choice(models.Model):
    infinibox = models.ForeignKey(Infinibox, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.BooleanField(default=0)

    def __str__(self):
        return self.choice_text

Here is my forms.py:

from django import forms
from .models import Choice

class ChoiceForm(forms.ModelForm):
    votes = forms.ModelMultipleChoiceField(queryset=None, widget=forms.CheckboxSelectMultiple)
    def __init__(self, *args, **kwargs):
        q_pk = kwargs.pop('q_pk', None)
        super(ChoiceForm, self).__init__(*args, **kwargs)
        self.fields['votes'].queryset = Choice.objects.filter(infinibox_id=q_pk)

    class Meta:
        model = Choice
        fields = ('votes',)

Temporary I've just write some primitive code to get it work:

    def detail(request,infinibox_id):
    if request.POST:
        print('-=posting data=-',request.POST)
        choice = Choice.objects.filter(infinibox_id=infinibox_id)
        vot = [int(item) for item in request.POST.getlist('votes')]
        for variant in choice:
            if variant.id in vot:
                variant.votes = 1
                variant.save()
            else:
                variant.votes = 0
                variant.save()

        return HttpResponseRedirect(reverse('polls:detail', args=(infinibox_id,)))

But I suppose, that this approach is more slowly and unsafe,... maybe it possible to get my request.POST passed to db trough a django's form validation/population logic?

Thanks in advance, Boris




ASP MVC check if checkbox is checked before submitting form and with out Jquery?

I have a form with 2 fields. One is a signature pad, and one is a checkbox. The checkbox is for staff and says something like "signature is on file", and will replace the signature field with a standard stamp. This all works so far. Problem is they want it so that if the box is not checked, then the signature pad must have a signature (not be null/empty). So I need this field to be required only if the checkbox is unchecked.

I wont want to use Jquery because I want to the form field to use an if else statement. If checkbox unchecked

 new { @class = "form-control",  required="required"})

else if checked not required. Since I don't know how to blend jquery with c# classes I want to avoid jquery. I also want to avoid postback if possible because the application has A LOT of TempData[] and I dont want to have to go back and figure out all the data that was lost after being accessed.

Is there a way?

Here is my form:

 @using (Html.BeginForm()) 
 {
     @Html.AntiForgeryToken()

<div class="form-horizontal">

    <hr />
    <span class="text-danger">Leave blank if you wish to fill this part out at later date.</span> <br /><br />
    <input type="checkbox" name="SignatureOnFile" value="True"> Check this box if the signature is on file.<br>
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.MySignature, "", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.MySignature, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.MySignature, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>

}




Clicking image inside of a doesn't reliably change checkbox when text is selected in Chromium browsers

I have a checkbox, and then I have a <label> with a for attribute which is used to activate this checkbox. There is an <img> within this label. Usually, clicking the image changes the checkbox, but when text is selected elsewhere in the page it doesn't always work on the first click. Example:

Select this text! Then try to activate the checkbox by clicking the image while text is still selected: 
<input id='check' type='checkbox'>
<label for='check'>
    <img style='height: 75px' src='http://ift.tt/2w9uaVX'>
</label>

It works as expected in Firefox (only takes one click, and is reliable), so I'm inclined to believe this is a browser issue, but am not 100% sure. Is there anything else that could be causing this, and any possible way to work around it?




CheckBox on tableview duplicating, Swift, iOS

I have a tableView that when selected changes an image from one to another. This all works fine but when I select a tableCell it changes the image, but when I scroll it has also changed the image of another cell that I didn't select.

Below is my code.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "FeaturesCell") as! FeaturesCell

    cell.featuresLabel.text = self.items[indexPath.row]

    return cell

}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

     pickedFeatures.append(items[indexPath.row])

    let cell = tableView.cellForRow(at: indexPath) as! FeaturesCell

    cell.checkImage.image = #imageLiteral(resourceName: "tick-inside-circle")

}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    pickedFeatures.remove(at: pickedFeatures.index(of: items[indexPath.row])!)

    let cell = tableView.cellForRow(at: indexPath) as! FeaturesCell

    cell.checkImage.image = #imageLiteral(resourceName: "No-tick-inside-circle")
}

If I use detqueureusable cell in the did select function then it just doesn't change the picture at all when selected.




How to manage checkbox filtering with React?

I am working on my first React app. It is a recipe sort of app. It has an ingredients filter. The main component is the Cookbook component. It has a Filter component and a Recipe component.

The Recipe component displays all recipes on load. The Filter component displays all needed ingredients or staples. This part all works great.

What I want to do now is when a person clicks on a staple, lets say butter, it would then filter the entire recipe list. My assumption is that I need to pass the state of Filter up. How can I do this with these checkboxes?

Here is what I have:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
var data = require('./recipes.json');

function IngredientDetailList(props){
    const ingredientList = props.ingredientList;
    const listItems = ingredientList.map((ingredient, index) => 
        <div key={index}> 
            {ingredient.measurement_amount}&nbsp;
            {ingredient.measurement_unit}&nbsp;
            {ingredient.ingredient}
        </div>

    );
    return (
        <div>{listItems}</div>
    )
}


function Recipe(props){
    const recipeList = props.cookbook.recipes
    const listItems = recipeList.map((recipe) =>
        <div key={recipe.id}>
            <h2>{recipe.name}</h2>
            <IngredientDetailList ingredientList = {recipe.ingredient_list}/>
        </div>

    );
    return(

        <div>{listItems}</div>
    )
}

class Filter extends React.Component {
    constructor(){
        super();
        this.state = {
            checkedStaples: {},
        }
    }

    render(){
        const stapleList = this.props.stapleList;
        const checkboxItems = stapleList.map((staple, index) => 
            <div key = {index}>
            <label>
                <input type="checkbox" value="{staple}"/>
                {staple}
            </label>
            </div>
        );
        return (
            <form>
                {checkboxItems}
            </form>
        );
    }
}


class Cookbook extends React.Component {
    constructor(){
        super(); 
        this.state ={
            cookbook: data
        }   
    }

    getStapleList(recipes){
        let stapleList = [];
        recipes.forEach(function(recipe){
            recipe.ingredient_list.forEach(function(list){
                stapleList.push(list.needed_staple);
            });
        });

        let flattenedStapleList = stapleList.reduce(function(a,b){
            return a.concat(b);
        })

        return flattenedStapleList
    }

    render(){
        const cookbook = this.state.cookbook;
        const stapleList = this.getStapleList(cookbook.recipes);
        return(
            <div className="cookbook">
                <div className="filter-section">
                    <h1>This is the filter section</h1>
                    <Filter stapleList = {stapleList}/>
                </div>
                <div className="recipes">
                    <h1>This is where the recipes go</h1>
                    <div className="recipe">    
                        <Recipe cookbook = {cookbook}/>
                    </div>
                </div>
            </div>
        );
    }
}

ReactDOM.render(
  <Cookbook />,
  document.getElementById('root')
);




How to find coordinates(x, y) of checkbox with Selenium python

I would like to find the position (x, y) of a checkbox, but unfortunately after several searches I have not found solutions ... (Even following the instructions in this answer: Selenium: get coordinates or dimensions of element with Python)

Here is my code:

Locate = wait (browser, 20) .until (EC.element_to_be_clickable ((By.ID, 'recaptcha-anchor')))
Location = locate.location
Size = locate.size
Print location
Print size

Unfortunately, this action returns me coordinates not going towards the direction of the checkbox in question ...

Did you have a solution, or is it really impossible to do this?

Thank you in advance!




js HTML Checkbox

I am not able to pull through a set of text if the checkbox is checked. JS and HTML below... Prob a simple fix - but I am lost that this is not functioning.

//js

function getTrainerExp()

{
    var trainerexp="None";
    //Get a reference to the form id="courseform"
    var theForm = document.forms["courseform"];
    //Get a reference to the checkbox id="includeexp"
    var includeexp = theForm.elements["includeexp"];

    //If they checked the box set trainerexp to ACMEEXP
    if(includeExp.checked==true)
    {
        trainerexp="ACMEXP";
    }
    //return the trainer expenses
    return trainerexp;
}


function calculateExp()
{
     var expense = getTrainerExp () ;

    //display the result
    var divobj = document.getElementById('trainerexp').checked;

    divobj.style.display='block';
    divobj.innerHTML = "Please Include   " +expense;

}

HTML

 <p>
<label for='includeexp' class="inlinelabel">If course delivery is at customer site include trainer travel costs and expenses</label>

<input type="checkbox" id="includeexp" name='includeexp' onclick="calculateExp()" />
</p>

<div id="trainerexp"></div>




Remove the item when uncheck the parent checkbox in the form

I created a booking form and the URL is http://ift.tt/2v61OiD

the purpose of this form is to collect booking, when user click on the checkbox its addon appear (if any). its automatically make the dropbox select 1 item and add the selected checkboxed item in the total segment, and when user uncheck the field its removes the item from total segment.

but the issue is when user directly uncheck the parent checkbox... the child's data remain in the total segment. (all child items should removed from total when user uncheck the parent item).

HTML

<ul>
    <li>

        <label for="facial-dermaclear">

            <div class="parent">
                <span class="gp-input">
                    <input id="facial-dermaclear" type="checkbox" name="facial[0][name]" value="Dermaclear" class="parent-input" data-id="10" data-category="facial" data-price="2200">
                    <span class="label">Dermaclear</span>
                </span>
                    <span class="gp-price">
                    <span class="currency">Rs.</span>
                    <span class="price">2200</span>
                </span>
                <span class="gp-quantity">
                    <select name="facial[0][qty]">
                    <option value="0">0</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option>                                            </select>
                </span>
            </div>


            <div id="addon-dermaclear" class="addons-list child" style="display:none;">

                <h3 data-fontsize="16" data-lineheight="24">Addons</h3>
                <!-- child addons -->
                <ul class="addon-list">


                    <li>
                        <label for="">
                            <span class="gp-input">
                                <input name="facial[0][addon][]" type="checkbox" value="Extra Shoulder Massage (10 mins)" class="child-input" data-id="100" data-price="300" data-parent="dermaclear">
                                <span class="label">Extra Shoulder Massage (10 mins)</span>
                            </span>
                            <span class="gp-price">
                                <span class="currency">Rs.</span>
                                <span class="price">300</span>
                            </span>
                        </label>
                    </li>


                    <li>
                        <label for="">
                            <span class="gp-input">
                                <input name="facial[0][addon][]" type="checkbox" value="Hot Oil Head &amp; Shoulder Massage (15 min)" class="child-input" data-id="101" data-price="500" data-parent="dermaclear">
                                <span class="label">Hot Oil Head &amp; Shoulder Massage (15 min)</span>
                            </span>
                            <span class="gp-price">
                                <span class="currency">Rs.</span>
                                <span class="price">500</span>
                            </span>
                        </label>
                    </li>


                </ul> <!-- .addon-list ended -->

            </div>


        </label>

    </li>
</ul>

jQuery

  function total() {

      var total = new Array(),
          sum = 0;

      $('.cart-items li .price').each(function(i){
          total.push( $(this).text() );
          sum += parseFloat($(this).text()) || 0;
      });

      $('.cart-summary span.total').text(sum);

      return sum;

  }

  $('.accordion input[type="checkbox"]').on('change', function(){

      var $this = $(this),
          // thisLabel = $this.parent().parent('label'),
          thisLabel = $this.closest('label'),
          thisID = parseInt( $this.data('id') ),
          thisName = $this.val(),
          thisPrice = parseInt( $this.data('price') );

      if ( $this.is(':checked') ) {

          thisLabel.find('.addons-list').fadeIn();

          thisLabel.find('option[value="1"]').attr('selected', 'selected');
          $('.cart-items').append('<li id="'+thisID+'" class="item"><span class="left"><span class="title">'+thisName+'</span> x <span class="total-qty">1</span></span><span class="right"><span class="currency">Rs.</span><span class="price">'+thisPrice+'</span></span></li>');

          thisLabel.find('.gp-quantity select').on('change', function(){

              var $child = $(this),
                  addonQty = $child.find('option:selected').val(),
                  addonPrice = parseInt( addonQty * thisPrice );

              $('.cart-items li[id="'+thisID+'"]').find('.total-qty').text(addonQty);
              $('.cart-items li[id="'+thisID+'"]').find('.price').text(addonPrice);

              total();

          });

      } else {

          thisLabel.find('.addons-list').fadeOut();

          var textNew = thisLabel.find('option[value="0"]').attr('selected', 'selected');
          $('.cart-items li[id="'+thisID+'"]').remove();

          total();

      }

      total();

  });

All i want this to remove the child items (if any) in totals when user uncheck the parent item.




change div display with change checked of checkbox in bindec gridview using asp.net

i have gridviewthat binded to database. there is checkbox in it that i want change display attribute of another div with checkbox checked value. this is my backend code in asp.net, but it isn't work! what can i do to solve it? thanks!

protected void gv_sourceGalleryPic_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "checkPic")
        {
            CheckBox chkItem = (CheckBox)gv_sourceGalleryPic.FindControl("ck_checkGalleryPic_copyMove");

            if (chkItem.Checked == true)
            {
                div1.Style.Add(HtmlTextWriterStyle.Display, "block");
            }
        }
    }




Android: Programmatically set checkbox set text position on the right

How can I set a programmatically created checkbox's text to be aligned on the left instead of right side of the checkbox. Below is a code snippet:

                            Checkbox check1 = new Checkbox(getApplicationContext());
                            check1.setLayoutParams(new ActionBar.LayoutParams(LinearLayoutCompat.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                            check1.setId(fieldNo);
                            check1.setTextColor(Color.BLACK);
                            check1.setGravity(Gravity.RIGHT);
                            check1.setText(formField.get(fieldNo));

The above code resulted in the text shown on the right of the checkbox.

Here is a screenshot : enter image description here

How can I have the text on the left of the checkbox?




vendredi 28 juillet 2017

HighStock hiding specific series and axes based on checkboxes

I have a DataTable that has a column of checkboxes. As well as a HighStock chart. I'm trying to make it so when the corresponding checkbox in the datatable is checked, it shows/hides the appropriate series line on the chart as well as the axis that line is using.

Table:

<div class="panel-body">
                <table id="data-table" class="table table-striped table-bordered nowrap" width="100%">
                    <thead>
                        <tr>
                            <th>List</th>
                            <th class="all">Foods</th>
                            <th class="all"><input name="select_all" value="1" type="checkbox"></th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr class="odd gradeX">
                            <td>1</td>
                            <td>Apples</td>
                            <td><input type="checkbox" id="name1" /></td>
                        </tr>
                        <tr class="odd gradeX">
                            <td>2</td>
                            <td>Oranges</td>
                            <td><input type="checkbox" id="name2" /></td>
                        </tr>
                        <tr class="odd gradeX">
                            <td>3</td>
                            <td>Pears</td>
                            <td><input type="checkbox" id="name3" /></td>
                        </tr>
                    </tbody>
                </table>
            </div>

HighStock:

var seriesOptions = [],
        seriesCounter = 0,
        names = ['MSFT', 'AAPL', 'GOOG'];

    /**
     * Create the chart when all data is loaded
     * @returns {undefined}
     */
    function createChart() {

        Highcharts.stockChart('container', {
                    alignTicks: false,
            rangeSelector: {
                selected: 4
            },

            yAxis: [{ // Primary yAxis 
            tickAmount: 8,
            tickInterval: 1,
            offset: 26,
            labels: {
                format: '{value}Apples',
                style: {
                    color: Highcharts.getOptions().colors[2]
                }
            },
            title: {
                text: 'Apples',
                style: {
                    color: Highcharts.getOptions().colors[2]
                }
            },
            opposite: true,
            min: 0,
            max: 100,

        }, { // Secondary yAxis
                    tickAmount: 8,
            tickInterval: 1,
            title: {
                text: 'Pears',
                style: {
                    color: Highcharts.getOptions().colors[0]
                }
            },
            labels: {
                format: '{value} pears',
                style: {
                    color: Highcharts.getOptions().colors[0]
                }
            },
            id: 'pears-axis',
            opposite: true,
            min: 0,
                max: 25,

        }, { // Tertiary yAxis
                tickAmount: 8,
            gridLineWidth: 0,
            title: {
                text: 'Oranges',
                style: {
                    color: Highcharts.getOptions().colors[1]
                }
            },
            labels: {
                format: '{value} Oranges',
                style: {
                    color: Highcharts.getOptions().colors[1]
                }
            },
            opposite: true,
            id: 'orange-axis',
            min: 0,
            max: 100,
        }],




            plotOptions: {
                series: {
                    compare: '',
                    showInNavigator: true
                }
            },

            tooltip: {
                pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
                valueDecimals: 2,
                split: true
            },

            series: [{
            name: 'Pears',
            type: 'spline',
            yAxis: 1,
            data: [
                [Date.parse('05/30/2017 13:30:00'), 24],
                [Date.parse('05/30/2017 13:45:00'), 24],
                [Date.parse('05/30/2017 14:00:00'), 24],
                [Date.parse('05/30/2017 14:15:00'), 24],
                [Date.parse('05/30/2017 14:30:00'), 24],
                [Date.parse('05/30/2017 14:45:00'), 24],
                [Date.parse('05/30/2017 15:00:00'), 24],
                [Date.parse('05/30/2017 15:15:00'), 24],
                [Date.parse('05/30/2017 15:30:00'), 24],
                [Date.parse('05/30/2017 15:45:00'), 24],
                [Date.parse('05/30/2017 16:00:00'), 24],
                [Date.parse('05/30/2017 16:15:00'), 24]
            ],
            tooltip: {
                valueSuffix: ' V'
            }

        }, {
            name: 'Oranges',
            type: 'spline',
            yAxis: 2,
            data: [
                [Date.parse('05/30/2017 13:30:00'), 20],
                [Date.parse('05/30/2017 13:45:00'), 30],
                [Date.parse('05/30/2017 14:00:00'), 40],
                [Date.parse('05/30/2017 14:15:00'), 50],
                [Date.parse('05/30/2017 14:30:00'), 60],
                [Date.parse('05/30/2017 14:45:00'), 60],
                [Date.parse('05/30/2017 15:00:00'), 60],
                [Date.parse('05/30/2017 15:15:00'), 60],
                [Date.parse('05/30/2017 15:30:00'), 70],
                [Date.parse('05/30/2017 15:45:00'), 76],
                [Date.parse('05/30/2017 16:00:00'), 78],
                [Date.parse('05/30/2017 16:15:00'), 80]
            ],
            marker: {
                enabled: false
            },
            dashStyle: 'shortdot',
            tooltip: {
                valueSuffix: ' %'
            }

        }, {
            name: 'Apples',
            type: 'spline',
            yAxis: 0,
            data: [
                [Date.parse('05/30/2017 13:30:00'), 70],
                [Date.parse('05/30/2017 13:45:00'), 70],
                [Date.parse('05/30/2017 14:00:00'), 76],
                [Date.parse('05/30/2017 14:15:00'), 75],
                [Date.parse('05/30/2017 14:30:00'), 78],
                [Date.parse('05/30/2017 14:45:00'), 72],
                [Date.parse('05/30/2017 15:00:00'), 80],
                [Date.parse('05/30/2017 15:15:00'), 73],
                [Date.parse('05/30/2017 15:30:00'), 75],
                [Date.parse('05/30/2017 15:45:00'), 78],
                [Date.parse('05/30/2017 16:00:00'), 72],
                [Date.parse('05/30/2017 16:15:00'), 73]
            ],
            tooltip: {
                valueSuffix: ' °F'
            }
        }]
        });
    }

    $.each(names, function (i, name) {

        $.getJSON('http://ift.tt/2s0U00j' + name.toLowerCase() + '-c.json&callback=?',    function (data) {

            seriesOptions[i] = {
                name: name,
                data: data
            };

            // As we're loading the data asynchronously, we don't know what order it will arrive. So
            // we keep a counter and create the chart when all the data is loaded.
            seriesCounter += 1;

            if (seriesCounter === names.length) {
                createChart();
            }
        });
    });

I tried using this code to make it so when the oranges checkbox is selected, it hides the line/series for Oranges, as well as the Oranges axis, then upon unchecking the box, both reappear. But instead, it keeps adding the Oranges axis over and over no matter it its checking the box or unchecking the box. How would I go about fixing this situation?

$('#name2').click(function() {
   var chart = $('#container').highcharts();
    var series = chart.series;
    var seriesIndex = 0
     if (this.selected) {
        series[seriesIndex].hide();
        chart.get('oranges-axis').remove();
    } else {
        series[seriesIndex].show();
        chart.addAxis({  // Tertiary yAxis
                tickAmount: 8,
            gridLineWidth: 0,
            title: {
                text: 'Oranges',
                style: {
                    color: Highcharts.getOptions().colors[1]
                }
            },
            labels: {
                format: '{value} Oranges',
                style: {
                    color: Highcharts.getOptions().colors[1]
                }
            },
            opposite: true,
            id: 'orange-axis',
            min: 0,
            max: 100,

});
    }
});




Checkboxes and Radios in Angular2+

Working on a form component in Angular, and having some trouble with. I've been having trouble with the visuals mainly, and getting really odd behavior out of them.

I've decided to move over to a checkbox styled to be a toggle.

Template code:

  <div class="switch">
            <input
              type="checkbox"
              name='correctPerson'
              [(ngModel)]='person.name.correctPerson' 
              [value]='person.name.correctPerson.value'>
            <span
              class="slider round"
              (click)='setCorrectPersonName()'></span>
          </div>

CSS:

.switch {
  position: relative;
  display: inline-block;
  margin: 40px;
  width: 60px;
  height: 34px;
}
.switch input {
  display: none;
}
.switch .slider {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: 0.4s;
  transition: 0.4s;
}
.switch .slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: 0.4s;
  transition: 0.4s;
}
.switch input:checked + .slider {
  background-color: #cda;
}
.switch input:focus + .slider {
  box-shadow: 0 0 1px #dca;
}
.switch input:checked + .slider:before {
  -webkit-transform: translateX(26px);
          transform: translateX(26px);
}
.slider.round {
  border-radius: 34px;
}
.slider.round:before {
  border-radius: 50%;
}

for the most part, the code works, and the setCorrectPersonName() function works, but the checkbox is only registering the first click.




how to load the checkbox values and persist them on postback in asp.net webforms

I have a bunch of checkboxes and a textbox which I have hardcoded at this point. According to the business rule, The checkbox selection needs to get saved and also, on post back or page refresh the selection needs to persist, in my case I am able to save the values to the database, but, unable to load them again on postback. Can someone provide me a example to handle this. I think that I need to write a load method to do this. Can someone provide me with an example.

Code:

                                                                <asp:CheckBox runat="server" ID="chkRS" Text="RS" />
                                                                </div>
                                                                <br />

                                                                <asp:CheckBox runat="server" ID="chkSC" Text="SSC" />

                                                                <br />

                                                                <asp:CheckBox runat="server" ID="SCR" Text="SCR" />

                                                                <br />

                                                                <asp:Label runat="server" AssociatedControlID="txtPrint">Print Button Class</asp:Label>
                                                                <asp:TextBox runat="server" ID="txtPrint" CssClass="form-control"></asp:TextBox>

                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>




Zip files from checkbox and download

I am trying to make a list of files from a directory have them shown in a form via checkboxes. When the user checks files they want to download have them zipped and downloaded. I have basically no experience in php but have managed to make my list with checkboxes and a download script attached to the button that when it is selected should start the download but doesn't it does however clear the boxes.If possible I would also like to store a copy of this zip to a folder on the server in case the user would like to re-download in a certain amount of time. here is the code I have. Someone let me know where I went wrong and please explain any corrections to code as I am trying to learn as I do this little project.

 <?php
    $error = "";        //error holder
    if(isset($_POST['createzip'])){
        $post = $_POST;     
        $file_folder = "files/";    // folder to load files
        if(extension_loaded('zip')){    // Checking ZIP extension is available
            if(isset($post['files']) and count($post['files']) > 0){    // Checking files are selected
                $zip = new ZipArchive();            // Load zip library 
                $zip_name = time().".zip";          // Zip name
                if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){       // Opening zip file to load files
                    $error .=  "* Sorry ZIP creation failed at this time<br/>";
                }
                foreach($post['files'] as $file){               
                    $zip->addFile($file_folder.$file);          // Adding files into zip
                }
                $zip->close();
                if(file_exists($zip_name)){
                    // push to download the zip
                    header('Content-type: application/zip');
                    header('Content-Disposition: attachment; filename="'.$zip_name.'"');
                    readfile($zip_name);
                    // remove zip file is exists in temp path
                    unlink($zip_name);
                }

            }else
                $error .= "* Please select file to zip <br/>";
        }else
            $error .= "* You dont have ZIP extension<br/>";
    }
?>

Here's checkbox

<?php

if ($handle = opendir('./')) {
while (false !== ($entry = readdir($handle))) {
    if ($entry != "." && $entry != "..") {
        echo '<input type="checkbox" name="files[]" value=".$entry"/> '.$entry. '<br />';
    }
}
closedir($handle);
?>




Multiple checkbox search query fetching data from database in php

I have a multiple checkbox search query which fetches data from database. Below is the code:

HTML code:

<form action="search.php" method="post">
<input type="checkbox" name="cloth_color[]" value="Red" /> Red <br>
<input type="checkbox" name="cloth_color[]" value="Yellow" /> Yellow <br>
<input type="checkbox" name="cloth_color[]" value="Blue" /> Blue <br>
<input type="checkbox" name="cloth_color[]" value="Green" /> Green <br>
<input type="checkbox" name="cloth_color[]" value="Magenta" /> Magenta <br>
<input type="checkbox" name="cloth_color[]" value="Black" /> Black <br>
<input type="checkbox" name="cloth_color[]" value="White" /> White <br>
<input type="submit" value="SEARCH">
</form>

PHP code:

<?php
$checkbox1 = $_POST['cloth_color'];  
$chk="";  
foreach($checkbox1 as $chk1)  
   {  
      $chk .= $chk1;
   }

if($_POST['cloth_color'] != "") {
$query = "SELECT * FROM clothings WHERE colorofcloth = '$chk'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$colorofcloth = $row['colorofcloth'];

    echo 'The cloth with ' . $colorofcloth . ' color';
    echo '<br>';

}
}
?>

Now if I choose one option from the search select box I get query. But if I select two or more color I dont get the query. A help will be really appreciated.

P.S. I do have multiple joins in Mysql query but this is the place I am stuck so presenting as clear question as possible here. Also I intent to convert mysql to mysqli before the launch of this code. Thank you :)