samedi 30 septembre 2017

Update checkbox in CheckedTextView which is inside a ListView

I am a noob android studio and this is my first app I am developing.

Context: I have a ListView lv which is populated with CheckedTextViews using a SimpleAdapter. I have set up the OnItemClickListener for lv as shown below which checks and unchecks the check boxes as expected. I want the checks to remain persistent when I navigate between activities, so I am storing a key in the selectedTrackers array list.

lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
        {
            CheckedTextView ctv = (CheckedTextView) view.findViewById(R.id.trackerID);

            HashMap s = (HashMap)lv.getItemAtPosition(i);
            String mob = (String)s.get("mobile");

            //checked and pressed
            if (ctv.isChecked())
            {
                ctv.setChecked(false);
                for (int j = 0; j < selectedTrackers.size(); j++)
                {
                    if (selectedTrackers.get(j) == mob)
                    {
                        selectedTrackers.remove(j);
                        break;
                    }
                }

            }
            //not checked
            else
            {
                ctv.setChecked(true);
                selectedTrackers.add(mob);
            }

        }
    });

When I navigate back to the activity with the list view, I call a function getSelectedTrackers which I want to select the saved checkboxes based on the key in selectedTrackers

public static void getSelectedTrackers()
{
    if (basicSettings.selectedTrackers.size() == 0) return;
    for (int i = 0; i < trackers.size(); i++)
    {
        HashMap s = trackers.get(i);
        String mob = (String)s.get("mobile");
        for (int j = 0; j < basicSettings.selectedTrackers.size(); j++)
        {
            if (basicSettings.selectedTrackers.get(j).equals(mob))
            {
                View v = getViewByPosition(i, lv);
                CheckedTextView ctv = (CheckedTextView) v.findViewById(R.id.trackerID);

                ctv.setChecked(true);
                //******************************
                //some call to update the view HERE
                //******************************


                break;
            }
        }

    }

}

Question: I have confirmed that the function finds the correct checkbox, but none of the check boxes are displayed as being selected after calling setChecked(). I have scoured SO and tried invalidating, refreshing drawable state, notifyDataSetChanged, and I can't seem to figure it out how to get it to work. What's the best way to do this? Any help is appreciated!




PyQt4: When one checkbox is checked, by pressing a button to print some texts from a LineEdit if another checkbox is also checked

import sys, os
import PyQt4
from PyQt4 import QtGui, QtCore 
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class Tab1Widget1(QWidget):
    def __init__(self, parent=None):
        super().__init__()

        self.Tab1Widget1initUI()

        self.bridge = Tab1Widget2()

    def Tab1Widget1initUI(self):
        self.setLayout(QGridLayout())

        self.T1W1_checkbox = QCheckBox('checkbox1', self)
        self.layout().addWidget(self.T1W1_checkbox, 1, 0)

    def test(self):
        print ('123')


    def run(self):
        if self.T1W1_checkbox.isChecked() == True:
            self.test()
            if self.bridge.T1W2_checkbox.isChecked() == True:
                print (self.bridge.T1W2_le.text())

class Tab1Widget2(QWidget):

    def __init__(self, parent=None):
        super().__init__()
        self.setLayout(QGridLayout())

        self.T1W2_checkbox = QCheckBox('checkbox2', self)
        self.layout().addWidget(self.T1W2_checkbox, 0, 0)

        self.T1W2_le = QLineEdit()
        self.layout().addWidget(self.T1W2_le, 0, 1)

class Tab1Layout(QWidget):
    def __init__(self, parent=None):
        super().__init__()
        self.setLayout(QGridLayout())

        self.group1 = Tab1Widget1(self)
        scroll = QScrollArea(self)
        scroll.setWidget(self.group1)
        scroll.setWidgetResizable(True)
        self.layout().addWidget(scroll, 0, 0)

        self.group2 = Tab1Widget2(self)
        self.layout().addWidget(self.group2, 1, 0)

        self.btnRun = QPushButton('Run', self)
        self.layout().addWidget(self.btnRun, 3, 0)
        self.btnRun.clicked.connect(self.group1.run)


class Page1(QTabWidget):
    def __init__(self, parent=None):
        super().__init__()
        self.tab1 = Tab1Layout()
        self.addTab(self.tab1, "Tab1")

        self.tab2 = QWidget()
        self.tab3 = QWidget()
        self.addTab(self.tab2, "Tab2")
        self.addTab(self.tab3, "Tab3")
        self.tab2_initUI()
        self.tab3_initUI()

    def tab2_initUI(self):
        grid = QGridLayout()
        self.tab2.setLayout(grid)

    def tab3_initUI(self):
        grid = QGridLayout()
        self.tab3.setLayout(grid)

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__()
        self.setGeometry(450, 250, 800, 550)
        self.startPage1()

    def startPage1(self):
        x = Page1(self)
        self.setWindowTitle("Auto Benchmark")
        self.setCentralWidget(x)
        self.show()

def main():
    app = QApplication(sys.argv)
    main = MainWindow()
    main.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

If checkbox1 is checked and I press the run button, it will print 123. However, by pressing run button, I want checkbox2 to also print some texts entered in lineedit if the checkbox1 are also checked (i.e. it should print 123 first and then print 456).

I've looked up some similar types of questions, but none of that provides a proper answer. If anyone knows how to solve it, pls let me know thanks!!




Event triggered by ANY checkbox click

I'm going crazy trying to find a way for code to run when I click on ANY of the checkboxes on my sheet. I've seen multiple articles talking about making a class module, but I can't seem to get it to work.

I have code that will populate column B to match column C. Whatever I manually type into C10 will populate into B10, even if C10 is a formula: =D9. So, I can type TRUE into D10 and the formula in C10 will result in: TRUE and then the code populates B10 to say: TRUE. Awesome... the trick is to have a checkbox linked to D10. When I click the checkbox, D10 says TRUE and the formula in C10 says TRUE, but that is as far as it goes. The VBA code does not recognize the checkbox click. If I then click on the sheet (selection change), then the code will run, so I know I need a different event.

It is easy enough to change the event to "Checkbox1_Click()", but I want it to work for ANY checkbox I click. I'm not having ANY luck after days of searching and trying different things.

here is the code I'm running so far

    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim i As Long


For i = 3 To 11
    Range("B" & i).Value = Range("c" & i)
Next i
    End Sub

Any help would be appreciated.




Itext7 Checkbox checking error

I am filling out a premade PDF-Form programatically, using WinForms / C#. Textfields are working as intended, but for a few days now Checkboxes are acting up, though the same code worked before.

I am getting an exception:

"System.NullReferenceException: 'Object reference not set to an instance of an object.'"

Originating from the "toSet.SetValue ..." line of code.

if (radioHVZANein.Checked)
                {
                    fields.TryGetValue("HVZANein", out toSet);
                    toSet.SetValue("Yes");
                }

I checked that the "HVZANein" Checkbox exists, checked that "Yes" is a valid value to set it to. Setting the correct value to the existing field still causes the error (which visual studio helpfully displays on the next line of code, not the one that actually triggers it)

What is going wrong?

Any help is greatly appreciated.




Unable to set 'checked' attribute to MDL switch component

Here is the code to where I'm trying to set the 'checked' attribute of the MDL switch, where the value of userRoles.roles.subs is true.

 var dbRef = firebase.database().ref('users/' + window.localStorage.getItem('UserID')).on('value', function(snapshot){
        var userRoles = snapshot.val();
        console.log(userRoles.roles.subs);
        $('.subs')[0].checked = userRoles.roles.subs;
        // See http://ift.tt/2fyyc45
        // Related http://ift.tt/2xNJBa3

    })

None of the references seem to work in this case. Below is the component

<div class="mdl-cell mdl-cell--7-col">       
    <label class="mdl-switch mdl-js-switch mdl-js-ripple-effect" for="sendNews">
          <input type="checkbox" id="sendNews" class="mdl-switch__input subs">
          <span class="mdl-switch__label">Send me weekly InfoArticle via Email</span>
    </label>

</div>




htmlpurifier "checked" checkbox

I need to allow checkbox to be checked in the htmlpurifier. For now, I successfully allowed checkbox, but the plugin cut CHECKED attribute. Is there way to allow the CHECK attribute in the checkbox in htmlpurifier?

That's what I have for now:

$checkbox = $def->addElement(  // adding checkbox rule to HTMLPurifier
  'input',   // name
  'Block',  // content set
  'Empty', // allowed children
  'Common', // attribute collection
  array( // attributes
    'type' => new HTMLPurifier_AttrDef_Enum(array('checkbox')),
    'id' => 'Number',
    'class' => 'Text',
    'value' => 'Number',

  )
);
$checkbox->excludes = array('checkbox' => true);




Validate and add a subentity only if checkbox is checked

I have a user entity. The user may check a checkbox, and fill an additional entity of data. Thes data will be saved with doctrine

My form type looks like this:

...
$builder->add('name', null, array('error_bubbling' => true))
->add("hasSocieta", CheckboxType::class, array('mapped' => false, 'required'=> false))
->add("social_links", SocialType::class array('error_bubbling' => true, 'required' => false, 'validation_groups' => array('social'))

public function configureOptions(OptionsResolver $resolver)
{
 $resolver->setDefaults([
                'validation_groups' => function(FormInterface $form) {
                    if ($form->get('hasSocial')->getData() == false) {
                        return array('Default');
                    }
                    return array('Default', 'social');
                }
          ]);
}

I'll hide from the form this additional entity with javascript unless the user checkes the checkbox, but I'll have to show it the user has js deactivated.

When I submit the form, If I input one of the fields inside the Social entity, but not the others, a doctrine exception has raised (because it needs the other fields). How can I discard all the data associated to this entity, if the checkbox is checked?




By clicking a button, print some texts entered in QLineEdit when a checkbox is checked PyQt4

By clicking a button, I want to print some texts that is entered in QLineEdit when a checkbox is checked. My example codes are as below:

import sys
import PyQt4
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import *
from PyQt4.QtCore import *

class Widget(QWidget):
    def __init__(self, parent= None):
        super(Widget, self).__init__(parent)
        layout = QGridLayout()

        self.setLayout(layout)

        self.checkBox = QCheckBox()
        layout.addWidget(self.checkBox, 0, 0)


        self.le = QLineEdit()
        layout.addWidget(self.le, 0, 1)

        self.btn = QPushButton('Run')
        layout.addWidget(self.btn, 0, 3)


class Func ():
    def __init__(self):
        a = Widget(self)

    def someFunc(self):
        ##print ()


app = QApplication(sys.argv)
widget = Widget()
widget.show()
app.exec_()

As you can see above, I want the button in "Widget" class to connect to "someFunc" method in "Func" class. Thus when some texts are entered in "self.le" as well as "checkBox" is checked, I want "someFunc" to print the texts entered in "self.le" by clicking the button. If the "checkbox" is not checked, clicking the button should not cause anything to happen even when some texts are entered.

If anyone knows how to solve it, pls let me know thanks!!




Ajax debug Error

i have problem ,when i bind two components (checkbox and label) by adding tag attribute "for" to label , and tag attribute "id" to checkbox, it throws ajax debug error : " Cannot bind a listener for event "click" on element "variantBox4" because the element is not in the DOM".

Here is checkbox code:

      AjaxCheckBox checkBox = new AjaxCheckBox("variantBox", variantModel) {

                    @Override
                    protected void onUpdate(AjaxRequestTarget target) {
                        if (variantModel.getObject()) {
                            target.appendJavaScript(";utils_showElement(" + item.getModelObject().getId() + ");");
                        } else {
                            target.appendJavaScript(";utils_hideElement(" + item.getModelObject().getId() + ");");
                        }
                    }



                }; 

i add attribute modifier to checkbox in this code:

checkBox.add(new VariantElementAttributeModifier("id",Model.of("checkbox_"+Long.toString(item.getModelObject().getId()))));

here i do the same operation with label:

      Label headerLabel = new Label("content", Model.of(item.getModelObject().getContent()));

      headerLabel.add(new VariantElementAttributeModifier("for",Model.of("checkbox_"+Long.toString(item.getModelObject().getId()))));

here is html:

    <!DOCTYPE html>
     <html lang="en" xmlns:wicket="http://ift.tt/2xJMC9I">
      <head>
      <meta charset="UTF-8">
       <title>Title</title>
      </head>
      <body>

      <wicket:panel>




      <section class="column column_form">
        <div class="column__title">Опросный лист</div>
        <div wicket:id="container" class="column__content" style="height: 
       475px;">
            <div wicket:id="list" class="form">
                <div wicket:id="contentArea"></div>
                <div wicket:id="helpLabel"></div>

                <wicket:fragment wicket:id="variantFragment" 
         class="form__item checkbox">
                    <div class="checkbox__label" wicket:id="content">
        </div>
                    <input class="checkbox__input"   type="checkbox" 
        wicket:id="variantBox" />

                    <!--<input class="checkbox__input" type="checkbox" 
           name="input-name" id="checkbox_1"/>-->
                    <!--<label class="checkbox__label" for="checkbox_1"><b>текст</b><span>текст текст</span><span>текст текст</span></label>-->
                </wicket:fragment>
                <wicket:fragment wicket:id="Textfragment" 
        class="form__item form__textfield">
                    <label wicket:id="textlabel">лейбл</label>
                    <input type="text" wicket:id="textfield" />
                </wicket:fragment>
            </div>
        </div>
    </section>


</wicket:panel>
</body>
</html>

Here is attribute modifier code:

      package ru.simplexsoftware.constructorOfDocuments.Utils;
      import org.apache.wicket.AttributeModifier;
      import org.apache.wicket.model.IModel;


       public class VariantElementAttributeModifier extends AttributeModifier {
       public VariantElementAttributeModifier(String attribute, IModel<?> replaceModel) {

        super(attribute, replaceModel);
       }


       }

Thanks for help.




vendredi 29 septembre 2017

How bind checkboxes with a Model object List

i have a jsp to register new users with yours respective roles. In the form, i receive a roleList in checkbox using c:forEach.

Everything is going well, BUT...

  • If i try to save User with the first checkbox checked = OK, it is saved well
  • If i try to save User with the first and second checkbox checked = Ok again, everything going well
  • BUT if i try to save the user with the second or third role, jumping one element in the checkbox sequence, it throws a Exception like: Exception Save the transient instance before flushing...

So, what i am understanding here, is that the list that is passed in the bind to my List cannot have blank/null values. Even if i have 20 roles, i can save Users, with many roles, but if i jump anyone, it throws the exception.

How can i resolve that issue?? How can i pass the roles that i want without follow any order?

@Entity
public class User implements UserDetails {
@Id
private String login;
@NotBlank
private String password;
@NotBlank
private String name;
@ManyToMany(fetch=FetchType.EAGER)
private List<Role> roles = new ArrayList<>();


@Entity
public class Role implements GrantedAuthority {
@Id
private String name;


@Controller
@Transactional
@RequestMapping("/register")
@Scope(WebApplicationContext.SCOPE_REQUEST)
public class UserController {

@Autowired
UserDao userDao;
@Autowired
RoleDao roleDao;

@RequestMapping("userForm")
public ModelAndView userForm(User user) {
    ModelAndView modelAndView = new ModelAndView("user/userForm");
    modelAndView.addObject("roleList", roleDao.list());
    return modelAndView;
}

@RequestMapping (value="saveUser", method=RequestMethod.POST, name="saveUser")
public ModelAndView saveUser(@Valid User user, BindingResult bindingResult, RedirectAttributes redirectAttributes) {

    if (bindingResult.hasErrors()){
        return userForm(user);
    }
    userDao.save(user);

    redirectAttributes.addFlashAttribute("success", "User successfully registered");
    return new ModelAndView("redirect:/register/userForm");
}
}


<form:form action="${spring:mvcUrl('saveUser').build()}" method="post" commandName="user">

    <div>
        <label for="name">User name</label>
        <form:input path="name"/>
        <form:errors path="name"/>
    </div>

    <div>
        <label for="login">Login</label>
        <form:input path="login"/>
        <form:errors path="login"/>
    </div>

    <div>
        <label for="password">Password</label>
        <form:input path="password"/>
        <form:errors path="password"/>
    </div>

    <div>
        <c:forEach items="${roleList}" var="role" varStatus="status">
            <div>
                <label for="role_${role}">${role}</label>
                <input type="checkbox" value="${role}" name= "roles[${status.index}]" id="role_${role}"/>
            </div>
        </c:forEach>
    </div>

    <div>
        <input type="submit" value="Save">
    </div>
</form:form>

Thanks in advance




How to get the status of a JCheckBox which components are in a VerticalBox?

I'm creating a script where you can choose a folder of which you can pick components via a JCheckBox and copy them to another folder. My problem is, that i worked with a VerticalBox to store the file names and added the JCheckBox into it, so i have no clue how to get the status of a single CheckBox because it's variable is overridden for each new file and I can only read it from the last listed file.

Here's the (unfinished) code:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

public class CopyGUI extends JFrame implements ActionListener {

    private static final long serialVersionUID = 1L;
    private Box box;
    private File fromFile;
    private File toFile;
    private File folder;
    private File[] listOfFiles;
    private JButton beginButton;
    private JButton fromButton;
    private JButton toButton;
    private JCheckBox checkBox;
    private JLabel fromLabel;
    private JLabel toLabel;
    private JPanel panel;
    private JScrollPane scrollPane;
    private JTextField fromField;
    private JTextField toField;

    public CopyGUI() {
        init();
    }

    private void init() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setBounds(200, 200, 420, 700);
        setResizable(false);
        setTitle("File Copy");

        panel = new JPanel(null);
        add(panel);

        fromLabel = new JLabel("From:");
        fromLabel.setBounds(40, 20, 50, 20);

        fromField = new JTextField();
        fromField.setBounds(100, 20, 200, 20);

        fromButton = new JButton("Browse");
        fromButton.setBounds(300, 20, 80, 20);
        fromButton.addActionListener(this);

        toLabel = new JLabel("To: ");
        toLabel.setBounds(40, 40, 50, 20);

        toField = new JTextField();
        toField.setBounds(100, 40, 200, 20);

        toButton = new JButton("Browse");
        toButton.setBounds(300, 40, 80, 20);
        toButton.addActionListener(this);

        panel.add(fromLabel);
        panel.add(fromField);
        panel.add(fromButton);

        panel.add(toLabel);
        panel.add(toField);
        panel.add(toButton);

        beginButton = new JButton("Begin Copy");
        beginButton.setBounds(280, 620, 100, 20);
        beginButton.addActionListener(this);

        panel.add(beginButton);

        scrollPane = new JScrollPane();
        scrollPane.setBounds(40,80,340,520);

        box = Box.createVerticalBox();

        scrollPane = new JScrollPane(box);
        scrollPane.setBounds(40,80,340,520);

        panel.add(scrollPane);
    }

    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == fromButton) {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

            int op = fileChooser.showOpenDialog(this);
            if (op == JFileChooser.APPROVE_OPTION) {
                fromFile = fileChooser.getSelectedFile();
                fromField.setText(fromFile.getAbsolutePath() + "\\");
                folder = new File(fromFile.getAbsolutePath());
                listOfFiles = folder.listFiles();
            }

            box.removeAll();

            for (int i = 0; i < listOfFiles.length; i++) {
                if (listOfFiles[i].isFile()) {
                    checkBox = new JCheckBox(listOfFiles[i].getName());
                    box.add(checkBox);
                }
                else if (listOfFiles[i].isDirectory()) {
                }
            }

            panel.revalidate();
            panel.repaint();
        }

        if (e.getSource() == toButton) {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

            int op = fileChooser.showOpenDialog(this);
            if (op == JFileChooser.APPROVE_OPTION) {
                toFile = fileChooser.getSelectedFile();
                toField.setText(toFile.getAbsolutePath() + "\\");
            }
        }

        if (e.getSource() == beginButton) {

            System.out.println(checkBox.isSelected());

        }
    }

    public static void main(String[] args) {
        new CopyGUI().setVisible(true);
    }
}




How to check off checkboxes based on array values

I really need your help and I couldn't seem to find a similar solution out there that would provide the support I needed for what I am trying to accomplish here.

How can I programmatically check off the following check boxes based on their values in an array.

var arr = ['recurr_date2','recurr_date4']

I'd like to check the checkbox whose value is recurr_date2 and recurr_date4

Here is the HTML markup:

<input name="recurr_target" value="recurr_date2" type="checkbox">
<input name="recurr_target" value="recurr_date3" type="checkbox">
<input name="recurr_target" value="recurr_date4" type="checkbox">

I am fine with an anwer also using jQuery




Jquery Checkbox is checked?

I am working on making a slider that has different prices using jQuery and a little rangeslider.js. I made everything work, but the second two numbers only change when I move the slider, not when I check the checkbox. I am trying to make the numbers change right when I click the checkbox.

$(document).on('input change', '#range-slider', '#voiceover', function() { //Listen to slider changes (input changes)       

    var v=$(this).val();
  var voiceOption = $('#voiceover');//Create a Variable (v), and store the value of the input change (Ex. Image 2 [imageURL])
  console.log(v);

$('#sliderStatus').html(videoDuration[v]);
$('#sliderPrice').html('<span>$'+videoSubtotal[v]+'.00</span>');

var totalPrice = parseInt(voiceoverSubtotal[v])+parseInt(videoSubtotal[v]);
  if(voiceOption.is(":checked")){
    $('#voiceoverspan').html('<span>$'+voiceoverSubtotal[v]+'.00</span>');
      $('#totalspan').html('<span>$'+totalPrice+'.00</span>');
  }
    else{
    $('#voiceoverspan').html('<span>$0.00</span>');
     $('#totalspan').html('<span>$'+videoSubtotal[v]+'.00</span>');
  }

  /*if(voiceOption.is(":checked") ){
    $('#totalspan').html('<span>$'+totalPrice+'.00</span>');
  }
  else{
    $('#totalspan').html('<span>$'+videoSubtotal[v]+'.00</span>');
  }*/
});

Thank you so much my codepen is here: http://ift.tt/2fiRLxc




When Checkbox is selected dynamically using ajax data and Jquery, Once Checkbox is clicked It doesn't change with Jquery Dynamically

This code is Written in MVC 5, In the View, I am selecting a value from a Drop Down List and updating the Checkbox based on the value 0 or 1 from the Database using Jquery. When i select any value from the Drop down It dynamically calls the following ajax script code.

  <script type="text/javascript">
            $(function () {
                $(document).ready(function () {

                });
                $("#ddlUsername").change(function () {
                    if ($(this).val() != "") {
                        console.log($("#ddlUsername option:selected").text())
                        console.log($("#ddlUsername option:selected").val())

                        $.ajax({
                            type: "POST",
                            url: "/Home/RetrieveSettings",
                            data: {
                                upen: $("#ddlUsername option:selected").val()
                            },
                            success: function (data) {
                                console.log(data)
                                console.log($("#checkbox1").is(":checked"))
                               @*Data[0] is data array from database, and cb_field is column name in the Database*@
                                if (data[0].cb_field== 1) {
                                    $("#checkbox1").attr("checked", true);
                                    $("#checkbox1").val($("#checkbox1").is(":checked"));
                                } else {
                                    $("#checkbox1").attr("checked", false);

 $("#checkbox1").val($("#checkbox1").is(":checked"));
                                }
                                                                console.log($("#checkbox1"));
                            }
                        })



                    } else {
                        $("#list_user_name").text("");

                    }
                });

                $("#checkbox1").change(function () {
                    //console.log($("#touch_history").val())
                    //console.log($("#checkbox1").val())

                    console.log($("#checkbox1").is(":checked"))
                })
            });

        </script>

This works fine if we do not click the checkbox. Once any checkbox is clicked that checkbox will not be updated dynamically using following function. I am using A Switch Functionality for this checkbox and the checkbox is shown in CSS and HTML Code below

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CSS3 Toggle Switch Button</title>
<style>
    .switch {
      position: relative;
      display: block;
      vertical-align: top;
      width: 200px;
      height: 40px;
      padding: 3px;
      margin: 0 10px 10px 0;
      background: linear-gradient(to bottom, #eeeeee, #FFFFFF 25px);
      background-image: -webkit-linear-gradient(top, #eeeeee, #FFFFFF 25px);
      border-radius: 18px;
      box-shadow: inset 0 -1px white, inset 0 1px 1px rgba(0, 0, 0, 0.05);
      cursor: pointer;
    }
    .switch-input {
      position: absolute;
      top: 0;
      left: 0;
      opacity: 0;
    }
    .switch-label {
      position: relative;
      display: block;
      height: inherit;
      font-size: 13px;
      text-transform: uppercase;
      background: #eceeef;
      border-radius: inherit;
      box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.12), inset 0 0 2px rgba(0, 0, 0, 0.15);
    }
    .switch-label:before, .switch-label:after {
      position: absolute;
      top: 50%;
      margin-top: -.5em;
      line-height: 1;
      -webkit-transition: inherit;
      -moz-transition: inherit;
      -o-transition: inherit;
      transition: inherit;
    }
    .switch-label:before {
      content: attr(data-off);
      right: 11px;
      color: #aaaaaa;
      text-shadow: 0 1px rgba(255, 255, 255, 0.5);
    }
    .switch-label:after {
      content: attr(data-on);
      left: 11px;
      color: #FFFFFF;
      text-shadow: 0 1px rgba(0, 0, 0, 0.2);
      opacity: 0;
    }
    .switch-input:checked ~ .switch-label {
      background: #E1B42B;
      box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.15), inset 0 0 3px rgba(0, 0, 0, 0.2);
    }
    .switch-input:checked ~ .switch-label:before {
      opacity: 0;
    }
    .switch-input:checked ~ .switch-label:after {
      opacity: 1;
    }
    .switch-handle {
      position: absolute;
      top: 4px;
      left: 4px;
      width: 38px;
      height: 38px;
      background: linear-gradient(to bottom, #FFFFFF 40%, #f0f0f0);
      background-image: -webkit-linear-gradient(top, #FFFFFF 40%, #f0f0f0);
      border-radius: 100%;
      box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.2);
    }
    .switch-handle:before {
      content: "";
      position: absolute;
      top: 50%;
      left: 50%;
      margin: -6px 0 0 -6px;
      width: 12px;
      height: 12px;
      background: linear-gradient(to bottom, #eeeeee, #FFFFFF);
      background-image: -webkit-linear-gradient(top, #eeeeee, #FFFFFF);
      border-radius: 6px;
      box-shadow: inset 0 1px rgba(0, 0, 0, 0.02);
    }
    .switch-input:checked ~ .switch-handle {
      left: 165px;
      box-shadow: -1px 1px 5px rgba(0, 0, 0, 0.2);
    }
    /* Transition
        ========================== */
    .switch-label, .switch-handle {
      transition: All 0.3s ease;
      -webkit-transition: All 0.3s ease;
      -moz-transition: All 0.3s ease;
      -o-transition: All 0.3s ease;
    }

</style>
    </head>

    <body>
<label class="switch">
      <input class="switch-input" type="checkbox" id="checkbox1" />
      <span class="switch-label" data-on="ON" data-off="OFF"></span> <span class="switch-handle"></span> </label>

</body>
</html>




How to select single checkbox in a recycler view with multiple checkboxes

There are answers of this questions but none of them solved my problem .Below is my code .

public class QuizAdapter extends RecyclerView.Adapter<QuizAdapter.MyViewHolder> {
Context context;
private List<Quiz_G_S> quiz_g_sList = null;
int selectedPosition = -1;


public QuizAdapter(Context context, List<Quiz_G_S> list) {
    this.context = context;
    this.quiz_g_sList = list;
}


@Override
public QuizAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.quiz_single_row, parent, false);

    return new MyViewHolder(itemView);

}

@Override
public void onBindViewHolder(final QuizAdapter.MyViewHolder holder, int position) {

    final int pos = position;

    holder.answers.setText(quiz_g_sList.get(pos).getMCQ());


    if (selectedPosition == pos) {
        holder.checkBox.setChecked(true);

    } else {
        holder.checkBox.setChecked(false);

    }


    holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            selectedPosition = holder.getAdapterPosition();
            QuizAdapter.this.notifyDataSetChanged();

        }
    });


}


@Override
public int getItemCount() {
    return quiz_g_sList.size();
}

public class MyViewHolder extends RecyclerView.ViewHolder {

    TextView answers;
    CheckBox checkBox;

    public MyViewHolder(View v) {
        super(v);

        answers = (TextView) v.findViewById(R.id.quiz_adap_ans);
        checkBox = (CheckBox) v.findViewById(R.id.quiz_adap_check);

    }
}

}
Above is my adapter code. There is an error on notifyDataSetChanged. I guess the logic is right but i don't know how to refresh checkbox state.The only thing I know is notifyDataSetChanged is there any other method to refresh or is there any workaround for this problem




multiple checkbox insertion with different names and values

i have 2 checkboxes named EMD and HMD. now both EMD and HMD checkboxes has 2-2 another checkboxes in it named en_ner,en_kg and hn_ner,hn_kg. now all the inherit checkboxes have another 2-2 checkboxes in it. now i need to insert them in the database with its category wise. here is my html code

<div class="col-md-4" ">
    <input id="english " name="englishMedium " class="form-control input-md " onclick="EnglishDIV() " type="checkbox " value="ENM "  />
  </div>
<table width="100% ">
        <tr><td><label class="col-md-2 control-label "><b>Standards</b></label></td><td><label class="col-md-2 control-label "><b>Class</b></label></td></tr>
        <tr>
          <td>
            <input id="N " name="en_ner "  type="checkbox " value="N "><font size="3 "><b>Nursery</b></font>
          </td>
          <td>
          <input id="A " name="en_nursury_a "  type="checkbox " value="A " ><b>A</b>&nbsp;&nbsp;
          <input id="B " name="en_nursury_b "  type="checkbox " value="B " ><b>B</b>&nbsp;&nbsp;
          </td>
        </tr>
        <tr>
          <td>
            <input id="JK " name="en_jrkg "  type="checkbox " value="JK " ><font size="3 "><b>Junior KG</b></font>
          </td>
          <td>
          <input id="A " name="en_jrkg_a "  type="checkbox " value="A " ><b>A</b>&nbsp;&nbsp;
          <input id="B " name="en_jrkg_b "  type="checkbox " value="B " ><b>B</b>&nbsp;&nbsp;
          </td>
        </tr>
    </table>
    <div class="col-md-4 "">
  <input id="english" name="hindi" class="form-control input-md" onclick="EnglishDIV()" type="checkbox" value="HNM" />
</div>
<table width="100%">
  <tr>
    <td><label class="col-md-2 control-label"><b>Standards</b></label></td>
    <td><label class="col-md-2 control-label"><b>Class</b></label></td>
  </tr>
  <tr>
    <td>
      <input id="N" name="hn_ner" type="checkbox" value="N">
      <font size="3"><b>Nursery</b></font>
    </td>
    <td>
      <input id="A" name="hn_nursury_a" type="checkbox" value="A"><b>A</b>&nbsp;&nbsp;
      <input id="B" name="hn_nursury_b" type="checkbox" value="B"><b>B</b>&nbsp;&nbsp;
    </td>
  </tr>
  <tr>
    <td>
      <input id="JK" name="hn_kg" type="checkbox" value="JK">
      <font size="3"><b>Junior KG</b></font>
    </td>
    <td>
      <input id="A" name="hn_jrkg_a" type="checkbox" value="A"><b>A</b>&nbsp;&nbsp;
      <input id="B" name="hn_jrkg_b" type="checkbox" value="B"><b>B</b>&nbsp;&nbsp;
    </td>
  </tr>
</table>




Save checkbox state android xamarin

I am new on xamarin and i am trying to save my checkbox state even if the app is closed because when i close it the checkbox reset to uncheck state...

also.. the image that was changed resets.. is there any way to preserve both?

 protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        SetContentView(Resource.Layout.layout1);

        var seletor = FindViewById<CheckBox>(Resource.Id.checkBox1);
        var imagem = FindViewById<ImageView>(Resource.Id.imageView1);

        seletor.Click += (o, e) => {
            if (seletor.Checked)
                imagem.SetImageResource(Resource.Drawable.estado1);

            else
                imagem.SetImageResource(Resource.Drawable.estado2);

        };
    }




jeudi 28 septembre 2017

Exporting VueJS-rendered HTML with checkbox fails to preserve checked state

My component template contains the following checkbox code:

<div ref="htmlData">
    <input 
        type="checkbox" 
        class="mycb" 
        :id="uniqID" 
        :disabled="disabled"
        v-model="cbvalue"
    >
</div>

(parts removed for simplicity).

I need to create a PDF out of this template (on server). This is what i'm doing in the code:

methods : {
    save () {
        let saveData = {
              'html': this.$refs.htmlData.innerHTML 
            };
        this.$http.post('/api/save',saveData);
    }
}

However, the saved HTML doesn't contain checkbox state, so it always saves an unchecked checkbox.

Here's a slightly modified jsfiddle.

My question is: how can I capture the checkbox state in the rendered HTML?

I tried adding :checked="cbvalue" prop - no luck




How to use a CJuiAccordion Panel with checkboxes in Yii?

I have a panels with different sections. I want the user to be able to select(with a checkbox different selections and all be saved in one field filter. I have it set up and working. However, it is only saving the selections of the last panel to the database. Has anyone had experience using panels with checkboxes in Yii?

Here is my form (in view)

 <div>
    <?php echo $form->labelEx($model,'filters');?>
    <?php
    $id = $modelA->id;
    $groups = ClassGroups::model()-
         >findAll(array("condition"=>"id=$id","order"=>"id"));
    $panels = array();
    foreach($groups as $group)
    {
        $panels[$group->class->name] = $this-
    >renderPartial('_cat',array('model'=>$model, 'pID'=>$group-
      >filter_id),true);
    }

    $this->widget('zii.widgets.jui.CJuiAccordion',array(
    'panels'=>$panels,
    'options'=>array(
        'collapsible'=> true,
        'animated'=>'bounceslide',
        'autoHeight'=>true,
        'style'=>array('minHeight'=>'10'),
        'active'=>true,
    ),

    ));

    ?>
    <?php echo $form->error($model,'filters'); ?>  
</div>

Here is my _cat file which is used in the renderPartial

<?php
$listID = "list_" + $pID;
echo CHtml::activeCheckBoxList($model, 'filters',
        CHtml::listData(
            Class::model()->findAll(
                array("condition"=>"pID=$pID","order"=>"name")),
                'id',
                'name'
            ), 
            array()
       );
?>




In Anuglar 1.5.8 How to make check/uncheck checkbox functionality common for a website?

I am working on a website which has custom designed tables all over the application. All tables have a common functionality of checkbox check/uncheck.

I have used a very simple way to do this. Creating an array of selected ids. On toggle, check if Id exists in the array, then remove else add. And on checkAll/uncheckAll, push all the ids in the array or empty the array.

This code is repeated in each controller of every page that has a table in it.

What I am looking for is some help/suggestion, how to make this functional by defining this code in some service/factory and can be used all over the application.

Toggle check/uncheck:

function toggle(id) {
    let index = vm.selectedIds.indexOf(id)
    if(index >= 0) {
        vm.selectedIds.splice(index, 1);
    }
    else {
        vm.selectedIds.push(id);
    }
}

CheckAll/uncheckAll:

function checkUncheckAll() {
    if(vm.selectedIds.length != vm.renderedList.length && vm.selectedIds.length <= vm.renderedList.length) {
        vm.selectedIds = [];
        angular.forEach(vm.renderedList,function(row){
            vm.selectedIds.push(row._id);
        });
    }
    else {
        vm.selectedIds = [];
    }
}

Let me know if I need to add any other details or any other code.

Thanks.




Dynamic remove a view or override view Android

I have a spinner in my view. Based on spinner value position I am creating dynamic checkbox and data is coming through API. Now when I change Spinner value than I want :

Hide previous checkbox and create new OR override previous checkbox with new one.

Write now I am able to create dynamic checkbox, and when I change spinner value It add new checkbox with current boxes. I cant hide/remove/override them.

Here is my code:

    otherSchool.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    if (allSchoolClassesName.size() > 0) {
                        for (int j = 0; j < allSchoolClassesName.size(); j++) {
                            final CheckBox addonChechbox = new CheckBox(context);
                            addonChechbox.setText("");
                            dialog_checkboox_options_dynamic_school_class.removeView(addonChechbox);
                            addonChechbox.setText(allSchoolClassesName.get(j));
                            addonChechbox.setId(j);
                            addonChechbox.setTextColor(context.getResources().getColor(R.color.White));
                            addonChechbox.setButtonDrawable(context.getResources().getDrawable(R.drawable.selector_checkbox));
                            addonChechbox.setPadding(0, 0, 0, 0);
                            addonChechbox.setTextColor(context.getResources().getColor(R.color.black));
                            addonChechbox.setTypeface(tf);

                            for (int groupIds = 0; groupIds < groupsArray.size(); groupIds++) {
                                if (allSchoolClassesId.get(j).equalsIgnoreCase(groupsArray.get(groupIds))) {
                                    addonChechbox.setChecked(true);
                                    addonChechbox.setButtonDrawable(context.getResources().getDrawable(R.drawable.selector_checkbox));
                                    selectedGroupId.add(allSchoolClassesId.get(addonChechbox.getId()));
                                    selectedGroupType.add("1");
                                }
                            }
                            dialog_checkboox_options_dynamic_school_class.addView(addonChechbox);
                            addonChechbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                                @Override
                                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                                        if (isChecked) {
                                            selectedGroupId.add(allSchoolClassesId.get(addonChechbox.getId()));
                                            selectedGroupType.add("1");
                                        } else {
                                            boolean findSelectedId = selectedGroupId.contains(allSchoolClassesId.get(addonChechbox.getId()));
                                            if (findSelectedId) {
                                                int indexSelectedId = selectedGroupId.indexOf(allSchoolClassesId.get(addonChechbox.getId()));
                                                selectedGroupId.remove(indexSelectedId);
                                                selectedGroupType.remove(indexSelectedId);
                                            }
                                        }
                                }
                            });
                        }
                    }
                } else if (position > 0) {
                    if (schData.length() > 0) {
                        int i = 1;
                        int pos = position;
                        for (int k = 0; schData.length() > 0; k++) {
                            if (position == i) {
                                JSONObject achArray = schData.optJSONObject(k);
                                JSONArray grpList = achArray.optJSONArray("grpList");
                                for (int j = 0; j < grpList.length(); j++) {
                                    final CheckBox addonChechbox = new CheckBox(context);
                                    addonChechbox.setText("");
                                    dialog_checkboox_options_dynamic_school_class.removeView(addonChechbox);
                                    JSONObject classObj = grpList.optJSONObject(j);
                                    String classes = classObj.optString("classes");
                                    JSONObject jsonObjectId = classObj.optJSONObject(Constants.CONSTANT_id);
                                    final String classGroupId = jsonObjectId.optString(Constants.CONSTANT_$id);
                                    addonChechbox.setText("");
                                    addonChechbox.setText(classes);
                                    addonChechbox.setId(j);
                                    addonChechbox.setTextColor(context.getResources().getColor(R.color.White));
                                    addonChechbox.setButtonDrawable(context.getResources().getDrawable(R.drawable.selector_checkbox));
                                    addonChechbox.setPadding(0, 0, 0, 0);
                                    addonChechbox.setTextColor(context.getResources().getColor(R.color.black));
                                    addonChechbox.setTypeface(tf);

                                    for (int groupIds = 0; groupIds < groupsArray.size(); groupIds++) {
                                            if (classGroupId.equalsIgnoreCase(groupsArray.get(groupIds))) {
                                                    addonChechbox.setChecked(true);
                                                    addonChechbox.setButtonDrawable(context.getResources().getDrawable(R.drawable.selector_checkbox));
                                                    selectedGroupId.add(classGroupId);
                                                    selectedGroupType.add("1");
                                            }
                                    }
                                    dialog_checkboox_options_dynamic_school_class.removeView(addonChechbox);
                                    dialog_checkboox_options_dynamic_school_class.addView(addonChechbox);
                                    addonChechbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                                        @Override
                                        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                                            if (isChecked) {
                                                selectedGroupId.add(classGroupId);
                                                selectedGroupType.add("1");
                                            } else {
                                                boolean findSelectedId = selectedGroupId.contains(classGroupId);
                                                if (findSelectedId) {
                                                    int indexSelectedId = selectedGroupId.indexOf(classGroupId);
                                                    selectedGroupId.remove(indexSelectedId);
                                                    selectedGroupType.remove(indexSelectedId);
                                                }
                                            }
                                        }
                                    });
                                }
                                break;
                            }
                                i++;
                        }
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
    });

Editing and suggestion are welcome.




C# Checkbox-Dialog How to uncheck

I have a Windows Forms Dialog in C# which shows Checkboxes for each Element in a Dictionary. The Dialog returns a List with all selected Elements(Checkboxes). However I noticed that if I select a Checkbox and then uncheck it again, the Element is still in the returned List of Selected Elements. How can I fix this? My Dialog looks like this:

public SelectDialog(Dictionary<string, string> Result)
    {
        int left = 45;
        int idx = 0;
        InitializeComponent();
        for (int i = 0; i < Result.Count; i++)
        {
            CheckBox rdb = new CheckBox();
            rdb.Text = Result.Values.ElementAt(i).Equals("") ? Result.Keys.ElementAt(i) : Result.Values.ElementAt(i);
            rdb.Size = new Size(100, 30);
            this.Controls.Add(rdb);
            rdb.Location = new Point(left, 70 + 35 * idx++);
            if (idx == 3)
            {
                idx = 0; //Reihe zurücksetzen
                left += rdb.Width + 5; // nächste Spalte
            }
            rdb.CheckedChanged += (s, ee) =>
            {
                var r = s as CheckBox;
                if (r.Checked)
                    this.selectedString.Add(r.Text);
            };
        }
    }
//Some more Code
}




Metafizzy Isotope script convert checkboxes to buttons

I'm using the Metafizzy Isotope to filter some data: http://ift.tt/2plXF32

Specifically using the Combination filters: http://ift.tt/2fAAiE4

I have the following filter:

<div id="options">
  <div class="option-set" data-group="CAKE">
    <input type="checkbox" value=".ateCake" id="ateCake" /><label for="ateCake">ateCake</label>
    <input type="checkbox" value=".noCake" id="noCake" /><label for="noCake">noCake</label>
  </div>
  <div class="option-set" data-group="PLATE">
    <input type="checkbox" value=".usedPlate" id="usedPlate" /><label for="usedPlate">usedPlate</label>
    <input type="checkbox" value=".usedNapkin" id="usedNapkin" /><label for="usedNapkin">usedNapkin</label>
  </div>
</div>

and the following items:

<div id="grid">
  <div class="item ateCake usedPlate">
    <p>John</p>
  </div>
  <div class="item ateCake usedNapkin">
    <p>Terry</p>
  </div>
  <div class="item noCake">
    <p>Bill</p>
  </div>
  <div class="item noCake">
    <p>Wilson</p>
  </div>
</div>

My Script looks like this:

<script>
// init Isotope
var $grid = $('.grid').isotope();

// store filter per group
var filters = {};

// Process when checkbox state changes
$('#options').on( 'change', function( event ) {
var checkbox = event.target;
var $checkbox = $( checkbox );
var group = $checkbox.parents('.option-set').attr('data-group');

// create array for filter group, if not exists
var filterGroup = filters[ group ];
if ( !filterGroup ) {
  filterGroup = filters[ group ] = [];
}
  // add/remove filter
  if ( checkbox.checked ) {
  // add filter
  filterGroup.push( checkbox.value );
} else {
  // remove filter
  var index = filterGroup.indexOf( checkbox.value );
  filterGroup.splice( index, 1 );
}
var comboFilter = getComboFilter();
$(grid).isotope({ filter: comboFilter });
$filterDisplay.text( comboFilter );
});

function getComboFilter() {
var combo = [];
for ( var prop in filters ) {
var group = filters[ prop ];
if ( !group.length ) {
  // no filters in group, carry on
  continue;
}
// add first group
if ( !combo.length ) {
  combo = group.slice(0);
  continue;
}
// add additional groups
var nextCombo = [];
  // split group into combo: [ A, B ] & [ 1, 2 ] => [ A1, A2, B1, B2 ]
  for ( var i=0; i < combo.length; i++ ) {
  for ( var j=0; j < group.length; j++ ) {
  var item = combo[i] + group[j];
  nextCombo.push( item );
  }
  }
  combo = nextCombo;
}
var comboFilter = combo.join(', ');
return comboFilter;
}
</script>

This works well with checkboxes and filters the results correctly (eg. ateCake and usedPlate etc) I'm trying to convert the "input type="checkbox"..." to "button type="button"..." and keep the same filtering working. My JS is letting me down as I can't work out how to replace the code in the script to work with buttons as the checkbox has a "checked" status which the script uses and the button will need something similar - I've read around what I can on the web and the solution appears to be using the JS to add/remove a class to the button but after several hours of trying its becoming obvious that my JS/Jquery knowledge is too limited.

Could someone kindly help me out by pointing me in the right direction or providing a small sample of code to get me started.

Many thanks.




checkbox is not checked in playback mode of jmeter

In my application i need to select 2 check boxes and click on save. ServiceOrder:serviceTableId:2:serviceorderFormServiceId:on When i recorded the script its got recorded and the value for the checkbox parameter was set as "on".However when i try to playback its not checking the boxes .So my server is throwing an error. So can some one help me here.

I have even tried with fiddler,badboy and even taken developer tools help to see requests .Compared the param/value all are the same nothing new was found via this process.




Wrong checked checkbox Angularjs

I have a problem with a template with AngularJS. The page shows a books list with a checkbox. This is used for batch actions, like delete the books. If the list is too long, the books will be shown in a paged list

The problem is, if I check some of them and change the page number, the checkbox will be checked in the same position. Is easier to understan with this screenshots

Distinct pages and results, same checked checkbox

The get this results I´m using a query in a action.class.php and sending the json like this:

$ejemplares = array();
foreach($data as $ejemplar_bd)
{
    $id_documento = $ejemplar_bd['id_registro'];

    $ejemplar = array();
    $ejemplar['id'] = $ejemplar_bd['id'];
    $ejemplar['idDoc'] = (int)$ejemplar_bd['id_registro'];
    $ejemplar['numregistro'] = (int)$ejemplar_bd['numregistro'];
    $ejemplar['codigo'] = $ejemplar_bd['codigoejemplar'];
    $ejemplar['estado'] = $ejemplar_bd['estado'];
    $ejemplar['signatura'] = $ejemplar_bd['signatura1']."-".$ejemplar_bd['signatura2']."-".$ejemplar_bd['signatura3'];
    $ejemplar['tipo'] =$ejemplar_bd['tipoejemplar'];
    $ejemplar['reservas']=$ejemplar_bd['reservas'];
    $ejemplar['Ubicacion']=$ubicaciones[$ejemplar_bd['id']];
    $ejemplar['Motivo']=$ejemplar_bd['motivo_expurgado'];
    $ejemplar['Editorial']=$data_editorial['valor'];
    $ejemplar['Imprimido']= $ejemplar_bd['imprimido'];
    $ejemplar = array_merge($ejemplar,$fondos[$id_documento][$ejemplar['id']]);

    $ejemplares[] = $ejemplar;

}

$this->json_data = json_encode($ejemplares);

After that, the code in the template is:

<tr ng-repeat="item in data| filter:Buscar | filtroNumregistro:numregistro | filtroCodEjemplar:codEjemplar | filtroNombreNormalizado:nombreFiltro  | orderBy:sort:reverse | limitTo: (currentPage - 1) * pageSize - filtrados.length | limitTo: pageSize track by $index">
        <td class="sf_admin_text sf_admin_list_td_nombre">
          <input type="checkbox" name="ids[]" value="" class="sf_admin_batch_checkbox">
        </td>
        <td class="sf_admin_text">
          
        </td>
        <td class="sf_admin_text">
          
        </td>
        <td class="sf_admin_text sf_admin_list_td_titulo">
            <span><a ng-href=""></a></span><br/>
            <span class="autorListEjemplar" ng-repeat="autor in item.Autor"></span>
        </td>
        <td class="sf_admin_text" style="width:10%;">
          
        </td>
        <td class="sf_admin_text" style="width:10%;">
          
        </td>
        <td class="sf_admin_text" style="width:10%;">
          
        </td>
        <td class="sf_admin_text" style="width:10%;">
          
        </td>
        <td class="sf_admin_text">
          
        </td>
      </tr> etc...

What is going on? What could be the problem?

Thanks in advance




mercredi 27 septembre 2017

Use checkbox to save and read multiple values in Wordpress

I am trying to create a checkbox that saves multiple values like those below, i am working on a costum field for wordpress users. The problem is that I can only save the last checked box if i check any box above that one, it won't work. I want to be able to save as many values as the user checks ,one,two or all. Then I want to be able to read them one by one. I have no idea how to change this. But the saving part on the user_meta is working correctly because it saves the last value.

    <p> <p class="woocommerce-form-row woocommerce-form-row--first form-row form-row-first">
        <label for="area_profissao"><?php _e( 'Área de Intervenção Profissional'); ?></label><br/>
        <input type="checkbox" class="checkbox" name="area_profissao" id="area_profissao1" value="CAPDA" <?php if (get_the_author_meta( 'area_profissao', $user->ID) == 'CAPDA' ) { ?>checked="checked"<?php }?> />Crianças e adolescentes com perturbações do desenvolvimento e aprendizagem <br />
        <input type="checkbox" class="checkbox" name="area_profissao" id="area_profissao2" value="CMPIP" <?php if (get_the_author_meta( 'area_profissao', $user->ID) == 'CMPIP' ) { ?>checked="checked"<?php }?> />Crianças em meio pré-escolar e/ou Intervenção Precoce<br />
        <input type="checkbox" class="checkbox" name="area_profissao" id="area_profissao3" value="CACP" <?php if (get_the_author_meta( 'area_profissao', $user->ID) == 'CACP' ) { ?>checked="checked"<?php }?> />Crianças e adolescentes em contexto pedopsiquiátrico<br />
        <input type="checkbox" class="checkbox" name="area_profissao" id="area_profissao4" value="MA" <?php if (get_the_author_meta( 'area_profissao', $user->ID) == 'MA' ) { ?>checked="checked"<?php }?> />Meio Aquático<br />
        <input type="checkbox" class="checkbox" name="area_profissao" id="area_profissao5" value="SMAI" <?php if (get_the_author_meta( 'area_profissao', $user->ID) == 'SMAI' ) { ?>checked="checked"<?php }?> />Saúde mental do adulto e do idoso<br />
    </p>




JS delete multiple rows from MySQL db with checkbox

I have been trying to figure out how to delete multiple records from MySQL with checkbox and JavaScript.

At this moment I have got working script, that deletes only one record from my db (latest id).

For each product I got checkbox

<input class="checkboxProduct" type="checkbox" name="deleteProduct" value="<?php echo $product['id'];?>">

I have a button and JS form (working - It gets all needed id, and I can display them, but can't delete.

<script>
$(function(){
    var e = document.getElementById( "selectAction" );

    $("#btn-action").click(function(){
        if(e.options[ e.selectedIndex ].value == "delete"){
            var checked = $('.checkboxProduct:checked');
            var id = checked.map(function() {
                return this.value;
            }).get().join(",");
            if (id) {
                checked.closest(".product").remove();
                $.ajax(
                    { url: "<?php echo $_SERVER['PHP_SELF']; ?>?deleteProduct=true?action=select&id=" + id,
                      type: "get",
                      success: function(result){
                          alert("You have successfully deleted these products!");
                      }
                    });
            }
        }
    });
});
</script>

Delete function:

public function deleteProduct(){
    try{

        $product_id = $_GET['id'];

        $stmt = $this->conn->prepare("DELETE FROM products WHERE id=('$product_id')");
        $stmt->execute();

    }
    catch(PDOException $e)
    {
        echo $e->getMessage();
    }
}




C# selenium checkbox under div tag wtih javascript

Im new to selenium, my task is to tick few checkbox which is under a list control, basically the target website is code is like below

Provisional
  • Confirmed
  • Contracted
  • Management
  • Spa Charges
  • Enquiry
  • Billing
  • Cancelled
  • Resident
  • Checked Out

if you look at this code, there is no selected text for the checkboxes rather they have JavaScript. from there what i have to do is

how do i set tick if the checkbox has text of "Confirmed" or "Checked Out"?

Thanks in advance




Jquery display checkbox`s value in div

I have this script which lets me to display value (text) which is next to the checkbox (aspx). On checkbox change text is shown in the div separated by commas. Somehow if any of the checkbox is checked and then di-checked, the value does not disappear from JobIDs var. What im missing here?

 $(document).data('JobNumbers', "");
 $('[id*=projectchk] input').change(function() {
    var JobIDs = "";
    var JobIDs = $(':checked').map(function() {
        return $(this).closest("span").find("label").html();
    }).get().join(', ');
    var JobNumbers = "<label> Reference Job #:</label> " + JobIDs;
    $('#job_numbers').html(JobNumbers);
    if (JobIDs != "") {
        $(document).data('JobNumbers', JobNumbers);
    }
    return false;
 });

So if 3 checkboxes are selected it shows: enter image description here

But even if I di-select all of them it still shows the last one: enter image description here

Thanks.




C# Enable Checkbox In Another App?

I've been able to launch this program (ninjatrader) from within my C# Forms program.

enter image description here

private Process process;
process = System.Diagnostics.Process.Start(@"C:\Program Files (x86)\NinjaTrader 8\bin64\NinjaTrader");

I would like to also enable the checkbox named "Enabled". So far I haven't found a way to do this. I have access to Ninjatrader directly through witing indicators in C# but there is no documentation on how / if you can enable a checkbox. Anybody have any Ideas? - Thanks so much!




Dynamically add checkbox after spinner item selected

I add checkbox dynamically in android when one of spinner items choose, but after checkbox creating the spinner items disable. please help me. Thank you.




Does ag-grid have an api to filter multiple checkbox values?

I'm using angularjs and have a list of checkboxes that I need to able to filter my ag-grid on.

This works fine using radio buttons and calling api.setQuickFilter with the individual value. However, I'm not seeing a way to allow for multiple 'filters' (i.e. checkbox values stored in an array) to function with setQuickFilter. Is there another method I should be using to accomplish this?

Example:
[checkbox] Apple
[checkbox] Bee
[checkbox] Cheerios

Checking box Apple and Cheerios at the same time should return a grid filtered to only show rows that contain the word "Apple" OR "Cheerios".




how combine field (input type=text) with checkbox

WHAT I HAVE

I have this table: TABLE EXAMPLE Whose fields are populated by a mysql database. name of table TABELLA

HTML

<form action='inserisci.php' method='post'
   <input type='checkbox' name='selected[]' value='{$row['id']}'/>
   <input type='number' min='1' max='99' autocomplete='off' name='quantita[]' value='".substr($row['quantita'],3)."'/>
<input style="width:100px;" type="submit" value="Inserisci"/>

PHP INCOMPLETE but work without any quantita results

inserisci.php

if(!empty($_POST['selected'])) { //Se ci sono spunte
    foreach($_POST['selected'] as $check) {
        $query = $pdo->prepare("INSERT INTO tabella1 (nome, cognome, prodotto) VALUES ('$nome','$cognome', (SELECT prodotto FROM tabella WHERE ID=$check))");
        $query->execute();

WHAT I NEED

I need to combine selected[] (CHECKBOX) value with quantita[] and insert all in TABELLA1.

I wish also that the values ​​(quantita) from TABELLA to be displayed in field...so that they can be modified (if needed) and be included in the database along with the other values

FOR EXAMPLE (with quantita):

("INSERT INTO tabella1 (nome, cognome, prodotto, quantita) VALUES ('$nome','$cognome', (SELECT prodotto FROM tabella WHERE ID=$check), '$quantita')") 

How i can do that?




Jquery multiple checkboxes with same id issue

i have this problem with multiple checkboxes with the samen id (#group) if one of these checkboxes is checked another checkbox with the id (#user) should be checked as well. The problem is that with $this it works like a charm but then again you have also the checkboxes without the #group id. I made this fiddle to demonstrate the problem.

http://ift.tt/2xFTOW3

here is the simple Jquery

$('input').on('change', function() {
  var totalSeen = $("input#group:checked").length;
  if ($('#group').prop("checked")) {
    $('#user').prop('checked', true);
    return;
  } else if (totalSeen == 0) {
    $('#user').prop('checked', false);
    return;
  }
});




How to select multiple checkbox from single column data in c# .net

I am trying to make a restaurant form which stores data to a database when a user orders food. If the user comes again and enters his first and last name, the other data, like food and pickup option, should be filed automatically. For the food, I have a checkbox.

Here is the insert code:

string strCheckValue = "";
if (CheckBox1.Checked)
{
    strCheckValue = strCheckValue + "," + CheckBox1.Text;
}
if (CheckBox2.Checked)
{
    strCheckValue = strCheckValue + "," + CheckBox2.Text;
}
if (CheckBox3.Checked)
{
    strCheckValue = strCheckValue + "," + CheckBox3.Text;
}
if (CheckBox4.Checked)
{
    strCheckValue = strCheckValue + "," + CheckBox4.Text;
}
if (CheckBox5.Checked)
{
    strCheckValue = strCheckValue + "," + CheckBox5.Text;
}
if (CheckBox6.Checked)
{
    strCheckValue = strCheckValue + "," + CheckBox6.Text;
}
if (CheckBox7.Checked)
{
    strCheckValue = strCheckValue + "," + CheckBox7.Text;
}

The strCheckValue is stored in the database and gives result like this: ,Samosa,Biryani,Naan

Now I want to select all the food items a user previously selected while ordering the food when he hits remember me button.

For that my code is:

//checkbox value display
CheckBox1.Checked = false;
CheckBox2.Checked = false;
CheckBox3.Checked = false;
CheckBox4.Checked = false;
CheckBox5.Checked = false;
CheckBox6.Checked = false;
CheckBox7.Checked = false;
string aa = dr["ctm_food"].ToString();
string[] a = aa.Split(',');
Label10.Text = a[2].ToString();
foreach (Control cc in this.Controls)
{
    if(cc is CheckBox)
    {
        CheckBox b = (CheckBox)cc;
        for(int j=1; j<a.Length; j++)
        {
            if (a[j].ToString() == b.Text)
            {
                b.Checked = true;
            }
        }
    }
}

In label10, I can see the food that the user ordered. But the checkbox is not getting selected. What will be the right approach to complete this exercise?




Breaking up a checkbox column containing multiple answers into separate columns in R

I have multiple checkboxes in a data set that need to be divided. One of these checkbox questions asks about what states someone practices in (thus there are 50 checkbox options) The data is exported in the format below:

ID  q143

1   1,4,6

But I need it in this format (a true/false format for each individual check box (unchecked/checked)

ID   q143_1  q143_2  q143_3  q143_4  q143_5  q143_6

100    1       0       0       1       0        1

Since this is such a large number of columns that need to be made.. any ideas on how to separate this easily? I was thinking if, then statements but I think that would take a while.

Thanks in advance!




JQuery if x Checkboxes checked change link

i need a jquery script. I have three Chechboxes and two links. If all three checkboxes are checked, it show link 1. If only 1 or 2 checkboxes are checked, it show link 2.

Thanks in advance.

      <div>
     <section title=".agreeCheckbox">
        <div class="agreeCheckbox">
          <input type="checkbox" value="None" id="agreeCheckbox1" name="agreeCheckbox" unchecked onchange="toggleLink(this);"/>
          <label for="agreeCheckbox"></label>
        </div>
      </section>
     </div> 

    <div style="padding-top:100px;">
     <section title=".agreeCheckbox">
        <div class="agreeCheckbox">
          <input type="checkbox" value="None" id="agreeCheckbox" name="agreeCheckbox" unchecked onchange="toggleLink(this);"/>
          <label for="agreeCheckbox"></label>
        </div>
      </section>
     </div> 

<div style="padding-top:100px;">
     <section title=".agreeCheckbox">
        <div class="agreeCheckbox">
          <input type="checkbox" value="None" id="agreeCheckbox" name="agreeCheckbox" unchecked onchange="toggleLink(this);"/>
          <label for="agreeCheckbox"></label>
        </div>
      </section>
     </div>  

    <p><a href="exmaple.com" id="agreeLink" style="display:none;">Jetzt bewerben!</a><a href="none.com" id="dontagreeLink" style="display:inline;">Jetzt bewerben!</a></p>


    <script type="text/javascript">function toggleLink(checkBox)
    {
        var link = document.getElementById("agreeLink");

        if (checkBox.checked)
            link.style.display = "inline";
        else
            link.style.display = "none";

        var link = document.getElementById("dontagreeLink");

        if (checkBox.checked)
            link.style.display = "none";
        else
            link.style.display = "inline";
    }
     </script>




Check custom meta checkbox if it's checked Wordpress

    // Checkbox Meta
add_action("admin_init", "checkbox_init");

function checkbox_init(){
  add_meta_box("checkbox", "Checkbox", "checkbox", "post", "normal", "high");
}

function checkbox(){
  global $post;
  $custom = get_post_custom($post->ID);
  $field_id = $custom["field_id"][0];
 ?>

  <label>Check for yes</label>
  <?php $field_id_value = get_post_meta($post->ID, 'field_id', true);
  if($field_id_value == "yes") $field_id_checked = 'checked="checked"'; ?>
    <input type="checkbox" name="field_id" value="yes" <?php echo $field_id_checked; ?> />
  <?php

}

// Save Meta Details
add_action('save_post', 'save_details');

function save_details(){
  global $post;

if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
    return $post->ID;
}

  update_post_meta($post->ID, "field_id", $_POST["field_id"]);
}

I needed to add a custom meta checkbox on the posts page to enable certain content. The code above is from another stackoverflow answer. When I hit update post, it does save the check value, but I don't understand how to test if it's checked on a page I want to display the content.

doing if (isset()) tests if there is a value, so it's always returning true even if it's not checked. Is there a way I can test for the checked="checked" value? That is what is updating if I inspect element.




Vue checkbox checked and disable at the same time

I need to have checbox which is always checked and disabled at the same time. I tryed to do like this but it doesn't work:

<label class="form-check-label" for="clientAcceptClousure">
                    <input class="form-check-input" type="checkbox" id="clientAcceptClousure"
                           checked disabled 
                    v-model="clientAcceptClousure">
                    Client accept Clousure
</label>

It would be great to have some value to this input: true probably but it doesn't see this.




how to create a custom checkbox in c# which has an outlined text

I want to have a checkbox that has an outline to it's text. I searched for ways to do it and found none. Can anyone help?

Thanks




Can I call ID Element HTML from variabel in jquery

I have some values from JSON ARRAY. The values are Value1,Value2,Value3 And I have checkbox in HTML with ID same like Value. I wanna auto checked the checkbox like values from JSON Array.

I try to do like below

                    var OtherPay = response.OtherPay;
                    var benefit = OtherPay.split(",");
                    var sum = benefit.length;
                    for (var i = 0; i < sum; i++) { 
                        $('#'+benefit[i]).attr('checked',true);
                    }

Thanks before




Make it possible for a jQuery appended label to toggle a checkbox

I have a list with the following markup:

<div class="container">
    <div class="element">
        <input type="checkbox" id="checkbox1" class="toggler">
        <label for="checkbox1">Toggle +</label>
        <div class="more-info">
            <p>...</p>
        </div>
    </div>
    <div class="element">
        ...
    </div>
</div>

The purpuse is to use pure CSS to make the toggle function, so I use this to hide/show the <div class="more-info">...</div>:

.more-info {
    max-height: 0;
    opacity: 0;
    overflow: hidden;
    transition: all .3s ease;
}

.toggler:checked ~ .more-info {
    max-height: 200px;
    opacity: 0;
    overflow: hidden;
}

Under the container, I have a button that will get (in this case it is static) element and append to the container. And this is where I have my problem, the label in the new element won't toggle the checkbox. If I make the checkbox visible and check it directly it works.

I have also made a codepen to illustrate my problem.

Thanks in advance :)




mardi 26 septembre 2017

Codeigniter checkbox value

I want the value that is depended on the checked of the user
1st checkbox = 1, 2nd checkbox = .5, 3rd checkbox .5 that will be inserted/updated to the players column name "player_attitude" if the user check 1st box and 3rd the value of the user will be 1.5 in column "player_attitude"

My table name is players with the columns
player_id,player_fname,player_address,player_attitude

Since the player is already registered i want to add/update player attitude of the user

This is my output

View

<form action="<?php echo base_url('Evaluations/update') ?>" method="POST">
             <?php foreach($evaluationlist as $players): ?>     
           <tbody>
             <tr>
               <td>&nbsp;&nbsp;<?php echo $players->player_lname?>&nbsp;,&nbsp;<?php echo $players->player_fname?> 
               </td>

               <td><center>
                <input type="checkbox" name="checkbox1" value="1">
              </center></td>

                <td><center>
                  <input type="checkbox" name="checkbox2" value=".5">
                </center></td>

                <td><center>
                  <input type="checkbox" name="checkbox3" value=".5">
                </center></td>        
                    <td></td>

               <td>
                <a href="<?php echo base_url('Players/editview/'.$players->player_id) ?>"><span class="b"><span class="glyphicon glyphicon-check">Manage</span></span></a>               
                </td>


             </tr>
           </tbody>

         <?php endforeach; ?>

Controller

public function update($player_id){
    $this->load->model('User_model');
    $this->User_model->checkIfLoggedIn();

    $this->load->view('incf/header');
    $this->load->view('evaluationf/ev_tools');

    $checkbox1 = $this->input->post('checkbox1');
    $checkbox2 = $this->input->post('checkbox2');
    $checkbox3 = $this->input->post('checkbox3');

    $player_attitude = $checkbox1+$checkbox2+$checkbox3;
    //print_r($player_attitude); exit();
    $this->load->model('Evaluation_model');


if($this->Evaluation_model->editview($player_id,$player_attitude)){
        $this->session->set_flashdata('message', [
            'status' => 'success',
            'message' => '&nbsp;<span class="glyphicon glyphicon-ok-circle"> Account Successfully Updated!</span>'
            ]);

        redirect(base_url('Players'));
    }else{
        $this->session->set_flashdata('message', [
            'status' => 'danger',   
            'message' => '&nbsp;<span class="glyphicon glyphicon-remove-circle"> Please try again.</span>'
            ]);

        redirect(base_url('Players'));
    }

}

Model

public function editview($player_id,$player_attitude){

    $data = [               
            'player_attitude' =>$player_attitude                
    ];

    $this->db->where('player_id',$player_id);
    return $this->db->update('players',$data);
}




Save datas from multiple checkbox in a database

2 Questions about save datas from a multiple checkbox (I have few of them in my form) in a database with PDO (PHP). I just show the relevant parts of the code to make it more simple for everyone.

A) The code I wrote works (still saving all datas correctly) but it gives me still a failure message, which you can see below. Why, or what can I do better?

B) It saves the checked checkboxes as an array in the database. Later on I want to change datas by get the datas from the database back into my original form - will it make problems, if its saved like an array? If yes, what would you recommend to do then better.

Warning: implode ( ) : Invalid arguments passed on line ... for

$p2 = implode(',',$product_2);
$p3 = implode(',',$product_3);


$p1 = implode(',',$product_1);  which I defined first seems to be fine 


 <?php
        if(isset($_POST['send']))
        {   
            require("php/tconnect.php");




            $id = $_POST['id'];
            $name = $_POST['name'];
            $date = $_POST['date'];
            $p1 = implode(',',$product_1);
            $p2 = implode(',',$product_2);
            $p3 = implode(',',$product_3);



            $sql = "INSERT INTO database (id, name, date) VALUES (:id, :name, :date, '$p1', '$p2', '$p3')";
            $stmt = $dbh->prepare($sql);
            $stmt->bindValue(':id', $id);
            $stmt->bindValue(':name', $name);
            $stmt->bindValue(':date', $date);

            $stmt->execute();

            echo "Datas saved";

        }?>`


HTML

<input type="checkbox" name="product_1[]" value="apple" id="product_1_apple"  >
                    Apple </label>
                    <label class="checkbox-inline" >
                    <input type="checkbox" name="product_1[]" value="Banana" id="product_1_banana" >
                    Banana </label>
                    ...

and the next tables looks similar

<input type="checkbox" name="product_2[]" value="water" id="product_2_water"  >
                        Water </label>
                        <label class="checkbox-inline" >
                        <input type="checkbox" name="product_2[]" value="juice" id="product_2_juice" >
                        Juice </label>




What's the CSS to uncheck a checkbox which you increase the screen width?

Currently clicking the ☰ label toggles the mobile menu in mobile width.

Increasing screen width hides mobile menu.

PROBLEM: Toggled menu is still checked when resized to mobile width.

NEED: Checkbox to uncheck when the screen width exceeds X pixels.

Code so far:

    <!--toggle-->
                    <li><a class="menu" href="#">
                    <label for="toggle">☰</label>
                    <input id="toggle" type="checkbox">
                    <div class="togglemenu">test</div>
                    </a></li>

    /*toggle menu*/

    #toggle {
        display: none; /*hide checkbox*/
    }

#toggle:checked + .togglemenu { /*show menu on click*/
    display: block;
}

    .togglemenu {
        width: 100px;
        height: 100px;
        background: #333;
        top: 60px;
        right: 0;
        position: absolute;
        display: none;
    }

    /*hide menu width increase*/

    @media screen and (min-width: 480px) {
        .menu {
            display: none;
        }
    }

I'm sure I've done it before, just forgotten over time. Any ideas? Help appreciated, thanks.




Trying to Handle Removing Item From Array with Checkbox De-Select

I am trying to handle pushing and removing elements from an array based on whether a checkbox is checked or not in an Angular 2 app. I know native HTML can handle some form of this logic, but I'm trying to figure out exactly what to target. This is what my function looks like:

private onOptionSelected(option)
{
    let optionObj = {
        option: option,
        complex: false
    };

    if (option)
    {
        this.record.requestedOptions.push(optionObj);
    }
    else if (!option)
    {
        this.record.requestedOptions.splice(option);
    }
}

Right now, the first part works. I can check one of the checkboxes and that item gets added to the array and saved in my backend.

However, when I uncheck that item, rather than removing it from the array, that action ALSO triggers a new item being added to the array.

So how do I handle the negative case here -- where an item is unchecked, and should thus be removed from the array? Can I target a native HTML attribute like "checked" or "!checked" or something similar?

By the way, this is what my html/view looks like:

    <div>
       <md-checkbox 
          (change)="onOptionSelected('A')">Option A
       </md-checkbox>

       <md-checkbox
         (change)="onOptionSelected('b')">Option B
       </md-checkbox>

       <md-checkbox
         (change)="onOptionSelected('c')">Option C
       </md-checkbox>
   </div>




Unable to clear checkboxes using Watir

I am trying to clear two currently checked checkboxes using Watir.

The HTML contains the following:

<input type="checkbox" name="checkbox" class="notifications-settings-tickbox" value="PLAYER" id="PLAYER-settings-checkbox" checked="checked">

<input type="checkbox" name="checkbox" class="notifications-settings-tickbox" value="MUSIC" id="MUSIC-settings-checkbox" checked="checked">

When the page is loaded, both of these are checked. I am trying to clear them both.

My code is:

    $website.checkboxes(:class => "notifications-settings-tickbox").each do |checkbox|
        checkbox.clear
     end

But the checkboxes remain checked. I'm not receiving any error message either so i'm a bit unsure as to what's going on.

I've also tried to directly clear each checkbox:

$website.checkbox(:id => "PLAYER-settings-checkbox").clear
$website.checkbox(:id => "MUSIC-settings-checkbox").clear

But have the same outcome.




How to merge values ​to a checkbox or solve it with 2 query or foreach (i don't know)

I have a table (name: tabella) in mysql db (EXAMPLE: IMAGE) with a checkbox and a form (and other data that aren't useful now). I need to insert quantita[] in a other table (name: tabella1) with selected[]. The values of quantita field ​​can be edited (it is an input type=number). but when I pass the data to inserisci.php it gives back all quantita data from TABELLA and not the new values SELECTED... I don't know if I explained it well (I deleted everything that was not useful and I don't know if it works as well as now).

<?
echo "<form action='inserisci.php' method='post'>"; 

foreach ($pdo->query("SELECT * FROM tabella") as $row) {
echo "
<input type='checkbox' name='selected[]' value='{$row['id']}'/>
<input type='number' min='1' max='99' autocomplete='off' name='quantita[]' value='{$row['quantita']}'/>";
}
?>
<td align="left"><input style="width:100px;" type="submit" value="Inserisci"/>
        </form>

inserisci.php

foreach($_POST['selected'] as $check) {
        $query = $pdo->prepare("INSERT INTO tabella1 (prodotto, quantita) VALUES ((SELECT prodotto FROM tabella WHERE ID=$check))");
        $query->execute();}




Save checkbox button state using userdefaults in swift

view controller had two check boxes buttons 1.chekcIn 2.checkOut

am saving the checkIN [ checkbox button] status in user defaults, working fine but when am using that userdefaults key in Nextviewcontroller its always showing true and not running into false block this is the code

inHomeview controller

@IBAction func CheckInButtonClick(_ sender: UIButton) {


        for senderdata in checkINOUT {
            senderdata.setImage( UIImage(named:"uncheck1"), for: .normal)
            print("uncheck is called")

        }


        sender.setImage(UIImage(named:"check1"), for: .normal)
         prefs.set(true, forKey: "check")
    prefs.synchronize()

    }

nextviewcontroller

   override func viewDidLoad() {
        super.viewDidLoad()
{        

 let prefs:UserDefaults = UserDefaults.standard
  if  prefs.bool(forKey: "check") ==true
        {
        print("select")

        } else {

            print("unselect")
        }

 }     

check box select its execute main block if unselect execute else block

how to over come this problem where I did mistake




Transferring values of programmatically created checkboxes into the next Activity?

In my Activity_fruits there is a spinner with fruit names like "Apple, Pineapple, ..., etc.). When the user selects one of the items in the spinner, a series of check boxes is generated.

These checkboxes are names of dishes that come from my Dishes.java class. Every different fruit selected by the user from the spinner will create different dish checkboxes depending on which dishes corresponds to which fruit.

My question is: how do I pass the value/text of these generated check boxes into my next activity Activity_checkout when they are selected/checked by the user?

I have code below that seems to run fine BUT the value/text of the checked checkboxes (contained in the test[0] intent) isn't being transferred to the next activity.

Below is my views and controls declarations:

public class Activity_fruits extends Activity {

    // Instantiate Fruits class
    private Fruits fruits = new Fruits();
    private Dish dish = new Dish();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fruits);

        final String passToNextActivity = getIntent().getStringExtra("selectedDish");

    final String fruitStr = spnFruits.getSelectedItem().toString();
    final LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
    final int count = ll.getChildCount();
    final String[] test = {""};
...

And below is how I programmatically generated check boxes for dishes (grabbed from my Dish.java class). There is no xml layout for my CheckBoxes:

 // Create different dish checkboxes for each food selection in the spinner
        spnFruits.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String fruitStr = (String) adapterView.getItemAtPosition(i);
                TextView txtRestaurant = (TextView) findViewById(R.id.txtFruits);

                //This TextView is just to confirm the fruit that the user selected
                txtFruit.setText("You selected the Fruit: " + fruitStr);

                final List<String> listFruits = fruits.getFruits(fruitStr);

                // Clears the layout everytime the user selects another fruit from the spinner
                ll.removeAllViews();

                for (int j = 0; j < listFruits.size(); j++) {
                    final CheckBox cbDishes = new CheckBox(Activity_fruits.this);
                    cbDishes.setText(listFruits.get(j));
                    cbDishes.setTag(listFruits);

                    ll.addView(cbDishes);

                    ////////////
                    cbFruits.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {

                                for (int x = 0; x < count; x++) {
                                    View v = ll.getChildAt(x);

                                    if (v instanceof  CheckBox){
                                        test[0] = ((CheckBox) v).getText().toString(); } //My problem:  This code is not storing any string at all
                                }
                            }
                        });
                    ////////////
                }
            }

        });

        /////////////

        Button btnNextActivity = (Button) findViewById(R.id.btnNextActivity);

        btnNextActivity.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Activity_fruits.this, Activity_checkout.class);
                intent.putExtra("selectedDishes", test[0]); //My Problem:  The test[0] is supposed to contain all user selected check boxes but it doesn't.
                startActivity(intent);
            }
        });
    }
}

And my next activity Activity_checkout is:

public class Activity_checkout extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_checkout);

        final String dishes = getIntent().getStringExtra("selectedDishes");

        TextView txtSelectedDish = (TextView) findViewById(R.id.txtSelectedDish);

        txtSelectedDishs.setText("Your selected dishes are:  " + dishes.toString()); //My Problem:  food.dishes.toString() is not returning a value meaning the checkbox value from Activity_fruits wasn't successfully transferrred over.

    }
}




How to call that variable in other page (foreach)

I have this input module:

echo "<form action='inserisci.php' method='post'>";
echo "<input type='number' min='1' max='99' autocomplete='off' name='quantita' value='{$row['quantita']}'/>"

I insert in the field QUANTITA the values ​​extracted from mysql db, namely {$row['quantita']}.

The original values in the field, sometimes, has to be modified, but when i change they, on the next page (inserisci.php), it always returns only the values from the database and only the first quantita values that i have checked!!

FULL CODE:

            echo "<form action='inserisci.php' method='post' enctype='application/x-www-form-urlencoded'>";
            echo "<table align='left' border='10' width='40%'";
            echo "<tr><th></th><th>Qnt</th><th>Prodotto</th><th>Term</th><th>Data</th></tr>";

        foreach ($pdo->query("SELECT * FROM tabella") as $row) {

        echo "<tr><td><input type='checkbox' name='selected[]' value='{$row['id']}'/><br /></td><td>

        <input type='number' min='1' max='99' autocomplete='off' name='quantita' value='{$row['quantita']}'/>


    </td><td>{$row['prodotto']}</td><td>{$row['terminale']}</td><td>{$row['data']}</td></tr>";        }
        echo "</table>";        ?> 
//------------------------------------------------------------------------          
        <table width="500" border="10">
          <tr>
            <td width="987" align="center"><b>PRENOTAZIONE PRODOTTO</b></td>
          </tr>
          <tr>
            <td>
              <table width="633">
                <tr>
                  <td width="500">Nome:</td>
                    <td width="420" align="left"><input type="text" autocomplete="off" name="nome" size="70" onkeyup="maiuscola(this)"/>
                  </td>
                </tr>
                <tr>
                  <td width="500">Cognome:</td>
                    <td width="420" align="left"><input type="text" autocomplete="off" name="cognome" size="70" onkeyup="maiuscola(this)"/>
                  </td>
                </tr>
                <tr>
                  <td>Numero di tel.:</td>
                    <td width="420" align="left"><input type="text" step="any" size="20" autocomplete="off" min="1" name="numero"/>
                  </td>
                </tr>
                <tr>
                  <td>Note:</td>
                    <td width="420" align="left"><input type="text" autocomplete="off" size="70" name="note" onkeyup="maiuscola(this)"/>
                  </td>
                </tr>                                           
                <tr>
                  <td></td>

            <td align="left"><input style="width:100px;" type="submit" value="Inserisci"/>
                </tr>
                </form>
              </table>
            </td>
          </tr>
        </table>

inserisci.php

$nome = $_POST['nome'];
$cognome = $_POST['cognome'];
$quantita = $_POST['quantita'];
$numero = $_POST['numero'];
$note = $_POST['note'];
    echo $quantita;




javascript sum function + tax

i have a one problem. please help me.

i have a javascript code but doesnt work now.

that code:

<input type="checkbox" id="konut1" name="tasinmazsecim" class="tasinmazsecim" value="489" /><span>1-100m2</span> 
    <span id="payment-total" style="text-decoration:underline;">0</span>
    <input id="input" type="text" value="0"/>


    window.onload=function(){
var inputs = document.getElementsByClassName('tasinmazsecim'),
    total  = document.getElementById('payment-total');

 for (var i=0; i < inputs.length; i++) {
    inputs[i].onchange = function() {
        var add = this.value * (this.checked ? 1 : -1);
        total.innerHTML = parseFloat(total.innerHTML) + add
        var new_total = parseFloat(document.getElementById('input').value);
      console.log(new_total);
        document.getElementById('input').value=new_total + add
    }
  }
}

checkbox value + other checkbox value this worked.

but i need checkbox value + 0.07 tax + 50

please help me.




jQuery / Angular - How can I assign a value to MaterializeCSS checkbox?

I've used materialize checkboxes within forms in my single-page angular app, and I need to give these a value based on whether or not they are checked, like 'true' if checked and 'false' if not.

I've tried using the code below to assign values within a button's click handler function in my controller, but angular is returning the error 'TypeError: elem.nodeName is undefined' on load, and the button no longer functions.

if (angular.element('#employeePaymentForm input[type="checkbox"]').is(':checked')) {
    angular.element(this).val('Yes');
    console.log(angular.element(this).val());
} else {
    angular.element(this).val('No');
    console.log(angular.element(this).val());
}

Example checkbox HTML:

<div tooltipped class="tooltipped col-xs-12 col-sm-6 col-md-2" data-position="bottom" data-delay="800" data-tooltip="Select to reset hours and pay to zero at period end">

    <input id="zeroiseHoursCheckbox" name="zeroiseHoursCheckbox" type="checkbox" class="filled-in notRequired notRequired checkbox">

    <label for="zeroiseHoursCheckbox">Zeroise at Period End?</label>

</div>