简体   繁体   English

如何通过JS从HTML文本区域获取日期值

[英]How to get the date value from html textarea via JS

So I have this function that creates a number of textareas depending on what month it is. 因此,我具有此功能,该功能根据是哪个月份来创建许多textareas

For example: 例如:

  • If it's 'February', then 28 'textareas' are created. 如果是“ 2月”,那么将创建28个“ textareas”。
  • If it's 'March', then 31 'textareas' are created and so on. 如果是“ 3月”,则将创建31个“ textareas”,依此类推。

When the user clicks on the 'textareas' and then the forms button, the value of the textareas inserts into the MySQL database. 当用户单击“ textareas”,然后单击“表单”按钮时,textareas的值将插入到MySQL数据库中。

My problem right now is that the value that goes into the database is not the value of the textareas, eg 2018-02-19 , it is always 2018-02-28 . 我现在的问题是进入数据库的值不是textareas的值,例如2018-02-19 ,始终是2018-02-28

Functions: 职能:

function daysInMonth(month, year) {
    var days;
    switch (month) {
        case 1: // Feb, our problem child
            var leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
            days = leapYear ? 29 : 28;
            break;
        case 3:
        case 5:
        case 8:
        case 10:
            days = 30;
            break;
        default:
            days = 31;
    }
    return days;
}

var showDate = new Date();
var months = ["January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
];
var weeks = ["Sunday", "Monday", "Tuseday", "Wednesday", "Thursday", "Friday", "Saturday"];

function drawTable(forDate) {
    var daysInMonth = new Date(forDate.getFullYear(), forDate.getMonth() + 1, 0).getDate();
    var cellsToDraw = daysInMonth;
    var newdate = forDate.getFullYear() + "-" + ("0" + (forDate.getMonth() + 1)).slice(-2);
    var table = document.getElementById("table");
    table.innerHTML = "";
    for (var r = 0; r < (daysInMonth / 7); r++) {
        var newRow = document.createElement("tr");
        table.appendChild(newRow);
        for (var c = 0; c < 31 && cellsToDraw > 0; c++) {
            var day1 = ("0" + (c + 1)).slice(-2);
            var textarea = document.createElement("textarea");
            textarea.setAttribute("type", "button");
            textarea.setAttribute("name", "day");
            textarea.setAttribute("value", newdate + "-" + day1);
            textarea.setAttribute("placeholder", day1);
            newRow.appendChild(textarea);
            textarea.setAttribute("name", "day");
            textarea.setAttribute("day", newdate + "-" + day1)
            textarea.innerHTML = newdate + "-" + day1;
            cellsToDraw--;
        }
    }
}

window.onload = function() {
    document.getElementById("displayingMonth").innerHTML = months[showDate.getMonth()];
    drawTable(showDate);
};

html: 的HTML:

<form class="" action="insert.php" method="post">
    <table id="table">
        <input id="day"type="hidden" name="day" value="">
        <input id="btn"  type="submit" name="" value="Press">
</form>

php 的PHP

$day = mysqli_real_escape_string($conn, $_request['day']);
for ($i = 1; $i < count($day); $i++) {
    $stmt = "INSERT INTO calendar (day) VALUES('$day[$i])')";
    if (empty($day)) {
        $_SESSION['error'] = "Error";

        header('Location: insert.php', true, 303);
        exit();
    } else {
        if (mysqli_query($conn, $stmt)) {
            header('Location: insert.php', true, 303);
            exit;
        } else {
            $error= "Error: " .mysqli_error($conn);
            echo "$error";

        }
    }
}

This is because the data sent to insert.php looks like this(check using network tab) 这是因为发送到insert.php的数据看起来像这样(使用“网络”标签检查)

day=2018-02-01&day=2018-02-02&day=2018-02-03&day=2018-02-04&day=2018-02-05&day=2018-02-06&day=2018-02-07&day=2018-02-08&day=2018-02-09&day=2018-02-10&day=2018-02-11&day=2018-02-12&day=2018-02-13&day=2018-02-14&day=2018-02-15&day=2018-02-16&day=2018-02-17&day=2018-02-18&day=2018-02-19&day=2018-02-20&day=2018-02-21&day=2018-02-22&day=2018-02-23&day=2018-02-24&day=2018-02-25&day=2018-02-26&day=2018-02-27&day=2018-02-28

It seems it is taking the last value because of same key name. 由于键名相同,似乎正在取最后一个值。

Instead of directly submitting the form,submit it using ajax and send the data in an array or as an object 与其直接提交表单,不如使用ajax提交表单并以数组或对象形式发送数据

In this case your date fields should be named as an array. 在这种情况下,您的日期字段应命名为数组。 If you name multiple fields as day , it will act as single field take the last field value with the same name. 如果将多个字段命名为day ,它将作为单个字段使用具有相同名称的最后一个字段值。 So you have to change in one line and it will work nicely. 因此,您只需要更改一行,它就可以很好地工作。

 textarea.setAttribute("name", "day[]");

JavaScript 的JavaScript

Right, lets first start with the JavaScript. 正确,首先让我们开始使用JavaScript。

function drawTable(forDate) {
    // Days in a month
    const daysInMonth = new Date(
        forDate.getFullYear(),
        forDate.getMonth() + 1,
        0
    ).getDate();
    // 28

    // Start of a date
    const date = [
        forDate.getFullYear(),
        (forDate.getMonth() + 1 + '').padStart(2, 0)
    ]
    .join('-');
    // 2018-02

    // Reset the table
    const table = document.getElementById("table");
    table.innerHTML = "";

    // For each day of the month
    // Start at one, go until day > daysInMonth. e.g. (1 -> 28)
    for (let day = 1; day <= daysInMonth; day++) {
        const dateString = date + '-' + (day + '').padStart(2, 0);

        // Create the elements.
        const row = document.createElement("tr");
        const cell = document.createElement("td");
        const textarea = document.createElement("textarea");

        textarea.setAttribute("name", "day[]");
        textarea.setAttribute("value", dateString);
        textarea.innerHTML = dateString;
        textarea.setAttribute("placeholder", day);

        // These do nothing.
        // textarea.setAttribute("type", "button");
        // textarea.setAttribute("day", dateString)

        // Stack the children into the table.
        cell.appendChild(textarea);
        row.appendChild(cell);
        table.appendChild(row);
    }

    return table;
}

PHP 的PHP

Now, lets move on to the PHP. 现在,让我们继续使用PHP。 I'm going to first look at the problems in your code. 我将首先查看您的代码中的问题。

// Currently 'day' is an array.
// So this will throw an error.
$day = mysqli_real_escape_string($conn, $_request['day']);

// For every '$day[$i]' in '$day'
for ($i = 1; $i < count($day); $i++) {
    // $day is still an array.
    if (empty($day)) {
        $_SESSION['error'] = "Error";

        // The problem that you'll face here is that
        // one empty day fails the rest of the days
        header('Location: insert.php', true, 303);
        exit();
    } else {
        if (mysqli_query($conn, "INSERT INTO calendar (day) VALUES('$day[$i])')")) {
            // Here this will stop on the first '$day[$i]'
            header('Location: insert.php', true, 303);
            exit;
        } else {
            $error= "Error: " .mysqli_error($conn);
            echo "$error";
        }
    }
}

Now, I'm going to look at a possible solution. 现在,我将探讨一个可能的解决方案。

// Currently 'day' is an array.
$days = $_request['day'];

// This is how we can carry our errors.
$error = array();

// For every 'day' in the 'days' array.
if (is_array($days))
foreach ($days as $day) {
    // Escape the day.
    $day = mysqli_real_escape_string($conn, $day);

    // Now this will work as expected.
    if (empty($day)) {
        // We shall use the $error array.
        $error[] = array(
            'day' => $day,
            'error' => 'day was empty'
        );
    }

    // Else if there is an error in the SQL query.
    else if (
        !mysqli_query(
            $conn,
            // You see how the '$day' variable is used
            "INSERT INTO calendar (day) VALUES('$day)')"
        )
    ) {
        // We shall use the $error array again here.
        $error[] = array(
            'day' => $day,
            'error' => mysqli_error($conn)
        );
    }
}

// If there was an error.
if (count($error)) {
    // Print the errors.
    print_r($error);
}

// Do your redirect.
header('Location: insert.php', true, 303);

HTML 的HTML

Finally, let's look at the HTML. 最后,让我们看一下HTML。 I'm going to first look at the problems in your code. 我将首先查看您的代码中的问题。

<!-- You do not need to define the blank 'class' -->
<form class="" action="insert.php" method="post">
    <!-- You should close the <table> tag. -->
    <table id="table">

    <!-- This is currently unneeded and could hinder the php. -->
    <input id="day"type="hidden" name="day" value="">

    <!-- You do not need to define the blank 'name' -->
    <input id="btn" type="submit" name="" value="Press">
</form>

Now, I'm going to look at a possible solution. 现在,我将探讨一个可能的解决方案。

<form action="insert.php" method="post">
    <table id="table"></table>
    <input id="btn" type="submit" value="Press" />
</form>

*Note: * I have not tried this code. *注意:*我没有尝试过此代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM