Home > Net >  How to target span by class name and get ID then pass ID in Ajax?
How to target span by class name and get ID then pass ID in Ajax?

Time:12-09

I am trying to get id of a span in a dropdown which has classname and id is dynamic but classname is always fixed so I tried this document.querySelector(".tag").id and this is working when I select the span from dropdown but when I did not select anything from dropdown my ajax gives an error main.js:357 Uncaught TypeError: Cannot read properties of null (reading 'id') which is clearly for this, How will I pass this span id so that if I select or not it should be pass in ajax?

why is it happening?

update:

I have tried this

  const element = document.querySelector(".tag");

  if (element) {
    jourid = element.id   "_"   $("#tags_input").val();
  } else {
    jourid = " ";
  }

but now it says jourid not define if I am not selecting the value ! how will i resolve this ?

<span id="249257" ><span>Test</span><a href="javascript:void(0)">x</a></span>
$(function () {
    var frm = $("#saveform");
    frm.submit(function (ev) {
      ev.preventDefault();
      $.ajax({
        type: frm.attr("method"),
        url: frm.attr("action"),

        data: {
          PubId: $("#Publications").val(),
          sdate: $("#datepicker").val(),
          jour:document.querySelector(".tag").id,
          pnumber: $("#pnumber").val(),
        },
        cache: false,
        error: function (err, data) {
          console.log("There was an error. Try again please!"   data, err);
        },
        success: function (data) {
          alert( "Saved!");
          window.location.reload();
        },
      });
    });
  });

How will I pass the id of span so that there will be successful ajax call whether value is empty or not?

CodePudding user response:

The error is occuring because the document.querySelector was not able to find any span elements.

You only need to add a check on whether the query return any element before accessing id field of it.

something like this:

frm.submit(function (ev) {
  ev.preventDefault();
  
  // this will set `undefined` to id if the span element is not obtained
  var id = document.querySelector(".tag")?.id; 

  // now you can error check here and return if needed
  // if(!id) return;
  
  //or set id as empty
  if(!id) id = " ";

  $.ajax({
        type: frm.attr("method"),
        url: frm.attr("action"),
        data: {
          // ...,
          jour: id,
          // ...
        },
        ...
      });
}

as for the jourid not defined, you just need to write let jourid; before using the variable in if statment, like so

  let jourid;
  if (element) {
    jourid = element.id   "_"   $("#tags_input").val();
  } else {
    jourid = " ";
  }
  • Related