简体   繁体   中英

Javascript onclick prompt save value

First of all I am displaying some text on my page for the user using php If the cookie id name is not found it will display the text whats your name.

<?php
if (isset($_COOKIE['name'])) {
    echo $_COOKIE["name"];
}
else {
    echo "<a href='' onclick='setcookie()'>Whats your name</a>";
}
?>

Onclick i get the alert/prompt for the user to input their name.

Next i want to create a cookie, the id of the cookie is name and the value will be their name that was input into the alert/prompt. I have been searching all day for away to do this but most explanations use a form input which i don't want.

<script type="text/javascript">

    function setcookie(name, value, expires) {
        var name=prompt("Please enter your name");        
    }       

</script>

Hopefully then if the cookie id name is found by php it will display the users name.

If you're looking to set a cookie with JavaScript, there's some docs for that .

For example, to set a cookie name :

document.cookie = 'name=' + name + '; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/';

To create a cookie you can do the following

function setcookie() {
    var name = prompt("Please enter your name");
    document.cookie = "name=" + name + "; expires=Thu, 18 Dec 2014 12:00:00 GMT";
}

Like they said in the comments you have 3 parameters in your function which you don't send values for, I removed these value for this. If you need them to be passed from somewhere make sure you do so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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