skip to Main Content

I have a form where I’m using Bootstrap container, rows and cols. In every row can be 1+ cols, and in every col can be one of two:

  1. checkbox, label, select:
<input type="checkbox">
<label> Some lable_1 </label>
<select class="select2">
  <option> Something </option>
</select>

or
2) checkbox, label, input:

<input type="checkbox">
<label> Some label_2 </label>
<input type="text" class="form-control">

Also I have a button to clear every select / input which checkbox is True.
None that in every col checkbox is the first elem and select / input – last

Here my button code:
<button type="button" class="btn btn-default" onclick="ClearSelectedElems($('#MyFormId'))" > Clear all checked </button>

Here is my function’s code:

function ClearSelectedElems(form) {
  $.each(form[0]['children'], function(index_row, value_row) {
    var row = form[0]['children'][index_row];
    $.each(row['children'], function(index_col, value_col) {
      var col = row['children'][index_col];
      var first = col['children'][0];
      var prev_last = col['children'][col['children']['length'] - 2];
      var last = col['children'][col['children']['length'] - 1];

      //console.log("first['checked']", first['checked']);
      //console.log("prev_last", prev_last);
      //console.log("prev_last['value']", prev_last['value']);          
      //console.log("last", last);

      if (first['checked']) {
        last['value'] = '777777';
        prev_last['value'] = '777777';
      }
    })
  })
}

About my code:
Function gets a jQuery object as input parametr
First loop goes through all rows;
Second loop goes through all cols in current row;
var first – checkbox of current row and col;
var prev_last – select or some rubish (I will explain lower);
var last – input of current row and col;

`if ()` - if checkbox is checked ---> change select / input field

I use prev_last and last together because when I meet select it isnt last element in current object’children it has this: [0 - ..., 1 - ..., n-1 - select, n - span]

I want to clear all selected elements without id’s through jQuery’s $.each, but I met a problem which I can’t solve.
I hope I has writen my problem quite clear and you will be able to understand the condition and help me.

I have learnt how to get ‘checked’ property from checkboxes,
also I can get and set ‘value’ property from and for inputs,
the only thing I can’t do now is to get / set value for inputs (it throws error when I write prev_last[‘value’] Can you help me please?

I tried only algorithm from above and coundn’t succeed.
Also I tried to do it throug id’s but also failed. (want to mention that ther first idea is better for my look because I can easyly add / remove rows and cols and it will work anyway without any need to rewrite all id’s by programmer’s hands)

2

Answers


  1. I think this is what you are after.

    • I have rows and columns in a grid.
    • A column will always contain a checkbox and either an input or a select.
    • on a button press I want to clear the values of all inputs/selects within the same column of a checked check-box

    My approach would be to;

    1. locate all the checked checkboxes
    let checked = $(".col>input[type='checkbox']:checked"); 
    
    1. loop through them
    2. locate the input / select in the same column using siblings()
    3. clear the value in the input, and the check-state.
    $(function() {
      $("button.clear").on("click", function() {
        let checked = $(".col>input[type='checkbox']:checked");
        checked.each(function(idx, elem) { //elem is a checked checkbox in a column
          $(elem).siblings("input, select").val(""); //clear any input/select in the same column
          $(elem).prop("checked", false); //uncheck the box
        });
      });
    });
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class='container'>
      <div class='row'>
        <div class='col'><input type="checkbox">
          <label> Some lable_1 </label>
          <select class="select2">
            <option> Something </option>
          </select>
        </div>
      </div>
      <div class='row'>
        <div class='col'><input type="checkbox">
          <label> Some lable_1 </label>
          <select class="select2">
            <option> Something </option>
          </select>
        </div>
      </div>
      <div class='row'>
        <div class='col'><input type="checkbox">
          <label> Some lable_1 </label>
          <input value="superman" type="text" />
        </div>
      </div>
      <div class='row'>
        <div class='col'><input type="checkbox">
          <label> Some lable_1 </label>
          <select class="select2">
            <option> Something </option>
          </select>
        </div>
      </div>
    </div>
    <button class="clear">clear</button>
    Login or Signup to reply.
  2. Sounds like you’re looking for DOM traversal, no identifiers required.

    jQuery has a number of custom css selectors, :checked being the one for elements with the checked property being true. You can use this to get just the checked checkboxes, then get the parent column of that, then get the child inputs / selects from that.

    Building from @Steve0 answer, because I don’t feel like retyping the html and also I assume that you want the selects to reset to the first option, rather than to just go blank?

    $('button.default').on('click', function() {
      $('input[type="checkbox"]:checked').each(function() {
        let $parent = $(this).prop('checked', false).parents('.col');
        
        $parent.find('input[type="text"]').val('');
        $parent.find('select').each(function() { this.selectedIndex = 0; });
      });
    });
    /* not important, just for aesthetics */
    input[type="text"] { margin: 8px; width: 120px; }
    .row { border: 1px solid #dddddd; margin: 8px; padding: 8px; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class='container'>
      <div class='row'>
        <div class='col'>
          <input type="checkbox">
          <label> reset </label>
          <select>
            <option> Something </option>
            <option> Something ELse </option>
            <option> Something More </option>
            <option> Something Less </option>
          </select>
        </div>
      </div>
      <div class='row'>
        <div class='col'>
          <input type="checkbox">
          <label> reset </label>
          <input type="text">
          <input type="text">
          <input type="text">
        </div>
      </div>
      <div class='row'>
        <div class='col'>
          <input type="checkbox">
          <label> reset </label>
          <select>
            <option> Is SUS </option>
            <option> Is not SUS </option>
            <input type="text" placeholder="murder weapon?">
            <input type="text" placeholder="murder location?">
          </select>
        </div>
      </div>
    </div>
    <button class="default">clear</button>

    Also I’ll mention that <button type="button" class="btn btn-default" is full of redundancies. I know that you’re supposed to define type for a button, but in practice I’ve never done or needed this. Also element procedes class in the css hierarchy, so unless you’re doing something more complex, <button type="button" class="btn btn-default"> == <button class="default">

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search