SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    Non-Member
    Join Date
    Nov 2010
    Posts
    220
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    problem with, jQuery add extra input form fields?

    Hello
    I tried, I do not know why this code does not work.
    What is your comment?

    Code JavaScript:
    $(document).ready(function () {
    var i = $('#gasht b').size() + 1;
     
    $('#add').click(function(event){
      event.preventDefault();
      $('<p><label for="gashte"><input type="text" id="gashte" size="20" name="gasht_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="rem">Remove</a></p>').appendTo('#gasht');
      i++;
      return false;
      });
    });

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,684
    Mentioned
    99 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by binboy View Post
    What is your comment?
    Do you have some HTML code that the script is being used with, so that we may test things out?
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Enthusiast
    Join Date
    Jun 2011
    Location
    Dartmouth, MA, USA
    Posts
    49
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Regardless of what the HTML is, it's bad practice to create several nested HTML elements within a jQuery call like that. For example, creating the elements one at a time and chaining the methods reduces the work that jQuery has to do:

    Code JavaScript:
    $("<p></p>").append(
      $("<label></label>")
        .attr("for", "gashte")
        .append(
          $("<input />")
            .attr({type: "text", id: "gashte", size: 20, name: "gasht_" + i, placeholder: "Input Value"})
        )
      )
      .append(
        $("<a></a>")
          .attr({href: "#", id: "rem"})
          .text("Remove")
      )
      .appendTo("#gasht");

    That code is a little ugly with all the chaining; you can save newly created elements to variables instead to clean it up if you want. Regardless, it's better than creating all those elements all at once in one jQuery call, which could potentially be why the code isn't working, though I'd have to see the HTML to really know.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •