skip to Main Content

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();

2

Answers


  1. 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();
    }
    Login or Signup to reply.
  2. 📎 – Looks like you’re trying to build a URL-encoded string.

    I strongly suggest building up an object of parameters and passing that through URLSearchParams() or jQuery’s $.param(). That way it will be properly encoded

    const params = {
      firstname: $("#first").val(),
    };
    const data = $("#data").val();
    if (data) {
      params.data = data;
    }
    
    const launch = (new URLSearchParams(params)).toString();
    // or = $.param(params)
    
    console.log("launch:", launch)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input readonly id="first" value="Boaty McBoatFace">
    <input readonly id="data" value="" placeholder="data">
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search