Add Attribute to inputs but with same class

0

I have different inputs type checkbox with a value ="{"valor":"1"}" or value ="{"valor":"0"}" . For example:

<input type="checkbox" id="switch" name="switch" value ="{"valor":"1"}" ">
<input type="checkbox" id="switch" name="switch" value ="{"valor":"0"}" ">
<input type="checkbox" id="switch" name="switch" value ="{"valor":"0"}" ">
<input type="checkbox" id="switch" name="switch" value ="{"valor":"1"}" ">

What I want to do is go through and add the attribute checked if this is a input with value {"valor":"1"} otherwise the attribute will not be added. For example:

<input type="checkbox" id="switch" name="switch" value ="{"valor":"1"}" checked">
<input type="checkbox" id="switch" name="switch" value ="{"valor":"0"}" ">
<input type="checkbox" id="switch" name="switch" value ="{"valor":"0"}" ">
<input type="checkbox" id="switch" name="switch" value ="{"valor":"1"}" checked">

This is my function but it changes all the inputs:

$('#switch').each(function(){

   if ($(this).val() == '{"valor":"1"}' )
   {
      $('#switch').attr("checked",true);
   }
   else{
     $('#switch').attr("checked",false);
   }
});

I know that it changes all the inputs because they have the same id ... but that id can not change it, will there be another way to do it? ...

    
asked by sebamim 12.06.2018 в 19:14
source

1 answer

0

There is a concept error in the html code. By definition, an id should be unique throughout the code. Not like an attr name.

Another thing that I see is that a checkbox does not need value, since they are two states 1, 0, on, off.

if( $('.micheckbox').attr('checked') ) {
    alert('Seleccionado');
}

If you want to send to the backend, you use p. eg in php isset(controlcheckbox) defined or not defined. p. ex. (isset($_POST['abmt_chkactivo'])) ? 1 : 0); (when sending the form)

    
answered by 12.06.2018 в 19:37