Search code examples
javascriptjqueryformscheckboxradio-button

How do I get an element from the list of element in js, which has a custom attribute?


I want to get all element that has costume value attribute from list of same element in jQuery.

I have this following HTML form :

<label>name <input type="text" name="name" value="value"></label>
<label>value1 <input type="radio" name="name1" value="value1"></label>
<label>value2 <input type="radio" name="name1" value="value2"></label>
<label>value3 <input type="radio" name="name1" value="value3"></label>
<label>value4 <input type="checkbox" name="name2[]" value="value4"></label>
<label>value5 <input type="checkbox" name="name2[]" value="value5"></label>

And i did try this following code :

form = $('form');
form_data = {
    'name':'test value',
    'name1':'value2',
    'name2[check]':'value5',
};
$.each(form_data,function(i,v){
    input = form.find('[name="'+i+'"]');
    inputtype = input.attr('type');

    if(inputtype == 'checkbox' || inputtype == 'radio'){
        input.has('[value="'+v+'"]').prop('checked',true);
    }else{
        input.val(v);
    }
});

But when i try input.has('[value="'+v+'"]') for get same element attribute then i did not return any element to checked that element.. ! any solution for this..?


Solution

  • You can use filter, this will reduce the variable input to those only have a value that is equal to variable v

    Here is the snippet.

    $(function() {
    
      var form = $('form');
    
      var form_data = {
        'name': 'test value',
        'name1': 'value2',
        'name2[]': 'value5',
      };
    
      $.each(form_data, function(i, v) {
        var input = form.find('[name="' + i + '"]');
        var inputtype = input.attr('type');
    
        if (inputtype == 'checkbox' || inputtype == 'radio') {
          input.filter(function() {return this.value === v;}).prop('checked', true);
        } else {
          input.val(v);
        }
      });
    
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form>
      <label>name <input type="text" name="name" value="value"></label>
      <label>value1 <input type="radio" name="name1" value="value1"></label>
      <label>value2 <input type="radio" name="name1" value="value2"></label>
      <label>value3 <input type="radio" name="name1" value="value3"></label>
      <label>value4 <input type="checkbox" name="name2[]" value="value4"></label>
      <label>value5 <input type="checkbox" name="name2[]" value="value5"></label>
    </form>

    For more docs: http://api.jquery.com/filter/