lundi 31 août 2015

How can I make content-dependent checkboxes, with a check-all box in JavaScript?

I have searched for hours, and tried many things, but I can't get it to work. This is my problem: I'm trying to make some sort of summary of a book series I enjoy, in html files (offline, though). And I want to be able to show/hide content based on a few checkboxes at the top of a page. So when I only check the "book 2" checkbox, no content from previous or later books may appear. Secondly I want a check-all button, too. For these 2 things I have 2 scripts, and they do work independently, but when I click the check-all box, the content does not automatically appear, and I'm stuck to why that is. Here's my code (HTML)

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <script src="Scripts.js"></script>
    </head>
<body>
    <p> <input type="checkbox" onchange="ToggleCheck(this);"> Check all</p>
    <p> <input type="checkbox" name="bookbox" onchange="ShowHide('Book0', this);"> Book 0</p>
    <p> <input type="checkbox" name="bookbox" onchange="ShowHide('Book1', this);"> Book 1</p>
    <p> <input type="checkbox" name="bookbox" onchange="ShowHide('Book2', this);"> Book 2</p>
    <p> <span class="Book0">Book 0 content. </span>
        <span class="Book1">Book 1 content. </span>
        <span class="Book2">Book 2 content. </span>
        <span class="Book1">Book 1 content. </span>
    </p>
</body>
</html>

And here's the attached JS file

function ToggleCheck(source) {
    var checkboxes = document.getElementsByName('bookbox');
    for(var i=0, n=checkboxes.length;i<n;i++) {
        checkboxes[i].checked = source.checked;
    }
}

function ShowHide(a, b) {
    var vis = (b.checked) ? "inline" : "none";
    var book = document.getElementsByClassName(a);
    for (var i = 0; i < book.length; i++) {
        book[i].style.display = vis;
    }   
}

I do apologize to sign up for this site just for this, but if someone could help me, I would be very gratefull. Thank you in advance!




When I choose two checkbox one change the value of the other

So guys, I am new in C# and I am doing Course of Programming(professional programmer),but as I am new to this language of programming,I am kind of lost in some parts. Please if you guys can help me, I will thanks.

I choose two CheckBox and the Label doens't get the two values to do one result. One changes another.

Example :

I choose CheckBox1 and CheckBox2 but just one of the two CheckBox will return the value to the Label1. I want to make it the Label1(result) gets the two values or more values to put together in one result. How can I do that ?




Stopping click propagation with custom checkboxes

I'm using custom styled checkboxes where I've replaced the default checkbox with font-awesome icons: link to image

The problem is that when I double click any of the items, although the checkboxes function, the clicks also get interpreted as if I'm highlighting text: link to image

Anyone know how I can get the same click behavior as a standard checkbox control where the clicks don't propagate down to the text?

Here's the code I'm using for the checkboxes:

CSS:

input[type=checkbox] {
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
} 
input[type=checkbox] + label:before {
    font-family: FontAwesome;
    display: inline-block;
    letter-spacing: 10px;
    font-size: 1.2em;
    width: 1.4em;
    content: "\f096";
}
input[type=checkbox]:checked + label:before {
    content: "\f046";
}

HTML:

  <div>
    <input type="checkbox" id="a">
    <label for="a">foo</label>
  </div>
  <div>
    <input type="checkbox" id="b">
    <label for="b">bar</label>
  </div>
  <div>
    <input type="checkbox" id="c">
    <label for="c">blah</label>
  </div>




Label don't change value when I choose one CheckBox

Hello for everyone I am new here,sorry if this post doens't match with at all with how should be,because It's my first post this.

I am wanting to change the value of the Label when I choose one CheckBox,but It's seems that the Label just changes when I click in the Label. I was looking for see if the Label had some Events for make work it but I didn't found one. The Label it's in another groupBox,It's seems like that :

In one GroupBox has 3 CheckBox and i want that when i choosing one or all from that CheckBox will change the value of the Label in the another GroupBox.

Please guys,help me here,I am really wanting to understand why It's not working.




Zend formBuilder raising exception on checkbox rendering

I'm trying to use Zend Framework 2 formBuilder with annotations in my model, but it's throwing an exception when trying to render a checkbox:

Model property annotation:

/**
 * @var boolean $Content
 *
 * @ORM\Column(name="Content", type="boolean", nullable=false)
 * @Annotation\Attributes({"type":"checkbox"})
 * @Annotation\Options({"label":"Value:"})
 * @Annotation\AllowEmpty({"true"})
 * @Annotation\Filter({"name":"Boolean"})
 */
protected $Content = true;

HTML from form template (phtml)

        <div id="Content">
            <?= $form->get('Content)->getLabel(); ?>
            <?= $this->formCheckbox($form->get('Content)); ?>
        </div>

When it tries to run the formCheckbox, it is throwing

 PHP Fatal error:  Uncaught exception 'Zend\\Form\\Exception\\InvalidArgumentException' with message 'Zend\\Form\\View\\Helper\\FormCheckbox::render requires that the element is of type Zend\\Form\\Element\\Checkbox' in /media/finaoweb/doctrine-test/vendor/zendframework/zend-form/src/View/Helper/FormCheckbox.php:29
Stack trace:
#0 /media/finaoweb/doctrine-test/vendor/zendframework/zend-form/src/View/Helper/FormInput.php(101): Zend\\Form\\View\\Helper\\FormCheckbox->render(Object(Zend\\Form\\Element))
#1 [internal function]: Zend\\Form\\View\\Helper\\FormInput->__invoke(Object(Zend\\Form\\Element))
#2 /media/finaoweb/doctrine-test/vendor/zendframework/zend-view/src/Renderer/PhpRenderer.php(393): call_user_func_array(Object(Zend\\Form\\View\\Helper\\FormCheckbox), Array)
#3 /media/finaoweb/doctrine-test/module/Application/view/application/itemoption/edititemoption.phtml(34): Zend\\View\\Renderer\\PhpRenderer->__call('formCheckbox', Array)

Looking at the stack trace before the formCheckbox() call, I can see the element attributes including 'type => "checkbox"'

I have even tried changing 'checkbox' to \Zend\Form\Element\Checkbox and Zend\\Form\\Element\\Checkbox with no luck.

Any help is appreciated.




Executing js before AutoPostBack of checkbox

NET 4 and asp checkbox which does an auto post back inside a user control and I need to call a js before that autopostback occurs.

Editing the onclick attribute of InputAttributes was of no help. It doesn't let me do that.

Tried registering on submit event or startupscript which was of no help. Unless there's a way to register on submit when checkbox was clicked or unclicked. Haven't found this yet. When I do register on submit my function gets called whenever anything happens on the page.

Don't want to start including jquery on my page just for this.

My last option would be to submit the form in js without AutoPostBack, however would love a solution using Register on submit or register startup instead of this. I want to be consistent with my code.

Thanks -P




Rails "undefined method" error in forms

I'm trying to create a simple form with a checkbox using Rails, however I keep getting the error: undefined method `recursive' for

My views:

<h1>Create A New Program</h1>
<br>
<%= form_for :program, url: programs_path, :html => {:method => "post"} do |f| %>
  <%= f.check_box(:recursive, {:id => "recursive"}, "recursive", "adhoc") %>Recursive
  <br><br>
  <%= f.submit(:Save) %>
<% end %>

My Controller:

class ProgramsController < ApplicationController
  def new
    @program = Program.new
  end

  def index
    @programs = Program.all
  end

  def edit
    @program = Program.find(params[:id])
  end

  def create
    @program = Program.new(program_params)

    if @program.save
      redirect_to programs_path
    else
      render "new"
    end
  end
end

And my model:

class Program < ActiveRecord::Base
end

I'm struggling to figure out to find a clue as the syntax for check_box does look right. Can someone please help me out? Thanks in advance!




How to find CheckBox control in DataGridView?

How to add item of checkbox in datagridview(2) to datagridview(1) for show data in checkbox(database) on datagridview(1)

My code

DataTable a = tablebill();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
    bool checkBoxValue = Convert.ToBoolean(row.Cells[0].Value);
    if (checkBoxValue == true)
    {
        a.Rows.Add(row.Cells["Products"].Value);
    }
    else { }
}
dataGridView1.DataSource = a;




Automatically check a checkbox if data is in database

I am creating an edit page right now where an admin can edit a few settings inside the database from the admin panel. Everything is working so far except the work with checkboxes.

I created four checkboxes and everytime a checkbox is checked, the data will be added to my database as a string and inside the database those values are seperated with an ","! Now I want to make an edit page where admin can change those settings.

Therefore I created the following:

<div class="form-group">
 <label class="control-label col-md-3 col-sm-3 col-xs-12">Menüarten:</label>
    <div class="col-md-9 col-sm-9 col-xs-12">
    <input type="checkbox" name="menuearten[]" value="Menü traditionell" <?php if($_SESSION['data']['menueart'] == 'Menü traditionell') echo 'checked = "checked"' ?>> 1. Menü traditionell <? if ($_SESSION['data']['menueart'] == "Menü traditionell") echo "<span class='label label-success'>Aktuelle Auswahl</span>"; ?><br />
    <input type="checkbox" name="menuearten[]" value="Menü vegetarisch" <?php if($_SESSION['data']['menueart'] == 'Menü vegetarisch') echo 'checked = "checked"' ?>> 2. Menü vegetarisch <? if ($_SESSION['data']['menueart'] == "Menü vegetarisch") echo "<span class='label label-success'>Aktuelle Auswahl</span>"; ?><br />
    <input type="checkbox" name="menuearten[]" value="Menü Nudelgerichte"<?php if($_SESSION['data']['menueart'] == 'Menü Nudelgerichte') echo 'checked = "checked"' ?>> 3. Menü Nudelgerichte <? if ($_SESSION['data']['menueart'] == "Menü Nudelgerichte") echo "<span class='label label-success'>Aktuelle Auswahl</span>"; ?><br />
    <input type="checkbox" name="menuearten[]" value="Menü Gebackenes"<?php if($_SESSION['data']['menueart'] == 'Menü Gebackenes') echo 'checked = "checked"' ?>> 4. Menü Gebackenes <? if ($_SESSION['data']['menueart'] == "Menü Gebackenes") echo "<span class='label label-success'>Aktuelle Auswahl</span>"; ?><br />

With $_SESSION['data']['menueart'] I get all my data from the database. This is working already for other fields too. My code for that is:

$user_id = $_GET['id'];
$get_schulen = "SELECT * FROM schule WHERE id = '$user_id'";
$result_get_schulen = mysqli_query($connect, $get_schulen);
$_SESSION['data'] = mysqli_fetch_assoc($result_get_schulen);

Now my problem is, that I want to check all checkboxes when an admin visits the edit page which are already inside my database. Here is a picture of one of my current entry: http://ift.tt/1fR9F7O

So therefore if I am at my edit page, the first two checkboxes should be checked but they aren´t. Can someone tell me what is wrong with my IF condition or what should I change so that if a string exists in my database already, than the checkbox is checked automatically.




Meteor checkbox group - At least one checkbox selected

This is the checkboxes i have so far. I would like to have at least one checkbox checked all the time - how can this be accomplished?

HTML:

    <form>
        <ul>
            {{#each checkbox}}
            <li>
                <input type="checkbox" checked="{{checked}}" class="toggle-checked"> {{name}}: {{checked}}
            </li>
            {{/each}}
        </ul>
    </form>

JS:

    Cbtest = new Mongo.Collection('cbtest');

    Template.checkbox.helpers({
        checkbox: function () {
            return Cbtest.find();
        }
    });

    Template.checkbox.events({
        "click .toggle-checked": function () {
           var self = this;
            Meteor.call("setChecked", self._id, !self.checked);
        }
    });

    Meteor.methods({
        setChecked: function (checkboxId, setChecked) {
            Cbtest.update(checkboxId, {
                $set: {
                    checked: setChecked
                }
            });
        }
    });

I'd like to avoid jquery and stick with javascript and underscorejs solely.

Thanks in advance! Vin




Whenever I click the checkbox the area should be highlighted using imagemapster

Whenever I click a checkbox the area should be highlighted or whenever I click the area the checkbox would be automatically ticked

This is my code jQuery code.

 $(document).ready(function (){

    $('img').mapster({
    singleSelect : false,
    clickNavigate : true,
    fill:false,
    stroke:true,
    strokeOpacity:1,
    strokeWidth:1,
    strokeColor:'ff0000',
    mapKey:'data-text',
    listKey:'data-text',
    });
});

for 1 sample of checkbox

<label class="checkbox-inline">
    <input type="checkbox" data-text="lipsize" id="inlineCheckbox6">Lip size and/or volume
</label>




Primefaces Checkboxmenu Default String Modification

User Story:

When ticking 0 to n Objects from a Primefaces Checkboxmenu (also called selectCheckboxMenu), the displayed String enter image description here

  • has to be Object.name if 1 Item is selected.

  • has to be every Objects name whoms Object has been selected, seperated by Commas, if more than 1 Item is selected.

  • has to be a default value, if nothing is selected.

Question:

What do i need to do in order to set the displayed String dynamically (like this), when for example a selectionchanged event is thrown?

Additional Info

Im using Primefaces in Version 5.2, JSF in Version 2.2 and Omnifaces in Version 1.5




dimanche 30 août 2015

Check all with specific value in checkbox using jquery

I got some problem when I want to develope checkall function using jquery.

I put all checkboxes in table to make it clear and would like to check all checkbox with value in input.

For example, when I click the checkbox with value type1, then all checkboxes value including type1 will be checked as well (type1, type1-1 and type 1-2).

HTML:

<table>
    <tr class='type1'>
      <td><input type="checkbox" value="type1"></td>
      <td>Type_1<td>
    </tr>
    <tr class='type1-1'>
      <td><input type="checkbox" value="type1-1"></td>
      <td>Type_1-1<td>
    </tr>
    <tr class='type1-2'>
      <td><input type="checkbox" value="type1-2"></td>
      <td>Type_1-2<td>
    </tr>
    <tr class='type2'>
      <td><input type="checkbox" value="type2"></td>
      <td>Type_2<td>
    </tr>
    <tr class='type2-1'>
      <td><input type="checkbox" value="type2-1"></td>
      <td>Type_2-1<td>
    </tr>        
</table>

Is it possible to do it with jquery?

Thank you.




ExpandabeListView with checkbox in ViewPager Lag/slowness

I have a lag problem in expandablelistview which includes a checkbox in a viewpager. I even use viewholder pattern(i dont use for groups because they can be at most 4 so not needed. I use it on childs) but still something is causing lag when scroll or whatever i do in that page is a little bit laggy(no other pages causes lag, I have only 4 page in my viewpager.). Here is my code;

@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {

    if (convertView == null) {
        infalInflater = (LayoutInflater) this.context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.task_group,parent,false);
    }

    LinearLayout bg = (LinearLayout) convertView.findViewById(R.id.taskGroupBg);
    TextView tv = (TextView) convertView.findViewById(R.id.closenessTv);

    CharSequence[] texts = context.getResources().getStringArray(R.array.closeness_texts);

    long id = this.getGroupId(groupPosition);

    if(id == -1){
        bg.setBackground(setGroupBackgroundColor(Color.parseColor(groupBgColors[0])));
        tv.setText(texts[0]);
    }else if(id == 0){
        bg.setBackground(setGroupBackgroundColor(Color.parseColor(groupBgColors[1])));
        tv.setText(texts[1]);
    }else if(id == 1){
        bg.setBackground(setGroupBackgroundColor(Color.parseColor(groupBgColors[2])));
        tv.setText(texts[2]);
    }else {
        bg.setBackground(setGroupBackgroundColor(Color.parseColor(groupBgColors[3])));
        tv.setText(texts[3]);
    }


    return convertView;
}

@Override
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {

    ViewHolder holder;

    if (convertView == null) {
        holder = new ViewHolder();
        convertView = infalInflater.inflate(R.layout.task_row,parent,false);

        // Create a ViewHolder and store references to the two children views

        holder.bg = (LinearLayout) convertView.findViewById(R.id.taskRowBg);
        holder.text = (TextView) convertView.findViewById(R.id.taskTv);
        holder.calendar =(LinearLayout) convertView.findViewById(R.id.calendar);
        holder.cb = (CheckBox) convertView.findViewById(R.id.taskCb);
        holder.dayRemain = (TextView) convertView.findViewById(R.id.dayRemainTv);
        //holder.cb.setEnabled(false);

        // The tag can be any Object, this just happens to be the ViewHolder
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    final Task t = this.childData.get((int) getGroupId(groupPosition)).get(childPosition);

    lis = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            checked.get((int)getGroupId(groupPosition))[childPosition] = isChecked;
            db = new TaskDb(context);
            if(isChecked)
                t.setStatus(DefaultValues.TASK_STATUS_COMPLETED);
            else
                t.setStatus(DefaultValues.TASK_STATUS_NOTDONE);
            db.updateTask(t);
        }
    };


    String text = t.getText();
    long id = this.getGroupId(groupPosition);
    if(id == -1)
        holder.bg.setBackgroundColor(Color.parseColor(rowBgColors[0]));
    else if (id == 0)
        holder.bg.setBackgroundColor(Color.parseColor(rowBgColors[1]));
    else if (id == 1)
        holder.bg.setBackgroundColor(Color.parseColor(rowBgColors[2]));
    else
        holder.bg.setBackgroundColor(Color.parseColor(rowBgColors[3]));

    holder.text.setText(text);
    // holder.dayRemain.setText(findHourDif(System.currentTimeMillis(),t.getRemindDate()));
    int status = t.getStatus();

    long curTime = System.currentTimeMillis();
    if(t.getRemindDate() < curTime && status == DefaultValues.TASK_STATUS_NOTDONE)
        t.setStatus(DefaultValues.TASK_STATUS_OVER_NOTDONE);
    else if(t.getRemindDate() < curTime && status == DefaultValues.TASK_STATUS_COMPLETED)
        t.setStatus(DefaultValues.TASK_STATUS_OVER_DONE);

    status = t.getStatus();
   //holder.cb.setTag(childPosition);
    holder.cb.setOnCheckedChangeListener(null);
    holder.cb.setChecked(checked.get((int)getGroupId(groupPosition))[childPosition]);
    holder.cb.setOnCheckedChangeListener(lis);
    if(status == DefaultValues.TASK_STATUS_OVER_DONE || status == DefaultValues.TASK_STATUS_OVER_NOTDONE) {
        holder.text.setPaintFlags(holder.text.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
    }
    else {
        holder.text.setPaintFlags(holder.text.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
       // holder.text.invalidate();
    }

    DateConverter dc = new DateConverter(context,t.getRemindDate());
    String[] dateStr = dc.getTaskDateFormat();
    holder.calendar.removeAllViews();
    holder.calendar.addView(new DrawCalendar(context, dateStr));//drawCalendar(dateStr[0],dateStr[1]));
    holder.calendar.invalidate();


    return convertView;

//My Calendar drawer probably has no effect but still i will put

 public class DrawCalendar extends View {

private RectF small = new RectF(),big = new RectF();
private Paint p = new Paint();
private Paint textP = new Paint();
private Paint.FontMetrics fm = new Paint.FontMetrics();
private String[] dates;
private float radiusSize = 20f;

public DrawCalendar(Context context,String[] dates) {
    super(context);
    this.dates = dates;
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    int width = canvas.getWidth();
    int height = canvas.getHeight();

    int smallH =height/2;

    small.set(0, 0, width, smallH);
    p.setColor(Color.parseColor("#6C4D4D"));
    p.setStyle(Paint.Style.FILL);
    p.setAntiAlias(true);
    drawAsymmetricRoundRect(canvas, small, new float[]{radiusSize, radiusSize, 0, 0}, p);
    /*p.setStrokeWidth(2);
    p.setStyle(Paint.Style.STROKE);
    p.setColor(Color.parseColor("#444444"));
    drawAsymmetricRoundRect(canvas, small, new float[]{10, 10, 0, 0}, p);*/


    textP.setTextSize(60);
    textP.setColor(Color.parseColor("#dddddd"));
    textP.setTextAlign(Paint.Align.CENTER);
    textP.getFontMetrics(fm);
    int textPos = smallH / 2 + smallH / 4;
    canvas.drawText(dates[1], width / 2, textPos, textP);

    big.set(0, smallH, width, height);
    p.setStyle(Paint.Style.FILL);
    p.setColor(Color.parseColor("#fafafa"));
    drawAsymmetricRoundRect(canvas,big,new float[]{0,0,radiusSize,radiusSize},p);
    /*p.setStyle(Paint.Style.STROKE);
    p.setColor(Color.parseColor("#444444"));
    p.setStrokeWidth(1);
    drawAsymmetricRoundRect(canvas,big,new float[]{0,0,10,10},p);*/

    textP.setTextSize(45);
    textP.setColor(Color.parseColor("#444444"));
    textP.setTextAlign(Paint.Align.CENTER);
    textP.getFontMetrics(fm);
    canvas.drawText(dates[0], width / 2, smallH + textPos, textP);

}
private void drawAsymmetricRoundRect(Canvas canvas, RectF rectF, float[] radii, Paint paint) {
    float topLeftX = rectF.left + radii[0];
    float topLeftY = rectF.top + radii[0];
    float topRightX = rectF.right - radii[1];
    float topRightY = rectF.top + radii[1];
    float bottomRightX = rectF.right - radii[2];
    float bottomRightY = rectF.bottom - radii[2];
    float bottomLeftY = rectF.bottom - radii[3];
    float bottomLeftX = rectF.left + radii[3];

    /*float[] radii is a float array (length = 4), that stores sizes of radii of your corners
     (clockwise, starting from top-left corner => {topLeft, topRight, bottomRight, bottomLeft}).*/
    RectF topLeftCorner = new RectF(rectF.left, rectF.top, topLeftX + radii[0], topLeftY + radii[0]);
    RectF topRightCorner = new RectF(topRightX - radii[1], rectF.top, rectF.right, topRightY + radii[1]);
    RectF bottomRightCorner = new RectF(bottomRightX - radii[2], bottomRightY - radii[2], rectF.right, rectF.bottom);
    RectF bottomLeftCorner = new RectF(rectF.left, bottomLeftY - radii[3], bottomLeftX + radii[3], rectF.bottom);

    canvas.drawArc(topLeftCorner, 180, 90, true, paint);
    canvas.drawArc(topRightCorner, 270, 90, true, paint);
    canvas.drawArc(bottomRightCorner, 0, 90, true, paint);
    canvas.drawArc(bottomLeftCorner, 90, 90, true, paint);
    canvas.drawRect(topLeftX, rectF.top, topRightX, bottomLeftY < bottomRightY ? bottomLeftY : bottomRightY, paint); //top rect
    canvas.drawRect(topLeftX > bottomLeftX ? topLeftX : bottomLeftX, topRightY, rectF.right, bottomRightY, paint); //right rect
    canvas.drawRect(bottomLeftX, topLeftY > topRightY ? topLeftY : topRightY, bottomRightX, rectF.bottom, paint); //bottom rect
    canvas.drawRect(rectF.left, topLeftY, bottomRightX < topRightX ? bottomRightX : topRightX, bottomLeftY, paint); //left rect
}




Is it possible to save checkBox state while switching layout or class? And if its possible how?

When you remember a good tutorial for checkBoxes please let me know!




Kivy Language Dynamic Checkbox List

I want to dyanmically add checkboxes in Kivy languages. I know how to achieve this in python but unaware how to do so in Kivy language. There should be a checkbox for each file in the below list:

 from kivy.uix.filechooser import FileSystemLocal
 file_system = FileSystemLocal()
 file_list=file_system.listdir(App.get_running_app().user_data_dir+'\\')   # this returns a list of files in dir
 file_list=[x for x in file_list if x[-4:]=='.csv']

How can I loop this Kivy? I assuming there should loop on the right side, since that is python code. But I have no clue how? Any starters can be helpful.




Meteor checkbox - Display Value of expression as String, not interpreted as Boolean

I have a checkbox implemented and it's working just fine.

HTML:

<form>
    <ul>
        {{#each checkbox}}
        <li>
            <input type="checkbox" checked="{{checked}}" class="toggle-checked"> {{name}}: {{checked}}
        </li>
        {{/each}}
    </ul>
</form>

JS:

Cbtest = new Mongo.Collection('cbtest');

Template.checkbox.helpers({
    checkbox: function () {
        return Cbtest.find();
    }
});

Template.checkbox.events({
    "click .toggle-checked": function () {
       var self = this;
        Meteor.call("setChecked", self._id, !self.checked);
    }
});

Meteor.methods({
    setChecked: function (checkboxId, setChecked) {
        CbTest.update(checkboxId, {
            $set: {
                checked: setChecked
            }
        });
    }
});

enter image description here

I want to display the Value ("true" or "false") depending on the checkbox's state. As now it seems that the Expression "{{ checked }}" is evaluatiated to true or false, and if its true then it returns the value of the corresponding document entry. How can i just display the content as String ("true" / "false")?

Thanks in advance! Vin




I can't get the checkbox to transmit properly When I hit submit always marks it as unchecked in database

The goal of the code is to transmit the checkbox information and update the database. It does update the database, if I uncheck the box and hit submit, or if i check the box and hit submit the value gets moved to zero.

The database table users is set up so allow_email is (int) with a default of 1 with 1 space allowed only one or zero.

The goal is to allow email to be checked for people who want to be a part of my mass emailing. if it is unchecked they will not get emailed for updates with new articles. By default i have the database set to automatically make all new users a 1 for allowing emails.

When they go to the settings page i and they can update their user information ie first last or email and can uncheck or check a box to allow them to receive emails.

I have the checkbox html code correct I believe because the checkbox will represent properly based on what the database displays so if it's a 1 when the user goes to the page the checkbox will still be checked grabbing that from the database properly. If i leave it checked and hit submit to change data, the code updates the database and makes it a zero, when you refresh the users settings.php page the box is then unchecked now reading that the database has been set to 0. Only if you check the box and hit submit it stays zero. (I am lost here). here is my code. Please assist me if you can.

settings.php

  <?php
  if (isset($_GET['success']) === true && empty($_GET['success']) ===true) {
   echo 'Your details have been updated!';
  } else {
   if (empty($_POST) === false && empty($errors) === true) {

    $update_data = array(
      'first_name'  => $_POST['first_name'],
      'last_name'  => $_POST['last_name'],
      'email_address' => $_POST['email_address'],
      'allow_email' => ($_POST['allow_email'] == 'on') ? 1 : 0
    );

   update_user($session_user_id, $update_data);
   header('Location: settings.php?success');
   exit();

  } else if (empty($errors) === false) {
   echo output_errors($errors);
  }
  ?>

  <form action="" method="post">
   <ul>
    <li>
     First Name:*<br>
     <input type="text" name="first_name" value="<?php echo          $user_data['first_name']; ?>">
</li>
<li>
 Last Name:<br>
 <input type="text" name="last_name" value="<?php echo   $user_data['last_name']; ?>">
</li>
<li>
 Email Address:*<br>
 <input type="text" name="email_address" value="<?php echo  $user_data['email_address']; ?>">
</li>
<li>
 <input type="checkbox" name"allow_email" <?php if ($user_data['allow_email'] == 1) { echo 'checked="checked"'; } ?>> Like the idea of getting updates from us about new articles?
</li>
<li>
 <input type="submit" value="update">
</li>

You can see that i am passing 'allow email' into $user_data variable here. init.php

if (logged_in() === true) {
 $session_user_id = $_SESSION['user_id'];
 $user_data = user_data($session_user_id, 'user_id', 'username', 'password', 'first_name', 'last_name', 'email_address', 'password_recover', 'type', 'allow_email');
 if (user_active($user_data['username']) === false) {
  session_destroy();
  header('Location: index.php');
  exit();

 }
 if ($current_file !== 'changepassword.php' && $current_file !== 'logout.php' && $user_data['password_recover'] == 1) {
  header('Location: changepassword.php?force');
  exit();
 }
}




How to add checkbox column in datatable?

This is my datatable. I want to add a column "Active" to the right most side, where there will be a check box in all the rows. What will be the desired process ? TIA




Based on the result of the observable array make the checkbox gets selected

I got struck with the checkbox bind using knockout js. I use two observable arrays. First observable array is used to display all the student details value with the checkbox in the view. In the 2nd observable array I obtain some values filtered that need to be checked(true) dynamically in the view where I have already displayed the checkbox with the whole value. My html code is,

  <div class="col-lg-10" style="white-space:pre">
                                <div class="checkbox-inline" data-bind="foreach: $root.Studentdetails">
                                    <input type="checkbox" data-bind="checkedValue: $data,value:id(), checked: $root.associatedItemIds, click: $root.toggleAssociation" />
                                    <span data-bind="text: '&nbsp;' + Name()"></span>
                                </div>
                            </div>

And this is the way i approach to gets the checkbox selecetd,

     self.associatedItemIds=ko.obsearvablearray();   
     self.associatedItemIds.push(response.CheckStudents);




samedi 29 août 2015

Changing a date into a checkbox in Django

I have a customer table that has an id, name, telephone and a date where the customer was set to inactive (called 'inactive_date').

In my form, I only want a checkbox to appear. If there is a date, then the checkbox is set. If the date is empty, then the checkbox is not set.

The only way I can set the checkbox so far is by doing the following:

class MyCustomerForm(ModelForm):
     inactive_checkbox = forms.BooleanField(initial='checked')

I tried to use a clean or an init method to be able to set the checkbox based on a condition, but these attempts down below have been unsuccessful. My form always return the checkbox as unset regardless of the contents of the inactive_date.

class MyCustomerForm(ModelForm):
     inactive_checkbox = forms.BooleanField()
     def clean(self, *args, **kwargs):
         inactive_date = self.cleaned_data['inactive_date']
         if (inactive_date != None):
             self.fields['inactive_checkbox'] = 'checked'
         return self.cleaned_data

    def __init__(self, *args, **kwargs):
        super(myCustomerForm, self).__init__(*args, **kwargs)

        inactive_date = self.cleaned_data['inactive_date']
        if (inactive_date != None):
             self.fields['inactive_checkbox'] = 'checked'

class Meta:
    model = MyCustomer
    fields = ['customer_id','customer_name','customer_phone',
              'inactive_checkbox']

Any idea what is wrong with my code or is there perhaps a better way to control my inactive_date through a checkbox?




Rails Multiple Check Box with drop down list

I have created an associated models to create a check box list, where user can select languages that he/she speaks. I have tried to use both Chosen and Select2 but could not make it work. The problem might be because I use check_box_tag

Here is my code;

<%= hidden_field_tag "user[language_ids][]", nil %>
    <% Language.all.each do |language| %>
    <%= check_box_tag "user[language_ids][]", language.id, @user.language_ids.include?(language.id), id: dom_id(language) %>
    <%= label_tag dom_id(language), language.name %> </br>
    <% end %> 

I have watched the Railscast Habtm video to create this. This just works fine but I would like to make it user friendly. Thank you




Shiny CheckBox to dynamically call and visualize data

after breaking my head over this quite a while, I have to admit to myself, I can't do it. I really hope you can help me.

I have a rChart(Morris) that I would like to present a dynamic dataframe, based on the selection in the checkboxgroup "check_de_solar" (Shiny widget).

I have a function callData(id, start.date, end.date) which returns a data.frame for the given arguments. The "ID" is pulled from the checkboxgroup. The data.frame contains two vectors, one for a Posixct (Date/Hour) and one vector with the corresponding value.

My problem is, that I don't understand how to create a data.frame that only pulls data when a checkbox is updated. The way it works now is that it pulls data for all checked boxes every time a checkbox is updated. I also don't know how to update the data.frame when a checkbox is unchecked. Finally, when I change the Datewidget(date1), the entire charts disappears, instead of rerunning with the new date, as it normally should.

server.ui


#Initialize an empty data.frame
de_solar <<- data.frame(matrix(nrow=24,ncol=1))


shinyServer(function(input, output) {


output$de_solar <- renderChart2({

for (i in 1:length(input$check_de_solar)) 
{

  temp <<- callData(input$check_de_solar[i], as.Date(input$date1), as.Date(input$date1+1))
  de_solar <<- merge(temp, de_solar)  
  grph2 <- mPlot(x = "Date", y = colnames(de_solar)[2:NCOL(de_solar)],
               data = de_solar, type = "Line")

})

my ui.r

shinyUI(fluidPage(
dateInput("date1", label = h3("Date"), value="Sys.Date()+1") 

checkboxGroupInput("check_de_solar", label = h3("Checkbox group"), 
                 choices = list("Choice 1" = 1, "Choice 2" = 2, "Choice 3" = 3),
                 selected = 1),

))

The original script is significantly longer, so I removed some unnecessary parts including the definition of callData() as it is not reproducable.

Thank you for your help.




apply experession if checked checkbox is more than one

http://ift.tt/1Ep87xe

<li ng-repeat="d in data"><input type="checkbox"/>{{$index}}</li>
<button ng-show="checkismorethanone">Save</button>

I can't use ng-model because it will check all the checkbox. How can I know if there's any of the checkbox checked? I want to show the save button if anyone of the checkbox is checked, or hide the button if no more button is checked.




vendredi 28 août 2015

Checkboxed option in Android menu does not work

I am trying to add the checkbox to menu of my Android app. But I don't know why item with android:checkable="true" attribute has this square of checkbox, but behave like others items. Do I have to write something in java code? I can read the value but tapping does not changing it's value...

My menu\main.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://ift.tt/nIICcg" >

    <item
        android:id="@+id/menu_settings"
        android:title="@string/settings"/>
    <item
        android:id="@+id/menu_tests"
        android:title="@string/i_want_to_test"/>
    <item
        android:id="@+id/menu_translating"
        android:enabled="false"
        android:title="@string/i_want_to_translating"/>
    <item
        android:id="@+id/menu_funmade"
        android:checkable="true"
        android:title="Enable funmade"/>

</menu>

Look:

How menu looks

The last option behve like other with no specified behaviour. I can tap and manu closes and state does not change. Hope you can help.

Andret




Using checkbox for multiple deletion in asp-mvc [duplicate]

This question already has an answer here:

Let me first present the essential parts of my application:

This is my view:

enter image description here

Here is the code of my view:

    @using MvcApplication6.Models;
    @model List<Employee>

    @{
        ViewBag.Title = "Index";
    }

    <h2>Index</h2>

    <p>

        <a href="@Url.Action("Create")">Create Entry</a>

    </p>


    <p>@Html.ActionLink("Check departments", "Index", "Department")</p>

    <p><a href="@Url.Action("Summary")">Check summary</a></p>



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

    <table border="1">

        <tr>
            <th>
                @Html.DisplayNameFor(model => model[0].id)
            </th>
            <th>
                @Html.LabelFor(model => model[0].firstname)
            </th>
            <th>
                @Html.LabelFor(model => model[0].lastname)
            </th>
            <th>
                @Html.DisplayNameFor(model => model[0].gender)
            </th>
            <th>
                @Html.DisplayNameFor(model => model[0].department)
            </th>
            <th>Action</th>
        </tr>




            @foreach (Employee mod in Model)
            {
                <tr>

                    <td>
                        <input type="hidden" value="@mod.id" name="id" id="id" />
                        @Html.DisplayFor(modelItem => mod.id)

                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => mod.firstname)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => mod.lastname)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => mod.gender)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => mod.department)
                    </td>
                    <td>
                        <button onclick="location.href='@Url.Action("Edit", new { id = mod.id })';return false;">Edit</button> |

                        @Html.CheckBoxFor(modelItem => mod.selected)


                    </td>

                </tr>

            }



        </table>
    <br />
    <input type="submit" value="submit" />
}

Here is my model:

 [Table("carl")]
public class Employee
{


    public int id { get; set; }

    [DisplayName("First Name")]
    [Required(ErrorMessage = "First name is required")]
    public string firstname { get; set; }


    [DisplayName("Last name")]
    [Required(ErrorMessage = "Last name is required")]
    public string lastname { get; set; }

    [DisplayName("Gender")]
    [Required(ErrorMessage = "Gender is required")]
    public string gender { get; set; }


    [DisplayName("Department")]
    [Range(1, 3)]
    [Required(ErrorMessage = "Dep name is required")]
    public int department { get; set; }

    [NotMapped]
    public bool selected { get; set; }
}

I am using Entity Framework and my context class is like this:

public class EmployeeContext: DbContext
{
    public DbSet<Employee> Employees { get; set; }
    public DbSet<Department> Departments { get; set; }
    public DbSet<gender> Genders { get; set; }

}

And lastly, here are is controller:

[HttpGet]
public ActionResult Index()
{

    EmployeeContext emp = new EmployeeContext();
    var adep = emp.Employees.ToList();

    return View(adep);
    }


 [HttpPost]
 public String Index(IEnumerable<Employee> emp)
  {

     if (emp.Count(x => x.selected) == 0)
     {
         return "0 selected";
     }
     else
     {
         return "Success";
     }
  }

Errors that i get is Additional information: Value cannot be null..

What i want to happen is that, all the selected checkboxes to be deleted once the user submits. I made two separate types of index for checking. There is not much functionality yet because i want to confirm it first if i am able to bind to the model. Is it because of the [NotMapped] Attribute? My database has id,firstname,gender,department and i don't want to add another column just for the sake of having some "flags".

The html helper for my checkbox is this line of code:

@Html.CheckBoxFor(modelItem => mod.selected)

And i attached them on every single table rows.




PHP Disabling checkboxes when selected

I am trying to disable a checkbox when selected.

doc1.php

<tr>
    <td>A1</td>
    <td><input type="checkbox" name="A1" value="on" id="A1chk"></td>
</tr>

doc2.php

if (isset($_POST['A1'])){
    array_push($Unavailablearray, 'A1');
    $Availablearray = array_diff($Availablearray, array('A1'));
    fridaydocument.getElementById($_POST["A1chk"]).disabled = true;
}

The code are on different documents. I am trying to disable the checkbox when the form is submitted but only if the checkbox is selected.

The arrays are used for something else on doc2.php




Why z-checkbox doesn't become active?

I am faced with ZK framework and folowing strange behavior. I have a page in which there a list of checkbox cjmponents. Each of them looks like

<div id="zkau_jsessionid_q2rp7jjhd9hm1tw8jbet2y7xj_24205" style="width:250px;" class="z-div" xy="1:0">
  <span id="zkau_jsessionid_q2rp7jjhd9hm1tw8jbet2y7xj_24206" style="width:250px;" class="z-checkbox">
    <input type="checkbox" id="zkau_jsessionid_q2rp7jjhd9hm1tw8jbet2y7xj_24206-real" 
      name="chb_dict_orderingauthority_nationalcustomer" style="position: absolute; left: -9000px;">
    <div id="zkau_jsessionid_q2rp7jjhd9hm1tw8jbet2y7xj_24206-advcheckbox" class="advcheckbox-default"></div>
    <label for="zkau_jsessionid_q2rp7jjhd9hm1tw8jbet2y7xj_24206-real" id="zkau_jsessionid_q2rp7jjhd9hm1tw8jbet2y7xj_24206-cnt"
      class="z-checkbox-content"></label>
  </span>
</div>

According the business logic, one checkbox (when it checked) should disable all another. And when that one is unchecked - all another should became enabled again. So, when I check that one checkbox, HTML layout chenges and looks like

<div id="zkau_jsessionid_q2rp7jjhd9hm1tw8jbet2y7xj_24205" style="width:250px;" class="z-div" xy="1:0">
  <span id="zkau_jsessionid_q2rp7jjhd9hm1tw8jbet2y7xj_24206" style="width:250px;" class="z-checkbox">
    <input type="checkbox" id="zkau_jsessionid_q2rp7jjhd9hm1tw8jbet2y7xj_24206-real" 
      name="chb_dict_orderingauthority_nationalcustomer" disabled="disabled" style="position: absolute; left: -9000px;">
    <div id="zkau_jsessionid_q2rp7jjhd9hm1tw8jbet2y7xj_24206-advcheckbox" class="advcheckbox-default advcheckbox-disabled"></div>
    <label for="zkau_jsessionid_q2rp7jjhd9hm1tw8jbet2y7xj_24206-real" id="zkau_jsessionid_q2rp7jjhd9hm1tw8jbet2y7xj_24206-cnt"
      class="z-checkbox-content"></label>
  </span>
</div>

Ans seems like all contenf of <div id="zkau_jsessionid_q2rp7jjhd9hm1tw8jbet2y7xj_24205" /> rewriting. When I uncheck checkbox, in the html changing only few attributes in <input type="checkbox" id="zkau_jsessionid_q2rp7jjhd9hm1tw8jbet2y7xj_24206-real" ...> (disabled="disabled" dosappears).

From the server, when I check checkbox I get response with folowing JSON fragments for checkboxes:

Disabled state (I check checkbox)

["outer",[{$u:'zkau_jsessionid_q2rp7jjhd9hm1tw8jbet2y7xj_24206'},[['zul.wgt.Checkbox','zkau_jsessionid_q2rp7jjhd9hm1tw8jbet2y7xj_24206',{$$1onCheck:true,$onCheck:true,$$0onSwipe:true,$$0onFocus:true,$onFocus:true,$$0onBlur:true,$onBlur:true,$$0onAfterSize:true,width:'250px',disabled:true,name:'chb_dict_orderingauthority_nationalcustomer'},[]]]]],

Pseudo-enabled state (I uncheck checkbox, but all other checkboxes still disabled)

["setAttr",[{$u:'zkau_jsessionid_q2rp7jjhd9hm1tw8jbet2y7xj_24206'},"disabled",false]],

Enabled state (if I quickly check and uncheck checkbox)

["outer",[{$u:'zkau_jsessionid_q2rp7jjhd9hm1tw8jbet2y7xj_24206'},[['zul.wgt.Checkbox','zkau_jsessionid_q2rp7jjhd9hm1tw8jbet2y7xj_24206',{$$1onCheck:true,$onCheck:true,$$0onSwipe:true,$$0onFocus:true,$onFocus:true,$$0onBlur:true,$onBlur:true,$$0onAfterSize:true,width:'250px',name:'chb_dict_orderingauthority_nationalcustomer'},[]]]]],

So, my question is: Why setAttr doesn't work properly? Why checkboxes still disabled and I need to overwrite much more HTML layout code for enable them?

Best regards and many thanks for wasting your time for me.




JQuery Checkbox click event never returns true

I can't seem to figure this out for something so simple. I am using jQuery 1.4.2 (though I tried later versions) in IE 11 and I can't seem to retrieve the checked value when the value should be true.

    <input id="<%=ID%>" class="abcdeCheckBox" type="checkbox" value="<%=ID%>" />

$('.abcdeCheckBox').bind('click', function()    
    {
        alert(this.checked);
        var indexCheck = cachedCheckedValues.indexOf(this.value);

        if(this.checked)
        {
            if(indexCheck == -1)
            {
                cachedCheckedValues.push(this.value);   
            }
        }
        else
        {
            cachedCheckedValues.splice(indexCheck, 1);
            alert("removing: " + this.value);
        }
    });

This never returns true and I can't understand why. It never adds the value to the array I have in the code.




How do I dynamically create check boxes from an array using the form?

I would like to use the code to dynamically create check boxes based on an array or object I pass to the function. Can you revise this function to take an array? I have a script that finds possible PC names based on the username and lists the matches. It would be nice to have this form to allow me to pick one of the results in the list as the correct PC to move into the right container and install the software.

function GenerateForm {

[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null

$form1 = New-Object System.Windows.Forms.Form
$button1 = New-Object System.Windows.Forms.Button
$listBox1 = New-Object System.Windows.Forms.ListBox
$checkBox3 = New-Object System.Windows.Forms.CheckBox
$checkBox2 = New-Object System.Windows.Forms.CheckBox
$checkBox1 = New-Object System.Windows.Forms.CheckBox
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState

$b1= $false
$b2= $false
$b3= $false

#----------------------------------------------
#Generated Event Script Blocks
#----------------------------------------------

$handler_button1_Click= 
{
    $listBox1.Items.Clear();    

    if ($checkBox1.Checked)     {  $listBox1.Items.Add( "Checkbox 1 is checked"  ) }

    if ($checkBox2.Checked)    {  $listBox1.Items.Add( "Checkbox 2 is checked"  ) }

    if ($checkBox3.Checked)    {  $listBox1.Items.Add( "Checkbox 3 is checked"  ) }

    if ( !$checkBox1.Checked -and !$checkBox2.Checked -and !$checkBox3.Checked ) {   $listBox1.Items.Add("No CheckBox selected....")} 
}

$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
    $form1.WindowState = $InitialFormWindowState
}

#----------------------------------------------
#region Generated Form Code
$form1.Text = "Primal Form"
$form1.Name = "form1"
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 450
$System_Drawing_Size.Height = 236
$form1.ClientSize = $System_Drawing_Size

$button1.TabIndex = 4
$button1.Name = "button1"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 75
$System_Drawing_Size.Height = 23
$button1.Size = $System_Drawing_Size
$button1.UseVisualStyleBackColor = $True

$button1.Text = "Run Script"

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 27
$System_Drawing_Point.Y = 156
$button1.Location = $System_Drawing_Point
$button1.DataBindings.DefaultDataSourceUpdateMode = 0
$button1.add_Click($handler_button1_Click)

$form1.Controls.Add($button1)

$listBox1.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 301
$System_Drawing_Size.Height = 212
$listBox1.Size = $System_Drawing_Size
$listBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$listBox1.Name = "listBox1"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 137
$System_Drawing_Point.Y = 13
$listBox1.Location = $System_Drawing_Point
$listBox1.TabIndex = 3

$form1.Controls.Add($listBox1)


$checkBox3.UseVisualStyleBackColor = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 104
$System_Drawing_Size.Height = 24
$checkBox3.Size = $System_Drawing_Size
$checkBox3.TabIndex = 2
$checkBox3.Text = "CheckBox 3"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 27
$System_Drawing_Point.Y = 75
$checkBox3.Location = $System_Drawing_Point
$checkBox3.DataBindings.DefaultDataSourceUpdateMode = 0
$checkBox3.Name = "checkBox3"

$form1.Controls.Add($checkBox3)


$checkBox2.UseVisualStyleBackColor = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 104
$System_Drawing_Size.Height = 24
$checkBox2.Size = $System_Drawing_Size
$checkBox2.TabIndex = 1
$checkBox2.Text = "CheckBox 2"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 27
$System_Drawing_Point.Y = 44
$checkBox2.Location = $System_Drawing_Point
$checkBox2.DataBindings.DefaultDataSourceUpdateMode = 0
$checkBox2.Name = "checkBox2"

$form1.Controls.Add($checkBox2)



    $checkBox1.UseVisualStyleBackColor = $True
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Width = 104
    $System_Drawing_Size.Height = 24
    $checkBox1.Size = $System_Drawing_Size
    $checkBox1.TabIndex = 0
    $checkBox1.Text = "CheckBox 1"
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 27
    $System_Drawing_Point.Y = 13
    $checkBox1.Location = $System_Drawing_Point
    $checkBox1.DataBindings.DefaultDataSourceUpdateMode = 0
    $checkBox1.Name = "checkBox1"

$form1.Controls.Add($checkBox1)


#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$form1.ShowDialog()| Out-Null

} #End Function

#Call the Function
GenerateForm




How to auto check the child checkboxes once the parent checkbox item is checked?

I am trying to autocheck the child elements when the parent element si checked. To have a clear picture please click on this url http://ift.tt/1IpYr0R.

I am using jquery to do this on every level but it only works for one level.

<script>

 $(document).ready(function(){
   $('#$i').change(function(){
   $('#checkbox-delv$j').prop('checked', $(this).prop("checked"));
    });
});
</script>

I am also sharing the source code

#set ($size = $discoverActorConfs.size())
#set ( $prev_actor_delv = "mycontent" )
#set ( $prev_impact = "fndsk" )


#foreach($i in [0..$size])

    #if($i < $size)
        </br>
        <table id="deliverable-table">
            <tbody>

            <tr class="impact-soy" >


                <div class=actors-$i style="margin-left: 56%; margin-right: auto" >

                    <script>

                        $(document).ready(function() {


                            $('div.actors-$i').connections({ from: 'div.new-div' }).length;
                            var connections = $('connection, inner');
                            setInterval(function() { connections.connections('update') }, 100);
                        });

                    </script>



                    #set ($actor_name = $discoverActorConfs.get($i).actor )
                    <span><input class="checkbox-actor" type="checkbox" name="actor-checkbox" onclick="addTotargetGroup('$actor_name', this);" id=$i>$discoverActorConfs.get($i).actor</span>
                                                                            <span class="remove aui-icon aui-icon-small aui-iconfont-remove"
                                                                                  title="Remove Actor" data-key="$discoverActorConfs.get($i).actor"
                                                                                  onclick="remove_actor('$discoverActorConfs.get($i).actor')">
                                                                                </span>



                    #set ($prev_actor_delv = $discoverActorConfs.get($i).actor)

                </div>

                #set ($size_impact = $discoverImpactConfs.size())
                #foreach($j in [0..$size_impact])

                    #if($j < $size_impact)

                        #if($discoverImpactConfs.get($j).actor == $prev_actor_delv )
                            <div class=impact-$j style="margin-left: 25%; margin-right: auto;" id="delvs-impact">


                                #set ($impact_name = $discoverImpactConfs.get($j).impact )
                                <span><input class="checkbox" type="checkbox" name="impact-checkbox" id="checkbox-delv$j" onclick="addToBigPicture('$impact_name', this);">$discoverImpactConfs.get($j).impact</span>
                                 <span class="remove aui-icon aui-icon-small aui-iconfont-remove"
                                       title="Remove Actor" data-key="$discoverImpactConfs.get($j).impact"
                                       onclick="remove_impact('$discoverImpactConfs.get($j).impact')">
                                                                                </span>
                                #set ($prev_impact = $discoverImpactConfs.get($j).impact)




                                <script>
                                    $(document).ready(function(){
                                        $('#$i').change(function(){
                                            $('#checkbox-delv$j').prop('checked', $(this).prop("checked"));

                                        });
                                    });

                                </script>


                                <script>

                                    $(document).ready(function() {

                                        $('div.impact-$j').connections({ from: 'div.actors-$i' }).length;
                                        var connections = $('connection, inner');
                                        setInterval(function() { connections.connections('update') }, 100);
                                    });
                                </script>
                            </div>


                            #set ($size_deliverables = $discoverDeliverablesConfs.size())

                            #foreach($k in [0..$size_deliverables])
                                #if($k < $size_deliverables)
                                    #if($discoverDeliverablesConfs.get($k).impact == $prev_impact and $discoverDeliverablesConfs.get($k).actor== $prev_actor_delv)
                                        <div class=deliverable-$k id="delvs">


                                            <span><input class="checkbox" type="checkbox" name="deliverable-checkbox" id="checkbox-delv$k" onclick="addReleaseTarget('$impact_name', this);">$discoverDeliverablesConfs.get($k).deliverable</span>
                                            <span class="remove aui-icon aui-icon-small aui-iconfont-remove"
                                                  title="Remove Actor" data-key="$discoverDeliverablesConfs.get($k).deliverable"
                                                  onclick="remove_impact('$discoverDeliverablesConfs.get($k).deliverable')">
                                                                                </span>

                                            <script>                                                    $(document).ready(function() {

                                                    $('div.deliverable-$k').connections({ from: 'div.impact-$j' }).length;
                                                    var connections = $('connection, inner');
                                                    setInterval(function() { connections.connections('update') }, 100);
                                                });
                                            </script>
                                        </div>

                                    #end

                                    <script>
                                        $(document).ready(function(){
                                            $('#checkbox-delv$j').change(function(){
                                                $('#checkbox-delv$k').prop('checked', $(this).prop("checked"));

                                            });
                                        });

                                    </script>

                                #end

                            #end

                        #end

                    #end

                #end

    </div>
        </tr>
        </tbody>
        </table>
    #end
#end




Same as above checkbox option in ASP Web Application

I want to implement the checkbox which on clicking will copy the text value of 5 one textbox to other textbox.

This is my code.

<script type="text/javascript" lang="javascript">
$(document).ready(function () {
    function SameAsMailing() {
        document.getElementById('<%= txtMName.ClientID %>').value = document.getElementById('<%= txtCName.ClientID %>').value;
    }
</script>
<input type="checkbox" name="chkSameAsMailing" id="chkSameAsMailing" onclick="SameAsMailing(this)" />




How to store data into multiple MySQL tables according to the checkbox value?

I have an html form, with multiple checkboxes (subjects) When a user (student) selects the subjects ,the StudentID is stored in a MySQL table along with the selections made in separate columns but in the same table.

My question is: How can I store the student ID in a new table if the checkbox value "equals" to something, would strpos do it ?

for example:

if (strpos($cc,'252000') !== false) {
    mysqli_query($dbcon,"INSERT INTO newtable (studentid,ckb) 
VALUES ('$studentid','$cc')");
}

Full Code:

<?php
      $host = 'localhost';
      $port = 8889;
      $username="root" ;
      $password="root" ;
      $db_name="db1" ;
      $tbl_name="courses" ;
      $tbl_name="studentinfo";
      $tbl_name="newtable";

        $dbcon = mysqli_connect("$host","$username","$password","$db_name") ;
                mysqli_set_charset($dbcon, "utf8");


        if (!$dbcon) {
        die('error connecting to database'); }


    $studentid = mysqli_real_escape_string($dbcon, $_GET['studentid']); //echo $studentid;

$name = $_GET['ckb'];
if(isset($_GET['ckb']))
{
foreach ($name as $courses){
$cc=$cc. $courses.',';
}
}

if (strpos($cc,'252000') !== false) {

    mysqli_query($dbcon,"INSERT INTO newtable (studentid,ckb) 
VALUES ('$studentid','$cc')");

    echo "$cc, trtue";
}

HTML

<form action="cdb.php" method="get">

<input name="studentid" type="text" id="studentid" maxlength="11"value="Student ID" />

<input type="checkbox" name="ckb[]" value="251000-1"/>
<input type="checkbox" name="ckb[]" value="251000-2"/>




EXTJS propertyGrid key column checkbox

Is there any way to put a checkbox to any row first column in property.Grid like in the picture?

enter image description here




Checkbox Cookie & Progress Bar Connection

First off, I apologise for being totally deft at Javascript. I've pieced together 2 scripts (among others - thank you developers!) for remembering checkboxes that have been checked off via a cookie, and then added a progress bar that changes also based off the check boxes.

Being as unknowledgeable as I am, I assumed that the cookie's data repopulation would also trigger the progress bar-which it doesn't. Since the progress bar is triggered by 'on.click', I can understand why it does not automatically register the repopulated cookie data- but I don't know how to proceed from there to connect the two. I really only know html and css. I'm guessing there should be some intermediary function that also triggers the progress bar?

This is for a semester long grad school project. If anyone could offer some advice, my appreciation and gratitude are yours! I apologise for the code perhaps not looking so great in the snippet - the item in question is currently hosted here under 'tasks':

http://ift.tt/1LzMIBn

//Creates the cookie that remembers the checkboxes
<script>
      $(":checkbox").on("change", function(){
        var checkboxValues7 = {};
        $(":checkbox").each(function(){
          checkboxValues7[this.id] = this.checked;
        });
        $.cookie('checkboxValues7', checkboxValues7, { expires: 7, path: '/' })
      });

      function repopulateCheckboxes(){
        var checkboxValues7 = $.cookie('checkboxValues7');
        if(checkboxValues7){
          Object.keys(checkboxValues7).forEach(function(element) {
            var checked = checkboxValues7[element];
            $("#" + element).prop('checked', checked);
          });
        }
      }

      $.cookie.json = true;
      repopulateCheckboxes();
   </script>
 //This is the progress bar input script //
   
   <script>
        $('input').on('click', function() {
    var emptyValue = 0;
    $('input:checked').each(function() {
        emptyValue += parseInt($(this).val());
    });
    $('.progress-bar').css('width', emptyValue + '%').attr('aria-valuenow', emptyValue);
});
        </script>
span.bigchecktarget {
    font-family: fontawesome; /* use an icon font for the checkbox */  
}
input[type='checkbox'].bigcheck {     
    position: relative;
    left: -999em; /* hide the real checkbox */
}

input[type='checkbox'].bigcheck + span.bigchecktarget:after {
    content: "\f096"; /* In fontawesome, is an open square (fa-square-o) */
    color: #197FD4;
    font-size: 1.5em; 
}
input[type='checkbox'].bigcheck:checked + span.bigchecktarget:after {
    content: "\f046"; /* fontawesome checked box (fa-check-square-o) */
        color: #FF4D4D;
}

li.taskcheck ul li{
        padding-right: 15px;
        font-size: .9em;
}
.progress{
        background-color: #EAEAEA;
        height: 50px;
        border: 1px solid transparent;
        border-radius: 8px;
        width: 75%;
        margin: auto;

}
.progress-bar{
        height: 50px;
        border-radius: 8px;

        } 
        
.progress-bar-success{
        background-color:  #50CA8E;
        width: 0;
}
<ul>
  <script src="http://ift.tt/1raaURo"></script>
        <li class="taskcheck">
                <label class="bigcheck" for="option1">
                  <span class="blue">Module 1: Assignment 1</span> 
                </label>
        <input class="bigcheck" type="checkbox" id="option1" name="option1" value="20">
        <span class="bigchecktarget"></span>
        <ul>
                <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </li>
        </ul>
        <div class="progress">
                 <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
    </div>



Aligning checkbox before text

I have a problem with the text after a checkbox. It is not aligned properly (the checkbox is too high) and since I am just starting to learn css and coding, I don't understand the solutions that were given to this problem on other sites. Here is an image of what it looks like right now and would appreciate any help on what to put in custom css in order to have the box properly aligned. Thank you! http://ift.tt/1NLmrCs




IF condition not working with Android CheckBox

if ((Problem != null && !notokcheckbox.isChecked()) || (Problem!=null && !ressolvedcheckbox.isChecked())) {
    Toast.makeText(getActivity(), "Enable Ok Or Not/Ok", 100000).show();
} else {    
    Toast.makeText(getActivity(), "Sucess", 100000).show();
}

I am trying to apply validation I have two check Box notokcheckbox and ressolvedcheckbox.

if Problem != null and nither notokcheckbox, ressolvedcheckbox is not checked then it should display Enable Ok Or Not/Ok

or

if Problem != null or either notokcheckbox or ressolvedcheckbox is enable then it should Print Sucess.

while I am trying it with single check Box i mean its working fine but not with both.

Can u please tell me how to apply with two check Box:

if (Problem != null && !notokcheckbox.isChecked()) {
    Toast.makeText(getActivity(), "Enable Ok Or Not/Ok", 100000).show();
} else {
    Toast.makeText(getActivity(), "Sucess", 100000).show();
}

working fine.

please suggest me how to fix it.




Checkbox in UITableView change and revert images

I have a tableView with custom tableViewCell. Each cell has an image on the left (see screen 1). The custom tableViewCell has been subclassed. Every row has a different image which depends on indexPath.row

If I click on the image(s) the screen, the images should change to tick boxes so user can multiselect (see screen 2). If I click back on the image with a tick, it should revert back to old image on screen 1.

Screen 1 Screen 2

Issue : I know how to change the image to tick mark but don't know how to go back to old image (pls remember every row has a different image - so the "else" part in my below code will not make sense).

Below is my code to change and revert the image

@IBAction func imageTap(sender: AnyObject) {    
    let imageView : UIImageView! = sender.view! as! UIImageView
    if imageView.image != UIImage(named: "Oval 5"){
        imageView.image = UIImage(named: "Oval 5")
        awardBadge.hidden = false
    }
    else // Need to figure out how to go back to same image
    {
        imageView.image = UIImage(named: "Oval 1") 
        awardBadge.hidden = true
    }
}




Uncheck table row in bootstrap table on specific condition

My previous question was this and I want to uncheck checked row if user selects a row that has 'Stock Available=null or 0'. Now my jquery code is:

$(document).ready(function()
{
    $("#add_cart_btn").hide();
    var json;
    var checkedRows = [];
    $('#table-style').on('check.bs.table', function (e, row) {
      checkedRows.push({id: row.id});
      $("#add_cart_btn").show();
    });

    $('#table-style').on('uncheck.bs.table', function (e, row) {
      $.each(checkedRows, function(index, value) {
        if (value.id === row.id) {
          checkedRows.splice(index,1);
        }
      });
    });
     /*if(checkedRows.length < 0) {
        // does not exist
        $("#add_cart_btn").hide();
      }
      else {
        // does exist
        $("#add_cart_btn").show();
      }*/

});

Here I'm also trying to show $("#add_cart_btn") button iff checkedRows[] contains at least one record. I searched bootstrap events for above but understood it.




How to get data from json array of different objects and add that in gridview of checkboxes in android dynamically

fields: [
{
type: "radio",
data: {
0: "I am in ABROAD",
1: " I am in INDIA"
}
},
{
header: "How would you like to go Abroad ?",
type: "check",
data: {
0: "Any How",
1: "On a Migrate Overseas",
2: "On a Student Visas",
3: "On a Settle Abroad",
4: "On a Temporary Visas",
5: "On a Work Abroad",
6: "On a Others",
7: "On a Invest Abroad",
8: "On a Evaluation",
9: "On a Dependent Visas",
10: "On a Concierge Services",
11: "On a Appeals",
12: "On a Work study Program"
}
},
{
header: "Which country would you be interested in ?",
type: "check",
data: {
0: "Anywhere Abroad",
2: "On a UK",
3: "On a USA",
4: "On a Australia",
5: "On a Canada",
6: "On a Denmark",
7: "On a France",
8: "On a Singapore",
9: "On a New Zealand",
10: "On a Hong Kong",
11: "On a Norway",
12: "On a Austria",
13: "On a South Africa",
14: "On a Ireland",
15: "On a Germany",
16: "On a Philippines",
17: "On a Netherlands",
18: "On a Malaysia",
19: "On a Switzerland",
20: "On a Belgium",
21: "On a Sweden"
}
},
{
header: "When do you plan to go ?",
type: "radio",
data: {
Immediate: "Immediate",
This Week: "This Week",
This Month: "This Month",
3 Months: "3 Months",
6 Months: "6 Months",
Not Sure: "Not Sure"
}
}
]

My Json is like this.. I need to get data from this json and add that in Gridview of checkboxes. I am not getting the logic how to do this ? first object of that json I need to add to a radio group and others to Gridview of checkboxes.




jeudi 27 août 2015

How to transfer data with selected checkbox in datagrid after button click? C# and SQL Server

I have two tables namely Pending.dbo and Approved.dbo. I put tabcontrol and in the first tab contains "Pending datagridview" with checkbox and btnApprove. The second tab named Approved is just a read-only datagridview. What I want is when I clicked the btnApprove, the data selected by checkbox in "Pending datagridview" will transfer to the table Approved.dbo. Was this possible? As of now, these is my codes:

private void btnApproved_Click(object sender, EventArgs e)
    {
        //List<DataGridViewRow> selectedRows = (from row in dataGridView1.Rows.Cast<DataGridViewRow>() where Convert.ToBoolean(row.Cells["checkBoxColumn"].Value) == true select row).ToList();
        foreach (DataGridView row in dataGridView1.Rows)
        {
            using (var connect = sqlcon.getConnection())
            {
                using (SqlCommand cmd = new SqlCommand("COMMAND TO TRANSFER DATA??????"))
                {

                }
            }
        }
    }

PS. Sorry for my bad english and explanation. Thanks!




How to output all checkbox value

hello please help me i have a problem outputting all the values of checkbox it outputs only one i need to show all the checked checkbox and output them please help me here is the code it only shows one whenever i checked them all i need this ASAP:

<html>
    <head>
        <title>Cake Form</title>
        <link rel="stylesheet" href="cakeform.css">
    </head>
    <body>
    <?php

        $nameErr = $addErr = $phoneErr = $scake  = $flavorcake = $fill = "";
$name = $address = $phone =  $rcake = $fillr = $cakeflavor = "";


if ($_SERVER["REQUEST_METHOD"] == "POST") {
   if (empty($_POST["name"])) {
     $nameErr = "Name is required";
   } else {
     $name = test_input($_POST["name"]);
   }

   if (empty($_POST["address"])) {
     $addErr = "Email is required";
   } else {
     $address = test_input($_POST["address"]);
   }

   if (empty($_POST["phone"])) {
     $phoneErr = "Gender is required";
   } else {
     $phone = test_input($_POST["phone"]);
   }
   if(isset($_POST['SelectedCake'])){
       $x=$_POST['SelectedCake'];

   }
   if(isset($_POST['CakeFlavor'])){
       $y=$_POST['CakeFlavor'];

   }
   if(isset($_POST['Filling'])){
       $z=$_POST['Filling'];

   }
   if(empty($x)){
       $scake='Select one Cake';


   }else{

       $rcake= $x;

   }
    if(empty($y) OR $y == 'Flavor'){
       $flavorcake='Select one flavor';


   }else{

       $cakeflavor= $y;

   }
   if(empty($z)){
       $fill='Select at least one Fillings';


   }else{
       foreach($z as $item){
           $fillr=$item;

       }


   }



}
function test_input($data) {
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}


    ?>
    <div id="wrap">
        <div class="cont_order">
        <fieldset>
        <legend>Make your own Cake</legend>
    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
        <h4>Select size for the Cake:</h4>
        <input type="radio" name="SelectedCake" value="Round6">Round cake 6" - serves 8 people</br>
        <input type="radio" name="SelectedCake" value="Round8">Round cake 8" - serves 12 people</br>    
        <input type="radio" name="SelectedCake" value="Round10">Round cake 10" - serves 16 people</br>  
        <input type="radio" name="SelectedCake" value="Round12">Round cake 12" - serves 30 people</br>
<span class="error">*<?php echo $scake;?></span>        
        <h4>Select a Cake Flavor: </h4>
        <select name="CakeFlavor">
            <option value="Flavor" selected="selected">Select Flavor</option>
            <option value="Carrot" >Carrot</option>
            <option value="Chocolate" >Chocolate</option>
            <option value="Banana" >Banana</option>
            <option value="Red Velvet" >Red Velvet</option>
            <option value="Strawberry" >Strawberry</option>
            <option value="Vanilla" >Vanilla</option>
            <option value="Combo" >Combo</option>
        </select>
        <span class="error">*<?php echo $flavorcake;?></span>
        <h4>Select Fillings:</h4>
        <label><input type="checkbox" name="Filling[]" value="Cream"/>Cream</label><br>
        <label><input type="checkbox" name="Filling[]" value="Fudge"/>Fudge</label><br>
        <label><input type="checkbox" name="Filling[]" value="Ganache"/>Ganache</label><br>
        <label><input type="checkbox" name="Filling[]" value="Hazelnut"/>Hazelnut</label><br>
        <label><input type="checkbox" name="Filling[]" value="Mousse"/>Mousse</label><br>
        <label><input type="checkbox" name="Filling[]" value="Pudding"/>Pudding</label><br>
        <span class="error">*<?php echo $fill;?></span>
        </fieldset>
        </div>
        <div class="cont_order">
        <fieldset>
        <legend>Contact Details</legend>
        <label for="name">Name</label><br>
        <input type="text" name="name" id="name"><span class="error">*<?php echo $nameErr;?></span>
        <br>
        <label for="address">Address</label><br>
        <input type="text" name="address" id="address"><span class="error">*<?php echo $addErr;?></span>
        <br>
        <label for="phonenumber">Phone Number</label><br>
        <input type="text" name="phone" id="phone"><span class="error">*<?php echo $phoneErr;?></span><br>
        </fieldset>
        <input type="submit" name="submitted" id="submit" value="Submit"/>
        </div>
        </form>
        <div class="cont_order">
        <?php

            echo $name.'<br>';
            echo $address.'<br>';
            echo $phone.'<br>';
            echo $rcake.'<br>';
            echo $cakeflavor.'<br>';
            echo $fillr.'<br>';


        ?>

        </div>
        </div>


        </body>
</html>




How to show non-popular checkboxes on button click in angular?

In a form I've got a list of about 15 checkboxes, of which 3 are the most popular. So by default I only want to show the 3 popular choices. At the end of the 3 checkboxes there should be an icon to expand and collapse the rest of the checkboxes.

I'm building the website in Angular, so I guess I can simply use an ng-show for this. The thing is that I wonder whether that is the correct way to do this. It seems to me that this is such a common thing, that there should be some kind of standard way of doing this..?

And also what kind of icon do people normally use for this? For expand and collapse I would normally use the little grey triangle, but I feel it doesn't suit this specific situation well. I know I've seen this before in other forms, but I just can't find it anymore to take inspiration from.

All tips are welcome!




Why is setting a checkbox's false value to 'undefined' causing ng-invalid to get added

I have a checkbox in angular that has a false value of undefined and despite it not being required, my form does not validate when it is checked and unchecked, due to ng-invalid being added as a class to the input on uncheck.

Why does this happen?

Here is a plunker you can mess with: http://ift.tt/1JySkIg

Notice the second checkbox has a false value of 'undefined'.




Request.InputStream not complete after a checkbox postback

I'm having a problem with a ASPX page of our production application that throws a lot of randomly weirds exceptions, as I explain now:

1.- A user write a value on an AutoPostBack TextBox (mnt_embarque). We received this Request.InputStream information:

EVENTTARGET=mnt_embarque&__EVENTARGUMENT=&__LASTFOCUS=&__VIEWSTATEGUID=4bcf3d2c-2dcf-4264-9743-5c32cf01cd79&__VIEWSTATE=&sfm_buscar%24alto_ventana=&sfm_importar%24alto_ventana=&sfm_exportar%24alto_ventana=&sfm_detalle%24alto_ventana=&sfm_configuracion_factores%24alto_ventana=&sfm_declaraciones_de_ingreso%24alto_ventana=&txt_carpeta=%5B27369%5D-&mnt_embarque=2&fps_gasto_flete_nacional%24data=%253Croot%253E%253Cdata%253E%253C%252Fdata%253E%253Cstate%253E%253Cchartinfo%253E%253C%252Fchartinfo%253E%253Ccolinfo%253E%253C%252Fcolinfo%253E%253Crowinfo%253E%253C%252Frowinfo%253E%253Cselection%253E%253C%252Fselection%253E%253Ccellinfo%253E%253C%252Fcellinfo%253E%253Cactiverow%253E-1%253C%252Factiverow%253E%253Cactivecolumn%253E-1%253C%252Factivecolumn%253E%253C%252Fstate%253E%253Cactivespread%253E%253C%252Factivespread%253E%253Cactivechild%253E%253C%252Factivechild%253E%253Cscrollleft%253E0%253C%252Fscrollleft%253E%253Cscrolltop%253E0%253C%252Fscrolltop%253E%253C%252Froot%253E&fps_gasto_flete_nacional%24extender=&fps_gasto_internacion_peso%24data=%253Croot%253E%253Cdata%253E%253C%252Fdata%253E%253Cstate%253E%253Cchartinfo%253E%253C%252Fchartinfo%253E%253Ccolinfo%253E%253C%252Fcolinfo%253E%253Crowinfo%253E%253C%252Frowinfo%253E%253Cselection%253E%253C%252Fselection%253E%253Ccellinfo%253E%253C%252Fcellinfo%253E%253Cactiverow%253E-1%253C%252Factiverow%253E%253Cactivecolumn%253E-1%253C%252Factivecolumn%253E%253C%252Fstate%253E%253Cactivespread%253E%253C%252Factivespread%253E%253Cactivechild%253E%253C%252Factivechild%253E%253Cscrollleft%253E0%253C%252Fscrollleft%253E%253Cscrolltop%253E0%253C%252Fscrolltop%253E%253C%252Froot%253E&fps_gasto_internacion_peso%24extender=&hf_decimales_CantidadValorTotal=2%7C8%7C2&hf_EstadoPagina=modificar&hf_validar=NO&hf_IDInterno=0&hf_TituloPagina=Costeo+de+mercaderias&hf_mensaje_eliminar_contenedor=Se+recuerda+que+al+eliminar+un+contenedor%2C+tambi%C3%A9n+ser%C3%A1+eliminado+de+los+productos.%5Cn+%C2%BFDesea+continuar%3F&hf_mensaje_marca_contenedor_incorrecto=La+sigla+del+contenedor+ingresado+es+incorrecto%2C+favor+revisar+e+ingresar+nuevamente.&hf_mensaje_sin_contenedores_para_asociar=No+existen+contenedores+para+asociar+al+producto+seleccionado.&hf_pnl_gastos_flete_display=none&hf_pnl_gastos_internacion_display=none&hf_mensaje_confirmacion_copiado=%C2%BFDesea+copiar+el+contenido+ingresado%2C+en+las+filas+continuas%3F

2.- A user do uncheck an AutoPostBack checkbox a few seconds later (chk_cerrar). We received this Request.InputStream information:

EVENTTARGET=chk_cerrar&__EVENTARGUMENT=&__LASTFOCUS=&__VIEWSTATEGUID=4bcf3d2c-2dcf-4264-9743-5c32cf01cd79&__VIEWSTATE=&sfm_buscar%24alto_ventana=&sfm_importar%24alto_ventana=&sfm_exportar%24alto_ventana=&sfm_detalle%24alto_ventana=&sfm_configuracion_factores%24alto_ventana=&sfm_declaraciones_de_ingreso%24alto_ventana=&fps_gasto_flete_nacional%24ctl09=&fps_gasto_flete_nacional%24ValidatorHold-1=&fps_gasto_flete_nacional%24ctl12=&fps_gasto_flete_nacional%24ctl14=&fps_gasto_flete_nacional%24data=&fps_gasto_flete_nacional%24extender=

3.- A user do click a button a few seconds later (btn_aceptar). We received this Request.InputStream information:

EVENTTARGET=btn_aceptar&__EVENTARGUMENT=&__LASTFOCUS=&__VIEWSTATEGUID=4bcf3d2c-2dcf-4264-9743-5c32cf01cd79&__VIEWSTATE=&sfm_buscar%24alto_ventana=&sfm_importar%24alto_ventana=&sfm_exportar%24alto_ventana=&sfm_detalle%24alto_ventana=&sfm_configuracion_factores%24alto_ventana=&sfm_declaraciones_de_ingreso%24alto_ventana=&fch_embarque%24fch_embarque_texto_fecha=15-07-2015&fch_tc_contable%24fch_tc_contable_texto_fecha=15-07-2015&fch_iva%24fch_iva_texto_fecha=21-08-2015&mnt_tc_especial=0.00&cmb_mes_tc_aduanero=08&mnt_ano_tc_aduanero=2015&mnt_cantidad_cajas_carnes=0&cmb_estado=80509&rdl_peso_valor=por_valor&fps_gasto_flete_nacional%24ctl09=&fps_gasto_flete_nacional%24ValidatorHold-1=&fps_gasto_flete_nacional%24ctl12=&fps_gasto_flete_nacional%24ctl14=&fps_gasto_flete_nacional%24data=%253Croot%253E%253Cdata%253E%253C%252Fdata%253E%253Cstate%253E%253Cchartinfo%253E%253C%252Fchartinfo%253E%253Ccolinfo%253E%253C%252Fcolinfo%253E%253Crowinfo%253E%253C%252Frowinfo%253E%253Cselection%253E%253C%252Fselection%253E%253Ccellinfo%253E%253C%252Fcellinfo%253E%253Cactiverow%253E-1%253C%252Factiverow%253E%253Cactivecolumn%253E-1%253C%252Factivecolumn%253E%253C%252Fstate%253E%253Cactivespread%253E%253C%252Factivespread%253E%253Cactivechild%253E%253C%252Factivechild%253E%253Cscrollleft%253E0%253C%252Fscrollleft%253E%253Cscrolltop%253E0%253C%252Fscrolltop%253E%253C%252Froot%253E&fps_gasto_flete_nacional%24extender=&fps_gasto_internacion_peso%243%2C0=on&fps_gasto_internacion_peso%24ValidatorHold-1=&fps_gasto_internacion_peso%24ctl11=&fps_gasto_internacion_peso%24ctl13=&fps_gasto_internacion_peso%24ctl15=&fps_gasto_internacion_peso%24ctl17=&fps_gasto_internacion_peso%24ctl19=&fps_gasto_internacion_peso%24ctl21=&fps_gasto_internacion_peso%24ctl23=&fps_gasto_internacion_peso%24ctl25=&fps_gasto_internacion_peso%24ctl27=&fps_gasto_internacion_peso%24ctl30=&fps_gasto_internacion_peso%24ctl32=&fps_gasto_internacion_peso%24ctl35=&fps_gasto_internacion_peso%24ctl37=&fps_gasto_internacion_peso%24ctl40=&fps_gasto_internacion_peso%24ctl42=&fps_gasto_internacion_peso%24data=%253Croot%253E%253Cdata%253E%253C%252Fdata%253E%253Cstate%253E%253Cchartinfo%253E%253C%252Fchartinfo%253E%253Ccolinfo%253E%253C%252Fcolinfo%253E%253Crowinfo%253E%253C%252Frowinfo%253E%253Cselection%253E%253C%252Fselection%253E%253Ccellinfo%253E%253C%252Fcellinfo%253E%253Cactiverow%253E-1%253C%252Factiverow%253E%253Cactivecolumn%253E-1%253C%252Factivecolumn%253E%253C%252Fstate%253E%253Cactivespread%253E%253C%252Factivespread%253E%253Cactivechild%253E%253C%252Factivechild%253E%253Cscrollleft%253E0%253C%252Fscrollleft%253E%253Cscrolltop%253E0%253C%252Fscrolltop%253E%253C%252Froot%253E&fps_gasto_internacion_peso%24extender=&hf_decimales_CantidadValorTotal=&hf_EstadoPagina=&hf_validar=NO&hf_IDInterno=27396&hf_TituloPagina=&hf_mensaje_eliminar_contenedor=&hf_mensaje_marca_contenedor_incorrecto=&hf_mensaje_sin_contenedores_para_asociar=&hf_pnl_gastos_flete_display=none&hf_pnl_gastos_internacion_display=none&hf_mensaje_confirmacion_copiado=

All InputStream information has been captured on the Global_asax.AcquireRequestState event. As i can see, after the postback of the checkbox, the InputStream has lot almost all information that the user has been working on. This problem happens pretty often.

What may be causing this problem? I really appreciate your help on this difficult situation.




Rails- Removing items from a collection with checkbox form

I have a model called Teams, which has_many Tokens. On the show route for a particular team, I display all of its tokens, along with a checkbox. I want to be able to remove any number of tokens from the current team by checking the corresponding checkboxes and clicking "Save".

I have a pretty kludgey solution at the moment, in which:

All of the checkboxes are checked by default. A post action is made to teams_controller#remove_token, which extracts the values of boxes that have been unchecked, and then updates the team_id of the corresponding token to nil.

My kludge looks like this:

team.rb:

    has_many :tokens, inverse_of: :team

routes.rb:

     resources :teams do
       member do 
        post :remove_token

teams_controller.rb:

    def remove_token
        @team = Team.find(params[:id])
        tokens = params["tokens"].select {|k,v| v["team_id"] == "0"}

        tokens.each { |k,v| Token.find(k).update_attributes(:team_id => nil) }

        respond_to do |format|
          format.html {redirect_to team_url(@team) }
        end
   end

view:

   <%= form_tag remove_token_team_path do %>
        <% @team.account_tokens.each do |token| %>
                <%= token.email %>

                <%= fields_for "tokens[]", token do |f| %>
                    <%= f.check_box :team_id %>
                <% end %>
        <% end %>
        <%= submit_tag "Save"%> 
   <% end %>

The problems with this are that:

  • The checkboxes are all checked, and unchecking them removes the token from the collection. I want it to be the reverse.

  • Having to parse the params to read 0 values to select the tokens that should be removed from the collection seems like a pretty clumsy way to do this, but I haven't worked out a better one.

What is the correct way to remove multiple elements from a collection with Rails?




Checkbox Hide one div when I click on another checkbox

I'm sure there is a simple solution. I have two labels associated with two checkboxes, and each of them shows their corresponding div. The thing is I have to hide div1 when I click on checkbox2 and show div2, and vice-versa.

This is my css:

input[type=checkbox] {
position: absolute;
top: -9999px;
left: -9999px;
}
label { 
display: inline-block;
margin: 60px 0 10px 0;
cursor: pointer;
}
/* Default State */
.hombres, .mujers{
display: none;
}
/* Toggled State */
input[type=checkbox]#hombre:checked ~ div.hombres {
display:block;
background-color: #f04e10;
}
input[type=checkbox]#mujer:checked ~ div.mujers {
display:block;
background-color: #f04e10;
}
input[type=checkbox]#hombre:checked ~ div.mujers {
display: none;
}
input[type=checkbox]#mujer:checked ~ div.hombres {
display: none;
}

This is my HTML:

<label for="hombre">Hombre</label>
<input type="checkbox" id="hombre">
<label for="mujer">Mujer</label>
<input type="checkbox" id="mujer">
<div class="hombres"><p>Hombre</p></div>
<div class="mujers"><p>Mujer</p></div>

Any idea?




Enable boolean and enter text in view then pass back to controller - MVC

I have a view that displays a boolean (currently defaulted to 0) in a box format in the view that I cannot check to activate as true and also want to enter text in the result field to pass back to the controller and save both changes to a table. Can someone please explain what I have to do to allow this functionality to work please.

enter image description here

Controller code

public ActionResult P1A1Mark()
    {
        List<MarkModel> query = (from row in db.submits
                                     where row.assignment_no.Equals("1") && row.group_no == 1
                                     group row by new { row.assignment_no, row.student_no, row.student.firstname, row.student.surname } into g
                                     select new MarkModel
                                     {
                                         student_no = g.Key.student_no,
                                         student_surname = g.Key.surname,
                                         student_firstname = g.Key.firstname

                                     }
                                        ).ToList();

        return View(query);
    }

View

@model IEnumerable<MvcApplication2.Models.MarkModel>

@{
    ViewBag.Title = "P1A1Mark";
}

<h2>Mark Student Assignments</h2>

<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.student_no)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.student_surname)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.student_firstname)
        </th>
         <th>
            @Html.DisplayNameFor(model => model.submitted)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.result)
        </th>

        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.student_no)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.student_surname)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.student_firstname)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.submitted)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.result)
        </td>

    </tr>
}

</table>

Model

    public class MarkModel
{
    public string student_no { get; set; }
    public string student_surname { get; set; }
    public string student_firstname { get; set; }
    public string assignment_no { get; set; }
    public bool submitted { get; set; }
    public string result { get; set; }
    public Nullable<int> group_no { get; set; }
}




Check, uncheck items of checkbox in an array angularjs javascript

I have an array named namesData that I am showing on the UI. By default the checkboxes should be checked. When a checkbox is unchecked, that item should get removed from namesData. If the checkbox is checked, it should get added back to namesData.

$scope.namesData = [{"name":"abc.txt"}, {"name":"xyz.txt"}]

html:

<div ng-repeat="namesList in namesData">
        <input type="checkbox" ng-model="nameItem[$index].checked" ng-change="nameChange(namesList, nameItem[$index].checked, 'nameObj'+ $index, $index)" ng-checked="nameItem.checked" name="nameObj" id="{{'nameObj'+$index}}"/>&nbsp;
        <span>{{namesList.name}}</span>

Controller:

$scope.namesData = [{"name":"abc.txt"}, {"name":"xyz.txt"}];
$scope.nameItem.checked = true;

$scope.nameChange = function(list, isChecked, id, itemNum){
    if (isChecked){
        $scope.namesData.push(list);
    }
    else
        $scope.namesData.splice($scope.newNamesList.indexOf(list), 1);
};

Issue: The problem with the above logic is that the checked/unchecked items are getting added/removed to the end of the namesData array rather than its actual index item. Please advise how to resolve this.




jQuery - Getting values of text input and checkboxes into one string (or array)

I have three types of items I'm trying to get into a comma-separated string (or array), which I want to display and use to form a URL later. How can I get these three types of data into the same string or array?

  1. An existing POST string
  2. Free input from a text field with an Add button
  3. The values of a series of checkbokes

Here's the fiddle.

I'm using this HTML:

<div class="srs-display">existingPostString</div>

<ul id="srs" class="srs">
    <!-- START TEXT INPUT FIELD -->
    <li class="sr">
        <div class="masonry-well">
            <input id="sr-custom" type="text" placeholder="Add your own">
            <a class="add-sr-custom">Add</a>
        </div>
    </li>
    <!-- END TEXT INPUT FIELD -->
    <!-- START CHECKBOXES -->
    <li class="sr">
        <div class="masonry-well">
            <input id="srPredefined1" type="checkbox" name="srPredefined1" value="srPredefined1">
            <label for="srPredefined1" class="ts-helper">srPredefined1</label>
        </div>
    </li>
    <li class="sr masonry-item">
        <div class="masonry-well">
            <input id="srPredefined2" type="checkbox" name="srPredefined2" value="srPredefined2">
            <label for="srPredefined2" class="ts-helper">srPredefined2</label>
        </div>
    </li>
    <li class="sr masonry-item">
        <div class="masonry-well">
            <input id="srPredefined3" type="checkbox" name="srPredefined3" value="srPredefined3">
            <label for="srPredefined3" class="ts-helper">srPredefined3</label>
        </div>
    </li>
    <!-- END CHECKBOXES -->
</ul>

And here's the JS I tried so far:

$('input[type="checkbox"]').bind('change', function() {
    var srs = 'existingPostString';

    $('input[type="checkbox"]').each(function(index, value) {
        if (this.checked) {
            /*add*/ /*get label text associated with checkbox*/
            srs += ($(this).val() + ', ');
        }
    });
    if (srs.length > 0) {
        srs = srs.substring(0,srs.length-2);
    } else {
        srs = 'No checks';
    }

    $('.srs-display').html(srs);
});

$(".add-sr-custom").on('click', function() {
    var srs = 'existingPostString';

    srs +=  ',' + $('#sr-custom').val();
    $('.srs-display').text(srs);
})




Dinamically generate / remove text inputs with checkboxes jQuery

Im having troubles with the removal of the correct input texboxes once these have been generated.

Basically the code generates a text input when a checkbox is selected. The generated text input contains the value of the selected checkbox. All this works fine as well does the dependency of the checkboxes selection.

Where I need help is to remove the actual input that contains the value of the de-selected checkbox. right now the one removes is always the last input box instead of the one corresponding to the checkbox being clicked.

The second problem is the following. The checkboxes are organized in pairs. but you can only select one checkbox per pair, this works fine, but I go from one checkbox to the other and the previous is automatically unchecked the input box has to be removed as well.

Here is the working code:

$(function() {
                 // Moneyline Visitor
        var scntDiv = $('#p_scents');
        var i = $('#p_scents p').size() + 1;
                var arrmlv = $("#mlv").map(function() { return $(this).val(); }).get();
        $('#mlv').change(function () {
            if ($('#mlv').is(':checked')) {
                $('<input type="text" id="p_scnt'+ i +'" class="p_scnt'+ i +'" size="20" name="p_scnt_' + i +'" value="'+ arrmlv +'" placeholder="No Disponible" />').appendTo(scntDiv);
             i++;   
                         $("input[name='rlo']").attr("disabled", true);
                         $("input[name='rlu']").attr("disabled", true);
                         $("input[name='mll']").prop('checked', false);
            } else if ($('#mlv').not(':checked')) {
                        i--;
                        $("input[name='rlo']").attr("disabled", false);
            $("input[name='rlu']").attr("disabled", false);
            $('.p_scnt'+ i +'').remove();
            }
         });   
                 // Moneyline Local
                var arrmll = $("#mll").map(function() { return $(this).val(); }).get();
        $('#mll').change(function () {
            if ($('#mll').is(':checked')) {
                $('<input type="text" id="p_scnt'+ i +'" class="p_scnt'+ i +'" size="20" name="p_scnt_' + i +'" value="'+ arrmll +'" placeholder="No Disponible" />').appendTo(scntDiv);
             i++;   
                         $("input[name='rlo']").attr("disabled", true);
                         $("input[name='rlu']").attr("disabled", true);
                         $("input[name='mlv']").prop('checked', false);
            } else if ($('#mll').not(':checked')) {
                        i--;
            $("input[name='rlo']").attr("disabled", false);
            $("input[name='rlu']").attr("disabled", false);
            $('.p_scnt'+ i +'').remove();
            }
         });             
                 // Runline Over
                var arrrlo = $("#rlo").map(function() { return $(this).val(); }).get();
        $('#rlo').change(function () {
            if ($('#rlo').is(':checked')) {
                $('<input type="text" id="p_scnt'+ i +'" class="p_scnt'+ i +'" size="20" name="p_scnt_' + i +'" value="'+ arrrlo +'" placeholder="No Disponible" />').appendTo(scntDiv);
             i++;   
             $("input[name='mlv']").attr("disabled", true);
                         $("input[name='mll']").attr("disabled", true);
                         $("input[name='rlu']").prop('checked', false);                  
            } else if ($('#rlo').not(':checked')) {
                        i--;
            $("input[name='mlv']").attr("disabled", false);
            $("input[name='mll']").attr("disabled", false);                     
            $('.p_scnt'+ i +'').remove();
            }
         });             
                 // Runline Under
                var arrrlu = $("#rlu").map(function() { return $(this).val(); }).get();
        $('#rlu').change(function () {
            if ($('#rlu').is(':checked')) {
                $('<input type="text" id="p_scnt'+ i +'" class="p_scnt'+ i +'" size="20" name="p_scnt_' + i +'" value="'+ arrrlu +'" placeholder="No Disponible" />').appendTo(scntDiv);
             i++; 
             $("input[name='mlv']").attr("disabled", true);
                         $("input[name='mll']").attr("disabled", true);
                         $("input[name='rlo']").prop('checked', false);                  
            } else if ($('#rlu').not(':checked')) {
                        i--;
            $("input[name='mlv']").attr("disabled", false);
            $("input[name='mll']").attr("disabled", false);                     
            $('.p_scnt'+ i +'').remove();
            }
         });             
                 // Over
                var arrov = $("#ov").map(function() { return $(this).val(); }).get();
        $('#ov').change(function () {
            if ($('#ov').is(':checked')) {
                $('<input type="text" id="p_scnt'+ i +'" class="p_scnt'+ i +'" size="20" name="p_scnt_' + i +'" value="'+ arrov +'" placeholder="No Disponible" />').appendTo(scntDiv);
             i++;  
                         $("input[name='un']").prop('checked', false);                   
            } else if ($('#ov').not(':checked')) {
                        i--;
            $('.p_scnt'+ i +'').remove();
            }
         });             
                 // Under
                var arrun = $("#un").map(function() { return $(this).val(); }).get();
        $('#un').change(function () {
            if ($('#un').is(':checked')) {
                $('<input type="text" id="p_scnt'+ i +'" class="p_scnt'+ i +'" size="20" name="p_scnt_' + i +'" value="'+ arrun +'" placeholder="No Disponible" />').appendTo(scntDiv);
             i++; 
                         $("input[name='ov']").prop('checked', false);                   
            } else if ($('#un').not(':checked')) {
                        i--;
            $('.p_scnt'+ i +'').remove();
            }
         });             
                 
                 
                 
                 
});
<script src="http://ift.tt/VorFZx"></script>
<input type="checkbox" id="mlv" name="mlv" value="+200"/>

                                                        <input type="checkbox" id="mll" name="mll" value="-200"/>
                                                        
                                                        <input type="checkbox" id="rlo" name="rlo" value="+100"/>

                                                        <input type="checkbox" id="rlu" name="rlu" value="-100"/>

                                                        <input type="checkbox" id="ov" name="ov" value="+300"/>

                                                        <input type="checkbox" id="un" name="un" value="-300"/>                                           
</br>

                                                        <div id="p_scents">

                                                        </div>

Thaks in advance Alex