简体   繁体   English

创建jquery对象数组并将其值发布到表单提交中

[英]Creating jquery object array and posting its values on form submit

I have dynamicly added html elements(selectlists) in a form : 我已经以一种形式动态添加了html elements(selectlists):

//Dynamicly adding selectlist elements
function newshit() {
    i = i + 1
    $("#mytable").append("<tr><td><div id='div" + i + "'><select id='elem" + i + "' name='elem" + i + "' class='ted'></select><input type='button' value='-' id='buttonminus" + i + "' style='width:5%;' onclick='removeelem(elem" + i + ",buttonminus" + i + "," + i + ")'/></div></td></tr>")
    getitems("elem" + i)
}

//filling lists
function getitems(item) {
    $.getJSON('@Url.Content("~/Stok/Items/")', {}, function (data) {
        $.each(data, function (i, c) {
            $("#" + item).append("<option value='" + c.Value + "' title='" + c.Text + "' label='" + c.Text + "'>" + c.Text + "</option>")
        })
    })
}

//removing element, when button next to it used
function removeelem(elem,buttonminus,i) {
    if ($("select").length > 1) {
        $("#div" + i).closest('tr').empty().remove()
    } else if ($("select").length <= 1) {
        alert("At least 1 of items must be chosen to create a group!")
    }
}

//checking elements and values existence
function check() {
    var slcts = $("select").serialize();
    alert(slcts)
}

im trying to get the value of each selectlist's selected option value and put them into an array than send them to my controller on form submit. 我试图获取每个选择列表的选定选项值的值,并将它们放入数组,然后将它们发送到表单提交时的控制器。

How can i achive this? 我怎样才能做到这一点?

Need to check this, but I think that the following should work: 需要检查一下,但是我认为以下应该起作用:

  1. Change your code so that the format of your ids is something like: 更改代码,以使ID的格式类似于:

    id="elem[0]" id =“ elem [0]”

Then if your controller has a signature something like this: 然后,如果您的控制器具有如下签名:

public ActionResult Something(IEnumerable<string> elem)
{

}

Then his should "just work". 然后他应该“工作”。

You could use something like - 您可以使用类似-

var selectdata = $("select").serialize()

This will return a string in the form <select name attribute1>=<chosen value1>&<select name attribute2>=<chosen value2> etc. You'd need to add a 'name' attribute to your select HTML when you create it for this to work. 这将以以下形式返回字符串: <select name attribute1>=<chosen value1>&<select name attribute2>=<chosen value2>等。创建时,需要在选择的HTML中添加“名称”属性为此工作。

Demo - http://jsfiddle.net/ipr101/fZXha/ 演示-http://jsfiddle.net/ipr101/fZXha/

You could then put the selectdata variable in a hidden field before the form was posted or send it via AJAX using the ajax or post methods. 然后,您可以在发布表单之前将selectdata变量放在隐藏字段中,或使用ajaxpost方法通过AJAX发送它。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM