skip to Main Content

The following is my ajax

$.ajax({
  url: formUrl,
  complete :function(){
    $("#formContainer").removeClass("some-class");
  },
  success: function(response){
    $("#formContainer").html(response);
    initFunctionOne();
    initFunctionTwo();
    initFunctionThree();
   }
 });
}

‘response’ contains respective html forms in string format depending on what screen is being loaded. Is there any way i can get the form ID from that response so that I can use switch case statements to only call the function whose form ID matches with the form ID in the html response.

I’m initialising the three functions outside document.getready and the above mentioned ajax call is inside the document.getready

I’ve tried to use .find and .filter but both of them did not work due to an error (error : .filter is not a function)

3

Answers


  1. Chosen as BEST ANSWER

    Not sure if this is a good practice but i have declared a variable and set the substring of the form ID using indices. And using that variable i have used if else conditions to call the functions


  2. As your response string is in HTML format, you can get the form id in a nice, easy and clean way by making use of DOMParser as below:

    //shorter version
    var formId = (new DOMParser()).parseFromString(response, "text/html").forms[0].id; //done
    

    Alternatively, a more detailed and reusable version is given below with an example:

     //Use DOMParser to convert the HTML string to a valid HTML document object  
      function parseHTMLString(htmlString) {
        const parser = new DOMParser();
        return parser.parseFromString(htmlString, "text/html");
      };
    
      //Get the form id of the first form element from the doc object. 
      //You may also return an array of form ids if you have multiple forms in your response.
      function getFirstFormIdFromParsedHtmlString(doc) {
        //console.log(doc.forms);
        return doc.forms[0].id;
      }
    
      //this is how to use it
      
      //example response string
      var response = '<form id="myForm1"></form>';
    
      const myDocument = parseHTMLString(response);
    
      const formId = getFormIdFromParsedHtmlString(myDocument);
    
      console.log('formId:', formId); //prints 'formId: myForm1'
    

    If you want to test the above, you can just copy/paste this code snippet in a <script>...</script> block to a blank HTML file ‘example.html’ and check the Console logs after you open this in your browser. This should just work fine as above.

    Login or Signup to reply.
  3. Try this to get the id of from in the response HTML.

    var formID = $($.parseHTML(response)).find('form').attr('id');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search