简体   繁体   English

如何使用javascript插入和获取动态创建的输入字段的值?

[英]How to insert and get the value of a dynamically created input field using javascript?

I am creating inputs dynamically depending on a radio button that's clicked and I am having trouble getting the value that is inserted in the input field.我正在根据单击的单选按钮动态创建输入,但在获取输入字段中插入的值时遇到问题。 I need to print the value that is inserted in a label field that is also created dynamically.我需要打印插入到也是动态创建的标签字段中的值。 It looks like this: https://codepen.io/christmastrex/pen/jOmxmQY它看起来像这样: https : //codepen.io/christmasrex/pen/jOmxmQY

So, if it's selected number 4, 4 input fields are created, and in column 3 I need to print the values inserted in the input fields.因此,如果选择了数字 4,则会创建 4 个输入字段,并且在第 3 列中我需要打印输入字段中插入的值。

Here is the code:这是代码:

<div class="row">
    <div class="column">
        <h2>Column 1</h2>

        <div>
            <input type="radio" value="1" name="col1"><label for="1">1</label>
            <input type="radio" value="2" name="col1"><label for="2">2</label>
            <input type="radio" value="3" name="col1"><label for="3">3</label>
            <input type="radio" value="4" name="col1"><label for="4">4</label>
            <input type="radio" value="5" name="col1"><label for="5">5</label>
        </div>

        <button type="button">Add</button>
    </div>

    <div class="column" style="background-color:#ccc;">
        <h2>Column 2</h2>
        <div class="add-input"></div>
    </div>

    <div class="column">
        <h2>Column 3</h2>
        <div class="add-label"></div>
    </div>
</div>
.column {
    float: left;
    width: 30%;
    padding: 10px;
}

.row:after {
    content: "";
    display: table;
    clear: both;
}

#col2 {
    display: none;
}
var inputDiv = document.getElementsByClassName("add-input")[0];
var inputLabel = document.getElementsByClassName("add-label")[0];
var btn = document.querySelector('button[type="button"]');

btn.onclick = function () {
    var radioCheckedNum = document.querySelector('input[type="radio"]:checked')
    .value;

    for (let i = 0; i < radioCheckedNum; i++) {
        var inputFieldValue;
        inputDiv.innerHTML += `<input type="text" id="" value="" name="col2" onChange="${inputFieldValue}"><br><br>`;
        inputFieldValue = document.querySelector('input[name="col2"]').value;
        
        console.log(inputFieldValue);
        
        inputLabel.innerHTML += `<label>Label ${radioCheckedNum} - ${inputFieldValue}</label><br><br>`;
    }
};

Please check the following commented code:请检查以下注释代码:

 // GET ELEMENTS MORE EFFICIENTLY BY USING IDs. const inputs = document.getElementById('add-input'); const labels = document.getElementById('add-label'); const button = document.getElementById('button'); const radios = document.querySelectorAll('input[type="radio"]'); // CREATE UTILITY FUNCTION TO CLEAR ALL CHILDREN FROM A NODE. const clear = (node) => { while (node.firstChild) { node.removeChild(node.lastChild); } }; const onClickHandler = () => { // CLEAR PREVIOUS ELEMENTS (REMOVE IF NOT NEEDED). clear(inputs); clear(labels); // GET CHECKED RADIO IN A MORE EFFICIENT WAY (WITHOUT QUERYING THE DOM AGAIN). const radio = Array.from(radios).find((input) => input.checked); // DO NOTHING IF NO RADIO IS CHECKED. if (!radio) { return; } // GET NUMBER OF INPUTS. const number = parseInt(radio.value); for (let i = 0; i < number; i++) { const index = i; /* NEVER USE 'innerHTML' BECAUSE IT IS NOT SAFE! INSTEAD, CREATE ELEMENTS PROGRAMMATICALLY USING DOM APIs AS FOLLOWS */ const input = document.createElement('INPUT'); const label = document.createElement('LABEL'); // SET INPUT ATTRIBUTES. input.name = `${index}`; input.type = 'text'; // ADD EVENT LISTENER TO EACH INPUT. input.addEventListener('input', ({target}) => { /* THIS CALLBACK WILL BE FIRED FOR EACH INPUT INDEPENDENTLY. HERE YOU CAN LEVERAGE 'label' REFERENCE TO CHANGE THE CORRESPONDING INNER TEXT. */ label.innerText = `Label ${index} - "${target.value}"`; }); // SET LABEL ATTRIBUTES. label.innerText = `Label ${index} - ""`; // ADD CREATED INPUT TO DOM AND SOME 'br' ELEMENTS. inputs.append( ...[ input, document.createElement('BR'), document.createElement('BR') ] ); // ADD CREATED LABEL TO DOM AND SOME 'br' ELEMENTS. labels.append( ...[ label, document.createElement('BR'), document.createElement('BR') ] ); } }; // ADD EVENT LISTENER TO BUTTON USING THE NEWEST API (RECOMMENDED). button.addEventListener('click', onClickHandler);
 .column { float: left; width: 30%; padding: 10px; } .row:after { content: ""; display: table; clear: both; }
 <div class="row"> <div class="column"> <h2>Column 1</h2> <div> <input type="radio" value="1" name="col1"><label for="1">1</label> <input type="radio" value="2" name="col1"><label for="2">2</label> <input type="radio" value="3" name="col1"><label for="3">3</label> <input type="radio" value="4" name="col1"><label for="4">4</label> <input type="radio" value="5" name="col1"><label for="5">5</label> </div> <button id="button">Add</button> </div> <div class="column" style="background-color:#ccc;"> <h2>Column 2</h2> <div id="add-input"></div> </div> <div class="column"> <h2>Column 3</h2> <div id="add-label"></div> </div> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何动态删除使用JavaScript动态创建的输入字段 - How to dynamically remove input field which is created dynamically using JavaScript 如何使用 vanilla JavaScript 从动态创建的输入字段中获取数据? - How can I get data from dynamically created input field using vanilla JavaScript? 如何使用使用Javascript动态创建的输入字段? - How to work with input field that is created dynamically using Javascript? 如何使用javascript / jQuery将值分配给动态创建的输入框 - How to assign value to dynamically created input box using javascript/Jquery 如何引用在JavaScript中动态创建的输入的值 - How to refer to the value of an input that was created dynamically in JavaScript 如何使用javaScript获取动态创建的表的名称属性值 - How to get name attribute value for dynamically created table using javaScript 使用JavaScript获取动态创建的文本框的价值 - Get value of dynamically created textbox using JavaScript 如何在IE8和IE9中使用JavaScript或JQuery获取输入值和动态创建的输入的选定值? - How do I get input value and Selected Value of dynamically created inputs using JavaScript or JQuery in IE8 and IE9? jQuery无法从动态创建的字段获取输入值 - JQuery can't get input value from dynamically created field 无法从动态创建的隐藏输入字段中获取价值 - Can't get value from dynamically created hidden input field
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM