在JQUERY中获取附加文本框的值

时间:2014-01-17 06:38:51

标签: jquery

需要帮助。

如何获取具有相同类名的附加文本框的值?请找到代码段。

JS:

var count = document.getElementsByName("emailId[]").length; //get the totol no. of contact no. elements
//function to add a new element for entering emailId 
$("#add-email-id").click(function () {
    $("#email-id-container").append('<div id="emailAddress_container_' + count + '" style="margin-top:8px"><input type="text" name="emailId[]"  id="email_address_' + count + '" data-toggle="tooltip" title="Enter Email address here" placeholder="example@example.com" size="30" onBlur="ValidateEmail(' + count + ');" class="emailId"><span><input class="username" id="username_' + count + '" name="username[]" value="username" /></span><span style="margin-left:8px;"><a href="javascript:void(0);"  class="delete-email-id" style="color:#F00;">(-)</a></span><span id="email_err_' + count + '"></span></div>');
    count++; //increment the counter as new contact element is being added.
});

$(document).ready(function () {
    $('.emailId').change(function () {
        var usernameDiv = $(this).parent("div").find(".username").attr("id"); //get the div where the truncated username will be placed
        alert($(this).attr("id"));
        alert($("#" + usernameDiv).val());
        var emailAddress = $(this).val();
        var truncatedValue = emailAddress;
        var name = "";
        if (emailAddress.indexOf("@") != -1) {
            ///alert("@");      
            name = $.trim(emailAddress.split("@")[0]);
            //alert(name);
            if (name && name.search(/\s/) === -1) {
                var len = name.length;
                //alert(len);
                if (len > 4) {
                    truncatedValue = name.substring(0, 3);
                }
                usernameDiv.val(truncatedValue);
            } else {
                usernameDiv.val("username");
            }
        }
    });
});

我需要获取email_address字段的值,然后在附加的相应用户名字段中获取截断值。

1 个答案:

答案 0 :(得分:1)

$('.emailId').change(function() {  //will not work for dynamic generated element

将上面的代码行更改为

$(document).on('change', '.emailId', function() {

而是附加到事件处理程序以记录或确保在创建元素时调用.change事件。