Solved

Populating html form in Sharepoint using JSOM

Posted on 2016-11-14
11
65 Views
Last Modified: 2016-11-14
I am trying to populate my form using JSOM but I'm having no luck. I don't get an error but when I go into debug mode, the form gets populated with the queried data.  Not sure why.

<link rel="stylesheet" href="/bootstrap.min.css">
<link rel="stylesheet" href="/jquery-ui.css">
<link rel="stylesheet" href="/jquery-ui.theme.min.css">

    <script src="/jquery.js"></script>
    <script src="/bootstrap.min.js"></script>    
    <script src="/jquery-ui.js"></script>     
    <script src="/projectPlanning.js"></script>

  <script>
  $( function() {
    $( "#ppcDate" ).datepicker();
    $( "#padDate" ).datepicker();
    $( "#aadDate" ).datepicker();
    $( "#mDescDate" ).datepicker();
	$( "#da_Date" ).datepicker();
	$( "#origDate" ).datepicker();
  } );
  </script>    
    <style>
<style>
    #home, #menu1, #menu2, #menu3 { 
        padding: 10px;
    }
    
    #projInfo {
        margin-left:65px;
        margin-bottom:15px;
    }
</style>

<div id="projInfo">
    <table width="65%">
        <tr>
            <td>Project Title</td>
            <td><input type="text" id="projTitle"></td>
        </tr>
        <tr>
            <td>VISN</td>
            <td><input type="text" id="visn"></td>
        </tr>
        <tr>
            <td>Station</td>
            <td><input type="text" id="station"></td>
        </tr>
        <tr>
            <td>Station Name</td>
            <td><input type="text" id="stationName"></td>
        </tr>  
        <tr>
            <td>Project Number</td>
            <td><input type="text" id="projNumber"></td>
        </tr>        
    </table>
</div>

Open in new window



JavaScript code (The adding portion works.  The retrieve works as well, it's just not populating my form unless I go into debug mode.)
$(document).ready(function() {
	$("#design_procPlan").on("click", function () {
		ppDesign_addListItem();
	});
});
SP.SOD.executeOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");

var getQueryString = function (field, url) {
    var href = url ? url : window.location.href;
    var reg = new RegExp('[?&]' + field + '=([^&#]*)', 'i');
    var string = reg.exec(href);
    return string ? string[1] : null;
};

//Retrieves all list items- Will need to modify to take in query string data to pass to CAML.
function retrieveListItems() {
    var clientContext = new SP.ClientContext();
    var oList = clientContext.get_web().get_lists().getByTitle('Project Module');
    
    if (getQueryString('projNumber')) {
        var prjQry = "<View><Query><Where><Eq><FieldRef Name='Project_x0020_Number' /><Value Type='Text'>" + getQueryString('projNumber') + "</Value></Eq></Where></Query><ViewFields><FieldRef Name='Title' /><FieldRef Name='Project_x0020_Number' /><FieldRef Name='Station_x0020_Name' /><FieldRef Name='VISN' /><FieldRef Name='Station_x0020_Number' /></ViewFields></View>";  
        //      
    }
    else {
        var prjQry = "<View><Query></Query></View>";
    }
    console.log(prjQry);
    
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml(prjQry);
    this.collListItem = oList.getItems(camlQuery);

    clientContext.load(collListItem);

    clientContext.executeQueryAsync(
        Function.createDelegate(this, this.onQuerySucceeded),
        Function.createDelegate(this, this.onQueryFailed)
        );
}

function onQuerySucceeded(sender, args) {
    var listItemInfo = '';
    var listItemEnumerator = collListItem.getEnumerator();
    
 if (listItemEnumerator.moveNext()) {
    
    var oListItem = listItemEnumerator.get_current();
              
    var vsn = oListItem.get_item('VISN');
    var pjTitle = oListItem.get_item('Title')          
	 $('#visn').val(oListItem.get_item('VISN'));
	 $('#projTitle').val(oListItem.get_item('pjTitle'));
	 $('#station').val(oListItem.get_item('Station_x0020_Number'));
	 $('#stationName').val(oListItem.get_item('Station_x0020_Name'));        
	 $('#projNumber').val(oListItem.get_item('Project_x0020_Number'));   
}	 
      
}

function ppDesign_addListItem() {
	var designPlan = $("#designPlan").val();
	var ppcDate= $("#ppcDate").val();
	var padDate = $("#padDate").val();
	var ppcDate= $("#ppcDate").val();
	var aadDate= $("#aadDate").val();
	var setAside= $("#setAside").val();
	var category= "Procurement Plan (Design)";
	
	var clientContext = new SP.ClientContext();
	var oList = clientContext.get_web().get_lists().getByTitle('Project Projections');
	var itemCreateInfo = new SP.ListItemCreationInformation();
	this.oListItem = oList.addItem(itemCreateInfo);
	
	oListItem.set_item('DesignType', designPlan);
	oListItem.set_item('ProcurementDesign', ppcDate);
	oListItem.set_item('PlannedAwardDates', padDate);
	oListItem.set_item('ActualAwardDates', aadDate);
	oListItem.set_item('PlannedAwardDates', padDate);	
	oListItem.set_item('SetAside', setAside);	
	oListItem.set_item('PlanningCategory', category);	
	oListItem.update();
	
	clientContext.load(oListItem);
	clientContext.executeQueryAsync(
	Function.createDelegate(this, this.onAddSucceeded),
	Function.createDelegate(this, this.onAddFailed)
	);
}

function onAddSucceeded(sender, args) {
	$("#submitResult").html("Item successfully added!");
}

function onAddFailed(sender, args) {
	alert('Request failed. ' + args.get_message() +
	'\n' + args.get_stackTrace());
}

Open in new window

0
Comment
Question by:Isaac
  • 7
  • 4
11 Comments
 
LVL 82

Expert Comment

by:leakim971
ID: 41886790
Let the squeleton of your page finish to load

replace :
$(document).ready(function() {
	$("#design_procPlan").on("click", function () {
		ppDesign_addListItem();
	});
});
SP.SOD.executeOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");

Open in new window

by :
$(document).ready(function() {
	$("#design_procPlan").on("click", function () {
		ppDesign_addListItem();
	});
	SP.SOD.executeOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");
});

Open in new window

0
 
LVL 5

Author Comment

by:Isaac
ID: 41886813
That did nor work.  I did notice something strange though.  In the code below, the alert()'s worked but when it gets to the line to populate the textbox ($('#projTitle').val(oListItem.get_item(pjTitle));), it appears blank.  Always blank. Is the .val() method correct?

function onQuerySucceeded(sender, args) {
alert("im in");
    var listItemInfo = '';
    var listItemEnumerator = collListItem.getEnumerator();
    
 while (listItemEnumerator.moveNext()) {
    
    var oListItem = listItemEnumerator.get_current();
                    
    //var vsn = oListItem.get_item('VISN');
    var pjTitle = oListItem.get_item('Title')        
    alert(pjTitle);
	 //$('#visn').val(oListItem.get_item('VISN'));
	 $('#projTitle').val(oListItem.get_item(pjTitle));

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
ID: 41886911
val is for form elements (input, textarea)
text or html is for other like div, span
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 5

Author Comment

by:Isaac
ID: 41886972
Not sure why it's not working. Here's my html code..

  <script>
  $( function() {
    $( "#ppcDate" ).datepicker();
    $( "#padDate" ).datepicker();
    $( "#aadDate" ).datepicker();
    $( "#mDescDate" ).datepicker();
	$( "#da_Date" ).datepicker();
	$( "#origDate" ).datepicker();
  } );
  </script>    
    <style>
<style>
    #home, #menu1, #menu2, #menu3 { 
        padding: 10px;
    }
    
    #projInfo {
        margin-left:65px;
        margin-bottom:15px;
    }
</style>

<div id="projInfo">
    <table width="65%">
        <tr>
            <td>Project Title</td>
            <td><input type="text" id="projTitle" value=""></td>
        </tr>
        <tr>
            <td>VISN</td>
            <td><input type="text" id="visn" value=""></td>
        </tr>
        <tr>
            <td>Station</td>
            <td><input type="text" id="station" value=""></td>
        </tr>
        <tr>
            <td>Station Name</td>
            <td><input type="text" id="stationName"></td>
        </tr>  
        <tr>
            <td>Project Number</td>
            <td><input type="text" id="projNumber"></td>
        </tr>        
    </table>
</div>

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
ID: 41887028
this is bad :
    var pjTitle = oListItem.get_item('Title')        
    alert(pjTitle);
	 //$('#visn').val(oListItem.get_item('VISN'));
	 $('#projTitle').val(oListItem.get_item(pjTitle));

Open in new window

that should be :
    var pjTitle = oListItem.get_item('Title')        
    alert(pjTitle);
	 //$('#visn').val(oListItem.get_item('VISN'));
	 $('#projTitle').val(pjTitle);

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
ID: 41887035
due to the second call, the code break and it do'nt populate the other fields. some of them are null as you can see (I checked their value before the error) :
some of them are not null but code broken
0
 
LVL 82

Expert Comment

by:leakim971
ID: 41887038
look like you cannot call get_item twice...
0
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 41887041
this one woked for me :
function onQuerySucceeded(sender, args) {
    var listItemInfo = '';
    var listItemEnumerator = collListItem.getEnumerator();
    
	if (listItemEnumerator.moveNext()) {
	    
	    var oListItem = listItemEnumerator.get_current();
	    var vsn = oListItem.get_item('VISN');
		$('#visn').val(vsn);
	    var pjTitle = oListItem.get_item('Title')
		$("#projTitle").val(pjTitle);
		var station_number = oListItem.get_item('Station_x0020_Number');
		$('#station').val(station_number);
		var station_name = oListItem.get_item('Station_x0020_Name');
		$('#stationName').val(station_name);
		var project_number = oListItem.get_item('Project_x0020_Number');
		$('#projNumber').val(project_number);   
	}	 
      
}

Open in new window

seems of
0
 
LVL 5

Author Comment

by:Isaac
ID: 41887102
How did you check
>>(I checked their value before the error)

I get an error so I must be doing something wrong.
dev error
0
 
LVL 82

Expert Comment

by:leakim971
ID: 41887116
your page run fine for me now, do you still have issue ?

to check, set a breakpoint or use the "debugger" keyword
don't forget to put semi-column (good practice :P )

debugger; // if your console is open it should let you see the value just like my screen copy
var pjTitle = oListItem.get_item('Title');

Open in new window


but again, your page run fine for me now
0
 
LVL 5

Author Closing Comment

by:Isaac
ID: 41887124
Thanks! It works.

The debugger still does not work for me.
When I add the debugger like you, I opened developer tool and did not see what you showed in your print screen image.

What were your steps?
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).   The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least …
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

823 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question