user525146
user525146

Reputation: 3998

Create a label using jQuery on the fly

I need to create a label and text field on the fly and also include datepicker for the textfield. I need something like this:

<label for="from">From </label> <input type="text" id="from" name="from" />

I have tried something like this in jQuery:

var label = $("<label>").attr('for', "from");   
                    label.html('Date: ' +
                        '<input type="text" id="from name="from" value="">');

                    $(function() {
                        $("#from").datepicker();
                    }); 

This one somehow doesn't create the label and also the text field. I am not sure what I am missing.

EDIT

To be more precise, I am using this in the portlets and I don't have body tags in the jsp page. So when I call the function to append to body it won't.

Upvotes: 16

Views: 58778

Answers (5)

kai_onthereal
kai_onthereal

Reputation: 488

An example from a project im working on right now

let fieldContainer = $("<div/>", {
    class: "dialog-field",
}).appendTo(container);

$("<input/>", {
    type: "checkbox",
    id: `dialog-field-${keyLabel}`,
    name: keyLabel,
}).appendTo(fieldContainer);

$(`<label/>`, {
    text: keyLabel,
    for: `dialog-field-${keyLabel}`,
}).appendTo(fieldContainer)

Upvotes: 0

kapa
kapa

Reputation: 78731

Something like this would work:

//Create the label element
var $label = $("<label>").text('Date:');
//Create the input element
var $input = $('<input type="text">').attr({id: 'from', name: 'from'});

//Insert the input into the label
$input.appendTo($label);
//Insert the label into the DOM - replace body with the required position
$('body').append($label);

//applying datepicker on input
input.datepicker();

jsFiddle Demo

Please note that you don't have to use the for attribute on the label if the input element is inside it. So use one of these:

<label><input id="x1"></label>

<label for="x1"></label> <input id="x1">

Upvotes: 26

Ilia G
Ilia G

Reputation: 10221

1) You are missing closing quote at the end of the ID attribute.
2) You didn't append the label itself to anything.

Upvotes: 0

Bryan
Bryan

Reputation: 6752

Where are you trying to insert the label? If you want it at the beginning of the page, you can do something like this.

var $label = $("<label>").attr('for', "from");   

$label.html('Date: <input type="text" id="from" name="from" value="">');

$(function() {
    $('body').prepend($label);

    $(':input', $label).datepicker();
});

Upvotes: 1

rjz
rjz

Reputation: 16510

You will need to attach the label you've created to the DOM to get it to show:

var label = $("<label>").attr('for', "from");
    label.html('Date: ' +
      '<input type="text" id="from name="from" value="">');

label.appendTo('body');

// set up datepicker
label.find('#from').datepicker();

Upvotes: 4

Related Questions