I am trying to add input field dynamically with assign custom name from these aa,ab,ac,ad.
Here is the code:
<script>
$(function() {
$('body').on('click', '.post-link', function() {
$('#post-container').fadeIn();
var post_title = $(this).closest('div').find('a').text();
var val = $(this).text("val");
if (val == "")
var post_id = "aa";
else if (val == "aa")
var post_id = "ab";
else if (val == "ab")
var post_id = "ac";
else
var post_id = "ad";
if ($('#post-container input').length <= 3)
$('#post-container').append('<input name="' + post_id + '" value="' + post_title + '">-- <a href="#" class="remove-title">REMOVE</a></input>');
});
$('body').on('click', '.remove-title', function() {
$(this).closest('input').remove();
});
});
</script>
HTML:
<button class="post-link" rel="<?php the_ID(); ?>"> ADD </button>
<div id="post-container"> </div>
Now the problem is that this adds name="ad" for all four fields; but I need each field with a different name.
How to assign different name to each input field?
And why not remove-title link work?
$(this).text("val");what are you trying to get with this? It should be$(this).val()!for (var i = 0; i < 3; i++) $('body').append('<input name='+Math.floor(Math.random() * 99)+'/>');<input name="' + post_id + '" value="' + post_title + '">-- <a href="#" class="remove-title">REMOVE</a></input>input is a void element, and void elements do not have an end tag--------------------------------------------- ^^^^^ Plus I'm not really sure an<a>nchor could be inside an input even if it wasn't a void element.