Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding HTML form field using jQuery

Tags:

html

jquery

dom

Since I cant use div inside forms, I wonder how can I add new field in the middle of the form (and I can't use .append() here) without reloading the page or rewriting the form? (using jQuery)

EDIT: this is the HTML:

<form id="form-0" name="0"> <b>what is bla?</b><br> <input type="radio" name="answerN" value="0"> aaa <br> <input type="radio" name="answerN" value="1"> bbb <br> <input type="radio" name="answerN" value="2"> ccc <br> <input type="radio" name="answerN" value="3"> ddd <br> //This is where I want to dynamically add the new radio or text line  <input type="submit" value="Submit your answer"> //but HERE is where .append() will put it!  </form> 
like image 804
ilyo Avatar asked May 23 '11 15:05

ilyo


People also ask

How dynamically add HTML element using jQuery?

You can use jQuery DOM manipulation methods like append(), appendTo() or html() to add new HTML elements like div, paragraph, headings, image into DOM without reloading the page again.

How do I add a dynamic field in HTML?

Create a button and on clicking this button we will dynamically add the input fields. Now write the click() function to handle the adding and removing functionality. Use the append() method to add the input field code to the existing HTML document.

How do you create a dynamic input?

If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container"> . Create new elements by means of document. createElement() , and use appendChild() to append each of them to the container.


2 Answers

What seems to be confusing this thread is the difference between:

$('.selector').append("<input type='text'/>");  

Which appends the target element as a child of the .selector.

And

$("<input type='text' />").appendTo('.selector'); 

Which appends the target element as a child of the .selector.

Note how the position of the target element & the .selector change when using the different methods.

What you want to do is this:

$(function() {    // append input control at start of form   $("<input type='text' value='' />")      .attr("id", "myfieldid")      .attr("name", "myfieldid")      .prependTo("#form-0");    // OR    // append input control at end of form   $("<input type='text' value='' />")      .attr("id", "myfieldid")      .attr("name", "myfieldid")      .appendTo("#form-0");    // OR    // see .after() or .before() in the api.jquery.com library  }); 
like image 89
thastark Avatar answered Sep 22 '22 03:09

thastark


This will insert a new element after the input field with id "password".

$(document).ready(function(){   var newInput = $("<input name='new_field' type='text'>");   $('input#password').after(newInput); }); 

Not sure if this answers your question.

like image 41
Fredrik Avatar answered Sep 24 '22 03:09

Fredrik