How to have an HTML Input Field not Send a String Value if Left Blank - send nothing

174 views Asked by At

I have an issue and want to see if this thought is possible. I created a project tracker where an individuals can load their project information (office, project title, status, date, assigned to., etc). The form works great. I have another form, update form, for the individual to update their input value (choice same as load project form: office, project, title, status, date, assigned to., etc) as the project progress. This form updates great. However, a issue I am having, if the HTML field is left blank, on the update form HTML input field, it sends a value of “null” that overrides the value posted to the tracker list of post - not being updated. The update form intended purpose is to give the individual a list of possible choices to what they might need to update, in this case everything.

Is there a way to not send any value if the input field is left blank to not override the value currently posted? Is this even possible or do I need to do something different, like have a separate update form for each different area/column being updated.

I am posting and updating the values to a SharePoint using the REST API.

---Edit to include Script---

<div id="container">
   <!-- --------------- code to update a list item ------------- -->
   <div id="updateForm">
      <div id="UpdateClose" style='text-align: left; float: right; margin-right: 10px; cursor: pointer;'>Close</div>
      <div style='margin: 0 auto; width: 100%; padding-top: 5px; padding-bottom: 5px; color: white; margin-top: 40px; margin-bottom: 10px; background-color: orange;'>
         <p>Click here to move</p>
      </div>
      <p>Fill out this form completely to update your item.</p>
      <input placeholder="Item ID" type="text" id="itemID">
      <table>
         <tr>
            <td>Office</td>
            <td><input type="text" id="uOffice" style="width: 200px"></td>
         </tr>
         <tr>
            <td>Project Title</td>
            <td><input type="text" id="uProjectTitle" style="width: 200px"></td>
         </tr>
         <tr>
            <td>Priority</td>
            <td><input type="text" id="uPriority" style="width: 200px"></td>
         </tr>
         <tr>
            <td>Start Date</td>
            <td><input type="text" id="uStartDate" style="width: 200px"></td>
         </tr>
         <tr>
            <td>Assigned To</td>
            <td><input type="text" id="uAssignedTo" style="width: 200px"></td>
         </tr>
         <tr>
            <td>Status</td>
            <td><input type="text" id="uStatus" style="width: 200px"></td>
         </tr>
         <tr>
            <td>Requestor</td>
            <td><input type="text" id="uRequestor" style="width: 200px"></td>
         </tr>
      </table>
      <button id="UpdateListItem">UPDATE</button>
   </div>
   <div id="introTxt">
      <p>Post and Track your Projects</p>
      <p id='openForm'><img class='qIcon' src="https://intelshare.intelink.gov/sites/dcsa/ep/epMainFiles/Project_Tracker/graphics/google-docs.svg" alt="logo" style="width: 100px; position: relative; top: 0px; margin-right: 10px; cursor: pointer; "><span style='color: blue; cursor: pointer; position: relative; top: 20px; font-weight: bold;' >Select to post a project. When the post project form opens, hover over the input fields for additional instructions.</span></p>
      <p id='openUForm'><img class='qIcon' src="https://intelshare.intelink.gov/sites/dcsa/ep/epMainFiles/Project_Tracker/graphics/google-docs.svg" alt="logo" style="width: 100px; position: relative; top: 0px; margin-right: 10px; cursor: pointer; "><span style='color: black; cursor: pointer; position: relative; top: 20px; font-weight: bold;' >Select to update a task. When the post project form opens, hover over the input fields for additional instructions.</span></p>
   </div>
   <div id="qForm" style='width: 250px; height: auto; padding: 10px; position: absolute; z-index: 10; background-color: white; border: 1px solid grey; text-align:center; cursor: all-scroll; display: none;'>
      <div id="qFormClose" style='text-align: left; float: right; margin-right: 10px; cursor: pointer;'>Close</div>
      <div style='margin: 0 auto; width: 100%; padding-top: 5px; padding-bottom: 5px; color: white; margin-top: 40px; margin-bottom: 10px; background-color: orange;'>
         <p>Click here to move</p>
      </div>
      <input type="text" placeholder="Enter Your Office" name="Office" id="office" title='Enter in your office' required> <br><br>
      <input type="text" placeholder="Enter a Project Name" name="Project Name" id="project" title='Enter in a project name' required> <br><br>
      <input type="text" placeholder="Priority" name="url" id="priority" title='Enter in project priority'> <br><br>
      <input type="text" placeholder="Project Start Date" name="Start Date" id="startDate" title='Enter in project start date'> <br><br>
      <input type="text" placeholder="Assigned to" name="Assigned" id="assigned" title='Project assigned to'> <br><br>
      <input type="text" placeholder="Status" name="Status" id="status" title='Project status'> <br><br>
      <input type="text" placeholder="Requestor" name="Requestor" id="requestor" title='Project requestor'> <br><br><br>
      <div id="udList" style='cursor: pointer';>Submit</div>
   </div>
   <div class="row vertical-padding"></div>
   <!--Close of vertical padding-->
   <div id="leftCol" class="grid_12">
      <input id="myInput" type="text" placeholder="To find a specific task, enter either the office name, individual's name, or by task ID...">
      <h2 style='color:blue; marigin: 0 auto; text-align: center; font-weight: bold;'>Project List</h2>
      <p>Select table header to sort.</p>
      <div id="CustomerPanel">
         <table id='tableCars' style="width: 100%;" border="1 px">
            <tr>
               <td>
                  <div id="carsGrid" style="width: 100%"></div>
               </td>
            </tr>
         </table>
      </div>
   </div>
   <!--Close of grid-->
</div>
<!--Close container-->



/*Add to Project Tracker List*/
var context;
var web;
var Url;
var listItemEntity;

jQuery(document).ready(function() {
  SP.SOD.executeFunc('sp.js', 'SP.ClientContext', FunctionReady);
  ItemSubmit();


  $("#qForm").draggable();

  $("#qFormClose").click(function() {
    $("#qForm").fadeOut();

  });

  $("#openForm").click(function() {
    $("#qForm").fadeIn();

  });

  $("#openUForm").click(function() {
    $("#updateForm").fadeIn();
  });

}); //Close of document ready function

var answer = document.getElementById('comAnswer');

function ItemSubmit() {
  $("#udList").click(function() {
    $("#qForm").fadeOut(400);


    var officeValue = $("#office").val();
    var projectValue = $("#project").val();
    var priorityValue = $("#priority").val();
    var startDateValue = $("#startDate").val();
    var assignedValue = $("#assigned").val();
    var statusValue = $("#status").val();
    var requestorValue = $("#requestor").val();

    if (this.value != 0) {
      AddItemToList(listItemEntity, officeValue, projectValue, priorityValue, startDateValue, assignedValue, statusValue, requestorValue);
    } else {

      AddItemToList(listItemEntity, officeValue, projectValue, priorityValue, startDateValue, assignedValue, statusValue, requestorValue);

    }

    $('#qForm').children('input').val('');



  });
}

function FunctionReady() {
  context = new SP.ClientContext.get_current();
  web = context.get_web();
  context.load(web);
  context.executeQueryAsync(onRequestSuccess, onRequestFailure);
}

function onRequestSuccess() {
  Url = web.get_url();
  GetListItemEntity(Url);
}

function onRequestFailure(sender, args) {
  alert("Error Occured:" + args.get_message());
}

function GetListItemEntity(webUrl) {
  var queryUrl = webUrl + "/_api/lists/getbytitle('ProjectTracker')?$select=ListItemEntityTypeFullName";
  $.ajax({
    url: queryUrl,
    method: "GET",
    headers: {
      "Accept": "application/json;odata=verbose"
    },
    success: onEntitySuccess,
    error: onEntityFailure
  });
}


function onEntitySuccess(data) {
  listItemEntity = data.d.ListItemEntityTypeFullName;
}

function onEntityFailure(err) {
  alert(err.statusText);
}

function AddItemToList(r, officeValue, projectValue, priorityValue, startDateValue, assignedValue, statusValue, requestorValue) {

  try {

    var queryUrl = Url + "/_api/lists/GetByTitle('ProjectTracker')/items?";

    $.ajax({
      url: queryUrl,
      type: "POST",
      contentType: "application/json;odata=verbose",
      data: JSON.stringify({
        '__metadata': {
          'type': r
        },

        'Office': officeValue,
        'ProjectTitle': projectValue,
        'Priority': priorityValue,
        'StartDate': startDateValue,
        'AssignedTo': assignedValue,
        'Status': statusValue,
        'Requestor': requestorValue
      }),
      headers: {
        "accept": "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val()
      },
      success: onQuerySucess,
      error: onQueryFailure
    });
  } catch (ex) {
    alert("Exception" + ex.message);
  }
}

function onQuerySucess() {
  jQuery("#success").fadeIn();

}

function onQueryFailure(error) {
  alert(JSON.stringify(error));
}


jQuery(document).ready(function() {

  ////Project Tracker Table script
  var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('ProjectTracker')/items";
  $.ajax({
    url: requestUri,
    type: "GET",
    headers: {
      "accept": "application/json; odata=verbose"
    },
    success: onSuccess,
    error: onError
  });



  function onSuccess(data) {
    var objItems = data.d.results;
    var tableContent = '<table id="projectTable" style="width:100%" border="1 px"><thead><th>ID</th>' + '<th>Office</th>' + '<th>Project_Title</th>' + '<th>Project_Priority</th>' + '<th>Project_Date</th>' + '<th>Assigned_To</th>' + '<th>Project_Status</th>' + '<th>Requestor</th>' + '</thead><tbody>';


    for (var i = 0; i < objItems.length; i++) {
      tableContent += '<tr class="sortTable">';
      tableContent += '<td>' + objItems[i].ID + '</td>';
      tableContent += '<td>' + objItems[i].Office + '</td>';
      tableContent += '<td>' + objItems[i].ProjectTitle + '</td>';
      tableContent += '<td>' + objItems[i].Priority + '</td>';
      tableContent += '<td>' + objItems[i].StartDate + '</td>';
      tableContent += '<td>' + objItems[i].AssignedTo + '</td>';
      tableContent += '<td>' + objItems[i].Status + '</td>';
      tableContent += '<td>' + objItems[i].Requestor + '</td>';
      tableContent += '</tr>';
    }





    $('#projectGrid').append(tableContent);


  }

  function onError(error) {
    alert('Error');
  }




}); ///End of Document Ready Function



///Sort Project Table
jQuery(document).ready(function() {

  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $(".sortTable").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });


  jQuery(document).on("click", 'th', function() {
    if ($(this).is('.asc')) {
      $(this).removeClass('asc');
      $(this).addClass('desc selected');

      sortOrder = -1;
    } else {
      $(this).addClass('asc selected');
      $(this).removeClass('desc');

      sortOrder = 1;
    }

    var table = $(this).parents('table').eq(0)
    var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))
    this.asc = !this.asc
    if (!this.asc) {
      rows = rows.reverse()
    }
    for (var i = 0; i < rows.length; i++) {
      table.append(rows[i])

    }


  })

}); //close of document ready

//Update Project Tracker list item Script

$(document).ready(function() {

  jQuery(document).on("click", '#UpdateListItem', function() {
    updateListItem();
  }); //button closed

  jQuery(document).on("click", '#UpdateClose', function() {
    $("#updateForm").fadeOut();
  }); //button closed


  function updateListItem() {

    //var listName = "ProjectTracker";
    var url = _spPageContextInfo.webAbsoluteUrl;
    var myID = $("#itemID").val();
    var listName = "ProjectTracker";
    var office = $("#uOffice").val();
    var pTitle = $("#uProjectTitle").val();
    var priority = $("#uPriority").val();
    var startDate = $("#uStartDate").val();
    var assignedTo = $("#uAssignedTo").val();
    var status = $("#uStatus").val();
    var requestor = $("#uRequestor").val();
    var title = "New Updated Information";
    var itemType = "SP.Data.Project_x0020_TrackerListItem";

    console.log(office);

    var item = {
      "__metadata": {
        "type": itemType
      },
      "Title": title, 
      "Office": office,
      "ProjectTitle": pTitle,
      "Priority": priority,
      "StartDate": startDate,
      "AssignedTo": assignedTo,
      "Status": status,
      "Requestor": requestor
    };

    $.ajax({
      url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('ProjectTracker')/items(" + myID + ")",
      type: "POST",
      type: "POST",
      contentType: "application/json;odata=verbose",
      data: JSON.stringify(item),
      headers: {
        "Accept": "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val(),
        "X-HTTP-Method": "MERGE",
        "If-Match": "*"
      },
      success: onSuccess,
      error: onError
    });

    function onSuccess(data) {
      jQuery("#success").fadeIn();
    }

    function onError(error) {

      alert(JSON.stringify(error));
    }
  } //Function close


});
0

There are 0 answers