2

I have made a Text box and a save button. when I write something in text box and click save button, I need to save this data every time in the list. How can I do this using Java Script?

Data should be in a column of a list. Every time click save button, data should save in new row.

2
  • i am not making a new item in share point list, i am just saving a line or text from text box to sharepoint list Commented Oct 7, 2016 at 11:54
  • When you save text to sharepoint list there will be 1 record created which is called ListItem. Commented Oct 7, 2016 at 12:55

3 Answers 3

2

You can also use the REST api to add item to list as below. Create javascript file and add its reference in a script editor/content editor webpart:

 function AddData() {
    var listName = "MyList";
    var newItemTitle = $("txtBox").val();
    CreateListItemWithDetails(listName, _spPageContextInfo.webAbsoluteUrl, newItemTitle, function () {
        console.log("New Item has been created successfully.");
 }, function () {
     console.log("Ooops, an error occured. Please try again.");
 });
}

// CREATE Operation
// listName: The name of the list you want to get items from
// weburl: The url of the web that the list is in. 
// newItemTitle: New Item title.
// success: The function to execute if the call is sucesfull
// failure: The function to execute if the call fails
function CreateListItemWithDetails(listName, webUrl, newItemTitle, success, failure) {
    var itemType = GetItemTypeForListName(listName);
    var item = {
        "__metadata": { "type": itemType },
        "Title": newItemTitle
    };

    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
        type: "POST",
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(item),
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            failure(data);
        }
    });
}

// Get List Item Type metadata
function GetItemTypeForListName(name) {
    return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}

the input button would be as below:

<input id="btnSubmit" type="button" value="Save" onclick="AddData();" />

For further reading on how to use REST api , you can follow this blog

1
  • can you pls show one example of a custom html which has datefields, valdiation, client side ppl picker tetxboxes, dropdown lists etc. am looking for a good looking html with the above controls and needs to be saved in the splist.
    – samolpp2
    Commented Oct 25, 2018 at 9:16
1

Add following script to your content editor webpart:

var listName = 'List1'; // Your SharePoint List Name
function createListItem() {

    var txtValue = document.getElementById('textBox1').value; // Your Textbox

    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle(listName);

    var itemCreateInfo = new SP.ListItemCreationInformation();
    this.oListItem = oList.addItem(itemCreateInfo);
    oListItem.set_item('Title', txtValue); // 'Title' is the internalName of the sharepoint list column
    oListItem.update();

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

function onQuerySucceeded() {
    alert('Item added successfully');
}

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

Call createListItem() function on save button:

<input id="btnSubmit" type="button" value="Save" onclick="createListItem();" />

For more: Complete basic operations using JavaScript library code in SharePoint

1

You can create Visual Web part and put this code inside web part and deploy the WSP and add the web part on the page. Or you can add this code directly to Content Editor web part on the particular page.

Try this below code: HTML code:

<div id="insert">  
    <table>  
        <tr>  
            <td> Employee Name: </td>  
            <td>  
                <input type="text" id="txtname" placeholder="Employee Name" /> </td>  
        </tr>  
        <tr>  
            <td> Designation: </td>  
            <td>  
                <input type="text" id="txtdesignation" placeholder="Employee Name" /> </td>  
        </tr>  
        <tr>  
            <td></td>  
            <td>  
                <button type="button" id="buttoninsert" onclick="insert()">Insert</button>  
            </td>  
        </tr>  
    </table>  
</div>  

JS Code:

var siteurl = '/sites/JS';  

function insert()  
{  
    var clientContext = new SP.ClientContext(siteurl); // Get SPSITEURL  
    var list = clientContext.get_web()  
        .get_lists()  
        .getByTitle('Employee'); // Get SP list   
    var itemCreateInfo = new SP.ListItemCreationInformation();  
    var value1 = document.getElementById('txtname')  
        .value;  
    //Get value from input element  
    var value2 = document.getElementById('txtdesignation')  
        .value;  
    //Get value from input element  
    this.oListItem = list.addItem(itemCreateInfo);  
    //Adding list items  
    oListItem.set_item('Title', value1);  
    oListItem.set_item('designation', value2);  
    oListItem.update();  
    clientContext.load(oListItem);  
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));  
}  

function onQuerySucceeded()  
{  
    alert('Item created Successfully');  
}  

function onQueryFailed(sender, args)  
{  
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());  
}  
4
  • i am not making any list in the HTML, i just need to save data from an HTML text box to a share point list. i am using content editor (script editor) web park to view text box and save button.. please give me code for this. it will be very helpful for me, and i will be very thankful to you @Dikesh Commented Oct 7, 2016 at 11:51
  • 1
    The above mention code by @Dikesh Gandhi is the same what you are asking about. It will take the data from HTML control and insert in SharePoint List,. Commented Oct 7, 2016 at 12:23
  • @Dikesh Gandhi , how can i make this script with impersonation to be created by system account , i have sharepoint public site and i want to design html page for questionnaire , and for every one can open this page and submit form to save it to my questionnaire result list , but how the people can submit form and didn't have edit permission of this list , Commented Dec 21, 2017 at 13:35
  • I think from Client side scripts, we cannot do user impersonation. You can create SharePoint app for the same, as app model has different permission scenarios so though if user don't have access on list he or she can edit the list via sharepoint app. Commented Dec 22, 2017 at 5:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.