skip to Main Content

I am developing an Application in Asp.Net Core MVC6.

I have a Razor page that render dynamically object.

Assuming I have creating dynamically this two Divs in my page

 <div id="A1">
         <input type="text" id="SearchSSN" />
        <input type="text" id="SearchLastName" />
    </div>
    <div id="A2">
         <input type="text" id="SearchSSN" />
        <input type="text" id="SearchLastName" />
    </div>
<a href="#" onclick="Search()" class="nav-link px-4 py-4" title="Show All"></a>

When I call Search() function in javascript, I want to read the value inside each Div

function Search() {
-- to read value from Object
var SSN: $("#SearchSSN").val(),
}

But I want to read the value inside each Div

Something like

$("#A1").("#SearchSSN").val()
$("#A2").("#SearchSSN").val()

How can I Do it?

Thanks

2

Answers


  1. Modify your Search() Method like this

    function Search() {
        var A1_SSN = $("#A1").find("#SearchSSN").val();
        var A1_LastName = $("#A1").find("#SearchLastName").val();
    
        var A2_SSN = $("#A2").find("#SearchSSN").val();
        var A2_LastName = $("#A2").find("#SearchLastName").val();
    
        // do something
    }
    
    Login or Signup to reply.
  2. You can find all your divs using querySelectorAll and then use map to pull the values out into an array using querySelector to find the input inside the div.

    Here is an example that will just log the values to the console when you click ‘Search’

    function Search() {
      const divs = document.querySelectorAll('div[id^=A]');
      var values = [...divs].map((div) => div.querySelector('#SearchSSN').value)
      console.log(values);
    }
    <div id="A1">
      <input type="text" id="SearchSSN" />
      <input type="text" id="SearchLastName" />
    </div>
    <div id="A2">
      <input type="text" id="SearchSSN" />
      <input type="text" id="SearchLastName" />
    </div>
    <div id="A3">
      <input type="text" id="SearchSSN" />
      <input type="text" id="SearchLastName" />
    </div>
    <div id="A4">
      <input type="text" id="SearchSSN" />
      <input type="text" id="SearchLastName" />
    </div>
    <a href="#" onclick="Search()" class="nav-link px-4 py-4" title="Show All">Show All</a>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search