Home > Software engineering >  Would like to add the `data` parameter only when it has value if not then don't add data in the
Would like to add the `data` parameter only when it has value if not then don't add data in the

Time:11-15

I would like to add the data parameter only when it has value if not then don't add data in the parameter string.

Currently, it is throwing unexpected token if and data values shows undefined

function Data() {
  if ($("#data").val().length != 0) {
    "&data="   $("#data").val();
  }
}

function check() {
  launch  = & firstname = "   $("#
  first ").val()   " & data = "   Data();           
}

Adding the parameter in this way

"&data="   Data();

CodePudding user response:

You need to return an empty string if there's no data value.

You need to fix the quoting in check(). And it doesn't need &data=, because that's added by Data().

You should call encodeURIComponent() to ensure that the values are properly encoded.

If you're using $.ajax(), you can avoid all of this by putting the parameters in an object instead of a string. Then you can just conditionally add the data: property to the object.

function Data() {
  if ($("#data").val()) {
    return "&data="   encodeURIComponent($("#data").val());
  } else {
    return "";
  }
}

function check() {
  launch  = "&firstname="   encodeURIComponent($("#first ").val())   Data();
}

CodePudding user response:

  • Related