简体   繁体   中英

Retrieving value from dynamically generated elements using Jquery Name attribute

I have a mvc cshtml form where I am generating multiple rows using following syntax :

foreach (var i in Model)
   {            
    <td>
     @Html.TextBoxFor(a => a[j].SFDCID, new { id = "SFDCID", @class ="SFDCID" })
    </td>
   }

This is resulting HTML snippet like :

 <input class="SFDCID" id="SFDCID" name="[0].SFDCID" type="text" value="">
    <input class="SFDCID" id="SFDCID" name="[1].SFDCID" type="text" value="">
.....
.....

Now I want to check if user has entered values in all SFDCID field then only the form submit should happen else should throw validation message.

For that I am trying to access the value using its name attribute & have written following code:

           for (var i = 0; i <= totalNumberOfRows; i++) {

                var elementName = '[' + i + '].SFDCID';    
                if ($("[name = elementName]").val() == "" || 
                                     $("[name = elementName]").val() == undefined) 
                {
                        ConsolidatedErrorMsg = "SFDC ID is a Mandatory field.";
    }
}

I have tried with class, id & name as selector to get the value, but in first 2 case its only working for 1st row. With Name selector its working for both name if I hard code the element name like '[0].SFDCID' & '[1].SFDCID' but when I am substituting i with 0 & 1, its not working.

Kindly help me to rectify any syntax error I have in this selector.

$("[name = elementName]") is actually selecting all elements with the name of, literally, elementName . You actually need to escape square brackets and concat the value you have constructed:

var elementName = '\\[' + i + '\\].SFDCID';
$("[name='" + elementName + "']")

Even better approach would be to use ends with selector:

$("[name$='\\.SFDCID']").each(function() {
    // this here refers to the found element
    var $this = $(this);
    if ($this.val() === "" || typeof($this.val()) === undefined) {
        ConsolidatedErrorMsg = "SFDC ID is a Mandatory field.";
    }
})

A couple of side notes. Please remove id = "SFDCID" bit, as duplicated IDs on the page may lead to inconsistent behavior. And consider using built-in ways to validate required fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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