jQuery jquery动态添加隐藏字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2833989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:21:46  来源:igfitidea点击:

jquery dynamic adding hidden field

jquery

提问by maztt

$().ready(function() 
  {
  $("#add").click(function() 
    {
    var vals = $("#txtaddfeature").val();
    if(vals !='')
      $('#FeatureLists').prepend('<option value="' + vals + '" selected="selected">' + vals + '</option>');
    $('#txtaddfeature').val('');
    });
  });

Ok after adding the value to the select list as above

将值添加到上述选择列表后确定

$('#FeatureLists').prepend('<option value="' + vals + '" selected="selected">' + vals + '</option>');

I want to create a dynamic hidden field with id=vals defined above and set it value to value entered in the textbox . how can i do that

我想用上面定义的 id=vals 创建一个动态隐藏字段,并将其值设置为在 textbox 中输入的值。我怎样才能做到这一点

回答by user113716

I couldn't tell exactly what you wanted. It seems like you want both the IDand the valueof the new hidden inputto be the value of vals. Is that right?

我不能确切地说出你想要什么。似乎您希望新隐藏的theID和 the都是. 那正确吗?valueinputvals

var $hiddenInput = $('<input/>',{type:'hidden',id:vals,value:vals});

Then you would append it wherever you want.

然后你可以将它附加到任何你想要的地方。

$hiddenInput.appendTo(selector);

EDIT:

编辑:

For clarification, selectoris the reference to the element where you want to append your new input.

为了澄清起见,selector是对要在其中附加新输入的元素的引用。

If you want to append it to the body tag, do:

如果要将其附加到 body 标记,请执行以下操作:

$hiddenInput.appendTo('body');

If you want to append it to an element with the class someClass, do:

如果要将其附加到具有 class 的元素someClass,请执行以下操作:

$hiddenInput.appendTo('.someClass');

回答by hunter

I would check to see if it was on the page first, then add.

我会先检查它是否在页面上,然后添加。

function SetHiddenInput(val)
{
    var $txtaddfeaturehidden == $("#txtaddfeaturehidden");

    if ($txtaddfeaturehidden.length == 0)
    {
        $("input").attr({
            id : "txtaddfeaturehidden", 
            type : "hidden",
            value : $('#txtaddfeature').val()
        }).after('#txtaddfeature');
    }
    else $txtaddfeaturehidden.val(val);
}

回答by Sarfraz

You can do like:

你可以这样做:

$("input").attr("type", 'hidden').val($('#txtaddfeature').val()).appendTo('selector_here');