HW8-1

by sunnyhong

HTML

<div>
        User ID: <input type="text" name="userid" id="userid"><h7 id="idcontent"></h7><br>
        Title: <input type="text" id="title"><h7 id="titlecontent"></h7><br>
        Body:<br><textarea cols="20" rows="5" id="body"></textarea><br>
        <button onclick="myFunction()">Submit</button>
    </div>
    <div id="content"></div>

JavaScript

$(document).ready(readyFunc);

function readyFunc() {
    fetch('https://jsonplaceholder.typicode.com/posts/', {
    method: 'POST',
    body: JSON.stringify({
      title: $("#title").val(),
      body: $("#body").val(),
      userId: $("#id").val()
    }),
    headers: {
      "Content-type": "application/json; charset=UTF-8"
    }
  })
  .then(response => response.json())
  .then(json => console.log(json))
}

function myFunction(){
    $('#idcontent').empty();
    $('#titlecontent').empty();
    if(!$("#userid").val()){
        $('#idcontent').append("required field");
        if(!$("#title").val()){$('#titlecontent').append("required field");}
    }
    else{
        if(!$("#title").val()){$('#titlecontent').append("required field");}
        else{
            $('#content').append(
                `<h3>User ID:`+$("#userid").val()+`<br>Title:`+$("#title").val()+`<br>Body:`+$("#body").val()+`</h3>`
            );
        }
    }
    $("#userid").val("");
    $("#title").val("");
    $("#body").val("");
}