2

I have following html code.

<div class="list">
   <p id="item1">Item 1</p>
   <p id="item2">Item 2</p>
   <p id="item3">Item 3</p>
   <p id="item4">Item 4</p>
</div>

<input name="item1" type="checkbox"/>
<input name="item6" type="checkbox"/>
<input name="item5" type="checkbox"/>

And when i click on checkbox i want to add new <p> tag to the <div> with id like input's name.

$('input').click(function(){
   $('.list').append('<p id="' + $(this).attr("name") + '"</p>'); 
});

But items with the same id should not be repeated! How can i check it? I'm thinking i need to loop through my list of <p> something like this

$('.list p').each(function(){
    if (..element with same id exists..) {
        ....    
    } else {
       ('.list').append('<p id="' + $(this).attr("id") + '"</p>');    
    }
});
user3673623
  • 1,795
  • 2
  • 12
  • 18

4 Answers4

0

You can use the length of paragraph elements in .list and and it in id variable in the end to make them unique:

$('input').click(function(){ 
  if($(this).is(':checked')){// on checked true
  var p_length=$('.list p').length; //find length of p elements
  if(p_length==0)
    $('.list').append('<p id="' + $(this).attr("id") + '"</p>');    
  else
    $('.list').append('<p id="' + $(this).attr("name")+"_"+p_length + '"</p>'); 
 }
});
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

You can check the length prop of selected objects by selecting it through id:

$("#YourId").length >0 //this means id already exist.

here are the ref links:

http://learn.jquery.com/using-jquery-core/faq/how-do-i-test-whether-an-element-‌​exists/

jquery how to find if div with specific id exists

Community
  • 1
  • 1
Hassan Baig
  • 346
  • 1
  • 10
  • You can see this also [http://stackoverflow.com/questions/3373763/jquery-how-to-find-if-div-with-specific-id-exists](http://stackoverflow.com/questions/3373763/jquery-how-to-find-if-div-with-specific-id-exists) and [http://learn.jquery.com/using-jquery-core/faq/how-do-i-test-whether-an-element-exists/](http://learn.jquery.com/using-jquery-core/faq/how-do-i-test-whether-an-element-exists/) – Hassan Baig Sep 16 '14 at 07:13
  • ok..yup , you are right. I was thinking trying to count more than one which doesn't work http://jsfiddle.net/fp8trt0u/ Got a bit ahead of myself – charlietfl Sep 16 '14 at 07:21
0

Try this $(element).has('#id');

   if( $('.list').has('#foo') )
{
  //dont append
}
else
{
//append
}
divakar
  • 1,379
  • 6
  • 15
  • 31
0

Try this:

$('input').on('click', function(){
    inputId = $(this).attr('name');
    console.log($('.list').find('#' + inputId));
    if($('.list').find('#' + inputId).length === 0)
    {
        $('.list').append('<p id="' + inputId + '"></p>'); 
    }
});

DEMO

Karmidzhanov
  • 229
  • 3
  • 14