-1

I'm tried to .append() a new radio type, then if I clicked in new radios, start a new function, but I can't do this. this is my code:

HTML:

<label>Where take the photo?</label>
        <input type="radio" id="MX0" name="wherePhoto" value="MX0"> México
        <input type="radio" id="EX0" name="wherePhoto" value="EX0"> Foreign
<div id="newPhoto"></div>

<div>
      <a class="btn btn-default" onclick="addPhoto();" id="btnAdd">Add photo</a>
</div>

JS:

var id = 1;
function addPhoto() {
  var $newPhoto='<div><label>Where take the photo?</label><input type="radio" id="MX' +id+ '"name="wherePhoto' + id + '" value="MX"> México<input type="radio" id="EX' +id+ '" name="wherePhoto' +id+ '" value="EX"> Foreign   <div>';

  $('#newPhoto').append($newPhoto);  
  id++;
}

$('[id^=MX]').click(function() {
  alert("hello MX");        
});

$('[id^=EX]').click(function() {
  alert("hello EX");    
});

So I try to send a alert when click on the new Radio (MX1)

Thanks to any help

Lubelmont
  • 7
  • 2
  • 7

1 Answers1

0

Read about Event delegation

var id = 1;

function addPhoto() {
  var $newPhoto = '<div><label>Where take the photo?</label><input type="radio" id="MX' + id + '"name="wherePhoto' + id + '" value="MX"> México<input type="radio" id="EX' + id + '" name="wherePhoto' + id + '" value="EX"> Foreign   <div>';
  $('#newPhoto').append($newPhoto);
  id++;
}

$('#newPhoto').on('click', '[id^=MX]', function() {
  alert("hello MX");
});

$('#newPhoto').on('click', '[id^=EX]', function() {
  alert("hello EX");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<label>Where take the photo?</label>
<input type="radio" id="MX0" name="wherePhoto" value="MX0">México
<input type="radio" id="EX0" name="wherePhoto" value="EX0">Foreign
<div id="newPhoto"></div>
<div>
  <a class="btn btn-default" onclick="addPhoto();" id="btnAdd">Add photo</a>
</div>
Rayon
  • 36,219
  • 4
  • 49
  • 76
  • Thanks for the answer and for helping me understand more of Event Delegation – Lubelmont May 27 '16 at 05:31
  • @Lubelmont, Happy to help! Kindly [accept and up-vote](http://meta.stackexchange.com/questions/23138/how-to-accept-the-answer-on-stack-overflow) the best solution which has solved the purpose :) __Happy coding!__ – Rayon May 27 '16 at 05:32