首页 > 解决方案 > 如何从 Input type="number" 中获取值,并将其提供给其他输入的 value 属性

问题描述

我正在尝试编辑我的表格行。当我尝试编辑它时,以前的值没有更新到新的输入框中。我想在新的输入框中获取数字。我尝试通过,value="' + $(this).text() + '">'但它适用于type="text",而它不适用于 type="number"。任何人都可以请帮忙。

// Edit row on edit button click
$(document).on("click", ".edit", function(){        
    $(this).parents("tr").find("td:not(:last-child, :nth-last-child(2))").each(function(){
        $(this).html('<input type="text" class="heading_label-box" value="' + $(this).text() + '">');
    });  
    $(this).parents("tr").find("td:nth-last-child(3)").each(function(){
        $(this).html('<input type="number" class="heading_total-weight" value="' + $(this).text() + '">');
    });    
    $(this).parents("tr").find(".add, .edit").toggle();
    $(".add-heading, .add-point").attr("disabled", "disabled");
});

我试过了$(this).val()$(this).value()但无法获得价值。

标签: javascriptjquery

解决方案


由于您要使用输入更新的对象是 TD,因此您应该这样做:

$(document).on("click", ".edit", function(){        
    $(this).parents("tr").find("td:not(:last-child, :nth-last-child(2))").each(function(){
        let thisVal = $(this).text();
        let inputObj = $('<input type="text" class="heading_label-box"/>');
        inputObj.val(thisVal);
        $(this).html('');
        $(this).append(inputObj);
    });  
    $(this).parents("tr").find("td:nth-last-child(3)").each(function(){
        let thisVal = $(this).text();
        let inputObj = $('<input type="number" class="heading_total-weight"/>');
        inputObj.val(thisVal);
        $(this).html('');
        $(this).append(inputObj);
    });    
    $(this).parents("tr").find(".add, .edit").toggle();
    $(".add-heading, .add-point").attr("disabled", "disabled");
});

推荐阅读