MishMish MishMish - 28 days ago 8
Javascript Question

How to call input id in javascript

I'm trying to do some javascript work on this example:

var str= '<td><input id="product" type="checkbox" name="product' + i + '" value="Yes" />&nbsp; new product?</td>';
str = str+'<td><input type="text"class="form-control" id="number ' + i + '" name="number' + i + '" placeholder="GTIN"</td>'


<script>
$(document).ready(function () {
var ckbox = $('#product');

$('input').on('click', function () {
if (ckbox.is(':checked')) {
document.getElementById("number").readOnly = true;
document.getElementById("number").value = "";
} else {
document.getElementById("number").readOnly = false;
}
});
});
</script>


This seems to work only if my input checkbox is outside the string builder

Answer

If I understood your question correctly you are trying to check if input created as string is checked or not. To do so, you can try something like this:

HTML

<div id="number">
  <table id='mytable'>

  </table>

</div>

JS

var str;
for(var i = 0; i < 4; i++){
    str = '<td><input id="product'+i+'" type="checkbox" checked name="product' + i + '" value="Yes" />new product?';
  str = str+'<td><input type="text"class="form-control" id="number ' + i + '" name="number' + i + '" placeholder="GTIN" data-checkbox-id="product'+i+'"></td>'
    $("#mytable").append(str);
}

$("[id*='product']").on("click", function(){
    var this_id = $(this).attr("id");

    if( $(this).is(":checked") )
      $("input[data-checkbox-id='"+this_id+"']").removeAttr("disabled");
    else
      $("input[data-checkbox-id='"+this_id+"']").attr("disabled", "disabled");
 });

Check the Fiddle: https://jsfiddle.net/koky7zj1/11/
Is that what you are looking for?

Edit
See updated code. I'm glad I could help! :)

Comments