bademeister
bademeister

Reputation: 107

jQuery selector can't find added elements in DOM

I know that the solution is the jQuery.on-function but it don't work as I expect it would do.

Following problem: I pull via Websocket(JSON) data and build my page up inside the document ready function (for connection reasons). That means I add several input fields via the jQuery.append()-function and try to access the select-input when the SET button is pressed. Accessing the select input fails. I have selected the body as parent element, every other form field should be in it.

For demo reasons I removed the Websocket-Functions. I have hardcoded the form as it would be in real. The debug-messages are displayed in the firebug-console. Here is the fiddle: http://jsfiddle.net/gLauohjd/

This is the way I am accessing the select input

$("body").on('click', ':button', function () {
    console.log( $( this ).text() ); //Value of the pressed button
    var ip = $(this).attr('ip');
    var selectvalue = "#" + "modeselect" + ip;
    console.log(selectvalue); //Print the selector to verify it is ok
    console.log($(selectvalue).val()); //fails ->not found in DOM

Any help on that is very appreciated!

Upvotes: 1

Views: 470

Answers (1)

George Nemes
George Nemes

Reputation: 196

To select a tag with jQuery, use just the tag name.

$("body").on('click', 'button', function () { .. } // any button clicked on body

As for actually retrieving the values, you won't be able to do so unless you escape the dots.

$("#modeselect127\\.0\\.0\\.1").val();

You could use something like:

var selectvalue = "#" + "modeselect" + ip.replace(/\./g, "\\\\.");

Hope this helps.

Upvotes: 1

Related Questions