0

I'm attempting to dynamically create a button using JQuery to create the button, initialize it, and insert it into the DOM. When the following code executes, an element is added into the DOM, however instead of being:

<input value="button">Click Me</input>

The item in the DOM is just:

<input>

Not sure why the properties are not being initialized or a complete htlm element is being created.

var list = $("#rootElement").find(".listclass");
var button = $("<input/>", {
    type : button,
    value : "Click Me"
});
list.append(button)
1
  • change button to "button" and it will work. Commented Dec 20, 2014 at 6:34

2 Answers 2

1

Do this instead

IMO it's much more easy.

var list = $("#rootElement").find(".listclass");
list.append('<input type="button" value="Click Me"/>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rootElement">
  <div class="listclass">
  </div>
</div>
   

BTW: <input> tag doesn't accept content.

<input value="button">Click Me</input>  <-- wrong

should be

<input type="button" value="Click Me"/> <-- good

or just

<button>Click Me</button>

Your code fixed

You forgot put quotes in button.

var list = $("#rootElement").find(".listclass");
var button = $("<input>", {   
    type: 'button', // here forgot quotes
    value: 'Click Me'
});
list.append(button)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="rootElement">
      <div class="listclass">
    </div>
 </div>

Sign up to request clarification or add additional context in comments.

Comments

0

You need to write type: "button" instead of type: button

Here is the fiddle: http://jsfiddle.net/su9m81yu/2/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.