开发者

I cannot find the name of a dynamically created javascript object (in jQuery)

开发者 https://www.devze.com 2023-01-31 17:05 出处:网络
I have a page which uses javascript to add some textboxes to the page, and then we try to do some work based on these later.

I have a page which uses javascript to add some textboxes to the page, and then we try to do some work based on these later.

What I am having a lot of trouble with though is that I cannot return the 'name' value which I am saving with the js.

Full page source (albeit a simplified version) is below.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script type="text/javascript" src="Scripts/jquery-1.4.1-vsdoc.js"></script>
    <script type="text/javascript"> 
    $(document).ready(function () {
        //we use live because the inputs havent been created yet. 
        $('.myclass').live('blur', function () {
开发者_运维知识库
            //debugger;
            alert('textbox selected has ID '+ $(this).attr('id') ); //this returns txtInput
            alert('textbox selected has name '+ $(this).attr('name') ); //this returns null (or an empty string). 
        });

    AddInputTextBox("My Label: ", "txtInput", "mydiv", "MyName");

    });

    function AddInputTextBox(LabelValue, Id, divToAddTo, NameKey) {
        //debugger;
        var txtbox = document.createElement('input');
        txtbox.setAttribute("type", "text");
        txtbox.setAttribute("id", Id);
        txtbox.setAttribute("name", NameKey);
        txtbox.setAttribute("class", "myclass"); 

        alert('Textbox created with name = ' + txtbox.name);

        var foo = document.getElementById(divToAddTo);
        foo.innerHTML += LabelValue;
        foo.appendChild(txtbox);
    } 
    </script> 
</head>

<body>
    <div id="mydiv">
        <!-- placeholder -->
    </div>
</body>
</html>

So as you can see, document.ready runs and creates one textbox. when the blur fires (box loses focus) - I can access the ID, class, type, etc, but I cannot get a value for the 'name'.

Sure it is something dead simple, but can someone tell me why?


When you create <input> elements with IE, you have to do it like this:

var txtbox = document.createElement('<input name="' + NameKey + '">');

IE doesn't like you changing the "name" attribute of an <input> once it exists, so you have to tell it what you're going to do in the call to "createElement()".

One might wonder why you're not using jQuery to build your dynamic content, since you've loading it anyway.

(edit I thought it was the "type" attribute, but now I think it's "name".)


This seems to be working for me.

http://jsfiddle.net/dem5d/

Am I missing something?

Bob

0

精彩评论

暂无评论...
验证码 换一张
取 消