如何创建表单元素输入框,标签使用javascript onclick

How to create form elements input box , label using javascript onclick

本文关键字:标签 onclick javascript 输入 元素 何创建 创建 表单      更新时间:2023-09-26

我想知道如何通过 onclick 函数使用 JavaScript 创建隐藏类型输入框和标签。

$().ready(function() {  
    $("#product").autocomplete("get_completeproducts", {            
        width: 406,
        matchContains: true,
        selectFirst: false
    });
});

<input type="text" value="" name="product" id="product" size="50">
<input type="button" value="Add to List" onclick="addprotolist()" name="select_pro">

通过ajax自动完成获取上面的输入框值,用户会点击选择框,然后我要做的是,我必须添加列出他们下面所选手机的数量,就像输入框一样

<label>Samsung Galaxy Y<label><input type="hidden" value="778" name="pro_id[]">
<label>Samsung Galaxy Y Duos<label><input type="hidden" value="788" name="pro_id[]">
<label>Samsung Galaxy Y Plus<label><input type="hidden" value="728" name="pro_id[]">
.
.
.
<input type="submit" name="save" value="Save your list">

任何人都可以为我提供如何使用JavaScript或jQuery编写代码。

function addprotolist() {
  var str = '<label>'+ var_for_text +'</label><input type="hidden" value="'+ var_for_value +'" name="pro_id[]">';
  $('#yourform').append( str );
}

注意

如果你想使用循环附加多个inputlabel等,不要在循环内调用追加,这会降低性能。制作一个像上面这样的字符串,最后调用.append()

例如

var str = '';
function addprotolist(inputObj) {
  // a typical example of inputObj may be
  // inputObj = [ {labelText: 'some 1', value: 'val1' }, {labelText: 'some 2', value: 'val2'} ]
  // loop
  for(var i = 0; i < inputObj.length; i++ ) {
    str += '<label>'+ inputObj[i].labelText +'</label><input type="hidden" value="'+ inputObj[i].value +'" name="pro_id[]">';
  }
  // call append outside of loop
  $('#yourform').append( str );
}

但是这样使用label就没有意义了。您必须通过包装它或指定指向输入idfor 属性来将其连接到您的input

<!-- Simple label example with for attribute -->  
<input type="radio" name="clickmebutton" id="clickmebutton">
<label for="clickmebutton">Click me</label>  
<!-- or more simply -->  
<label><input type="radio" name="clickmebutton"> Click me</label>  

label 在 MDN 上