Home > front end >  Get a form ID from html response of an ajax call (jQuery)
Get a form ID from html response of an ajax call (jQuery)

Time:09-07

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)

CodePudding user response:

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

CodePudding user response:

Try this to get the id of from in the response HTML.

var formID = $($.parseHTML(response)).find('form').attr('id');

CodePudding user response:

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.

  • Related