Javascript cookie output - javascript

I can't seem to get the cookie output right. I want to type in a player name as a cookie, and get it printed out inside <p id="playerName"></p>. I know this isn't the best option, but its what I am going for atm.
HTML
<form name="myform" action="">
Enter name: <input type="text" name="customer" />
<input type="button" value="Set Cookie" onclick="WriteCookie();" />
<p id="playerName"></p>
</form>
JavaScript
function WriteCookie() {
if (document.myform.customer.value == "") {
alert("Du må taste inn et navn!");
return;
}
cookievalue = escape(document.myform.customer.value) + ";";
document.cookie = "name=" + cookievalue;
document.getElementById("playerName").innerHTML = cookievalue("playerName");
}
Thanks in advance :)

document.getElementById("playerName").innerHTML = cookievalue("playerName");
Use innerHTML to set the stuff in the tag.

Related

Is LocalStorage variable exists: if statement does not work after element reloading (page is reloading after submiting reloaded form)

Please help to fix an algorithm and prevent reloading after clicking submit:
my website has to check, does user ever entered a nickname. If he did, then website have to show his name, if did not, then ask to type it. If the user decided to change it, he will click "reset username".
After clicking "reset" user has to submit twice his name (after first click on "Set" total page is reloading, and after second click it is reloading only one element). Please help to fix it - user has to submit it only once.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var formNewName = '<form id="new-task"> <input id="nickN" autocomplete="off" autofocus placeholder="Write your nick" type="text"> <input id="submitname" type="submit" value="Set new name1"> </form>';
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#setnewname').onsubmit = () => {
var newname;
localStorage.setItem('localN', newname);
document.querySelector('#nickName').innerHTML = formNewName;
// Stop form from submitting
return false;
};
});
// Checking does user entered his name
if ( !localStorage.getItem('localN') || localStorage.getItem('localN')=="undefined" )
{ var nick;
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#nickName').innerHTML = formNewName;
document.querySelector('#new-task').onsubmit = () => {
nick = document.querySelector('#nickN').value;
localStorage.setItem('localN', nick);
document.querySelector('#nickName').innerHTML = "Your nick is: <b>" + localStorage.getItem('localN') + '</b>';
// Stop form from submitting
return false;
};
});
}
else
{
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#nickName').innerHTML = "Your nick is: <b>" + localStorage.getItem('localN') + '</b>';
});
}
</script>
</head>
<body>
<div id = "nickName"></div>
<div id = "newname">
<br>
<form id="setnewname">
<input id="submitreset" type="submit" value="Reset nick name">
</form>
</div>
</body>
Update: event.preventDefault(); and event.stopPropagation(); does not helps to solve the problem.
Sorry for late reply if you are still having it, i couldn't see where you are taking the value from user in your code there's no input field where user can type so i'll add that and then on id submitreset you'll do this:
i work with jquery most so the syntax for that will be
// HTML CODE TO ADD
<input type="text" name="entername" id="entername">
// than in jquery for the submit button you already have
$(document).on("click","#submitreset",function(e){
e.preventDefaults();
var name = $(this).val();
// you can print the value in the div with this id
$("#nickName").html(name);
});
In a Russian language branch of StackOverflow I had received an answer (https://ru.stackoverflow.com/a/901260/291735):
HTML
<div id = "nickName">
<form id="new-task">
<input id="nickN" autocomplete="off" autofocus placeholder="Write your nick" type="text">
<input id="submitname" type="submit" value="Set new name1"> </form>
</div>
<div id = "newname">
<br>
<form id="setnewname">
<input id="submitreset" type="submit" value="Reset nick name">
</form>
</div>
JavaScript
var setName = document.getElementById('submitname');
var reset = document.getElementById('submitreset');
var nickN = document.getElementById('nickN');
document.addEventListener('DOMContentLoaded', () => {
if (localStorage.getItem('localN')!== null){
document.querySelector('#nickName').innerHTML = "Your nick is: <b>" + localStorage.getItem('localN') + '</b>'
}
})
setName.addEventListener('click', function(){
var newName = document.getElementById('nickN').value;
localStorage.setItem('localN', newName);
document.querySelector('#nickName').innerHTML = "Your nick is: <b>" + localStorage.getItem('localN') + '</b>'
})
reset.addEventListener('click', function(){
delete localStorage['localN'];
document.querySelector('#nickName').innerHTML = '<input id="nickN" autocomplete="off" autofocus placeholder="Write your nick" type="text"> <input id="submitname" type="submit" value="Set new name1">'
});

Autofocus on dynamically added textboxes - html/javascript

i am adding the text boxes dynamically to the form.
following is the code:
<html lang="en-US">
<head>
<meta name="referrer" content="origin">
<script>
var counter = 0;
var limit = 50;
function addInput(divName, arrName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
var af = "autofocus"
newdiv.innerHTML = "<input type='text' name='" + arrName + "[]' required autofocus=" + af + ">";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
</script>
</head>
<body>
<form action="part.php" align="center" method="POST">
<div id = "dynamicInputHolder_1">
<b>Emotion </b><input type="text" value="" name="emotion" id="emotion" class="generatedEmotion" readonly>
<input type="hidden" value="" name="uniqueID" id="uniqueID">
<div id="dynamicInput_1">
<textarea rows="5" cols="50" readonly class="floating-box">
John arrived at Sally's house to pick her up. John and Sally were going to a fancy restaurant that evening for a dinner. John was little nervous because he was going to ask Sally to marry him.</textarea>
</div>
<input type="button" value="Add connecting sentences" onClick="addInput('dynamicInput_1', 'myInputs_1');">
</div>
<br>
</form>
</body>
</html>
I am putting in autofocus="autofocus", but it works only for the first dynamic text box, for other it does not work. Any idea how can i achieve this?
See https://stackoverflow.com/a/47207659/5674976 for a detailed reason for autofocus not working; it only works on page load.
Use elementName.focus()
<html lang="en-US">
<head>
<meta name="referrer" content="origin">
<script>
var counter = 0;
var limit = 50;
function addInput(divName, arrName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
var af = "autofocus"
newdiv.innerHTML = "<input id='my-div-"+counter+"' type='text' name='" + arrName + "[]' required autofocus=" + af + ">";
document.getElementById(divName).appendChild(newdiv);
document.getElementById('my-div-'+counter).focus();
counter++;
}
}
</script>
</head>
<body>
<form action="part.php" align="center" method="POST">
<div id = "dynamicInputHolder_1">
<b>Emotion </b><input type="text" value="" name="emotion" id="emotion" class="generatedEmotion" readonly>
<input type="hidden" value="" name="uniqueID" id="uniqueID">
<div id="dynamicInput_1">
<textarea rows="5" cols="50" readonly class="floating-box">
John arrived at Sally's house to pick her up. John and Sally were going to a fancy restaurant that evening for a dinner. John was little nervous because he was going to ask Sally to marry him.</textarea>
</div>
<input type="button" value="Add connecting sentences" onClick="addInput('dynamicInput_1', 'myInputs_1');">
</div>
<br>
</form>
</body>
</html>
from https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
autofocus HTML5 This Boolean attribute lets you specify that a form
control should have input focus when the page loads, unless the
user overrides it (e.g. by typing in a different control). Only one
form element in a document can have the autofocus attribute, which
is a Boolean.
so you can use autofocus to focus on something (good for server side rendering)
and you need to use javascript if you want to change this after the page is laoded.
Edit:
see #George Campbell answer to how to achieve this: https://stackoverflow.com/a/47207691/6126033
Try to use just "<input type='text' name='" + arrName + "[]' autofocus";
And also ...
$(document).on(<event>, <object>, function(event) {console.log("test"});
(old post, already accepted answer, but anyways....)
try this.
var focusDynForms = function() {
var captureAutoFocus = function (form) {
var el_keys = Object.keys(form.elements);
for(var i = 0; i < el_keys.length; i++) {
var el = form.elements[el_keys[i]];
if (["text","password"].indexOf(el.type)>=0){
if (el.autofocus){
el.focus();
return;
}
}
}
};
var forms = document.querySelectorAll("form");
// dynamically created forms need a helping hand to find focus in life...
forms.forEach(captureAutoFocus);
}
Obviously this only addreses text and password inputs, but you can customize for other types.

How to place variables into .html

want to create an output of gathered variables from a script. but can't seem to input the variables in HTML markup in the script.
$(".regclick3").click(function(){
$('.regtarget4').trigger('click');
var data1 = $("[name='f_k_page_title']").val();
var data2 = $("[name='f_extended_user_email']").val();
$(".divoutput").html(data1+ " " + data2);
});
html
<form>
<input type="text" name="f_extended_user_email" />
<input type="text" name="f_k_page_title" />
</form>
<div class="capture_data">Capture</div>
<div class="divoutput"></div>
Is it possible to add class and variables to the script? Can there be if statements, so if var data1 exists then display "X"
Thank you
According to your comment yes you can show HTML only if it exists otherwise something default like so:
function showMe()
{
var theVal = $('#name').val();
if(!theVal)
{
theVal = "Oop's No value entered";
}
$('#theValue').html(theVal);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="name" />
<br/>
The value is :: <span id="theValue"></span>
<br/>
<button onClick="showMe();">Show Me</button>
$(".divoutput").html(data1+ " " data2+);
// Yah! its possible what your missed + symbol in your code use like below https://codepen.io/kalaiselvan/pen/xdoWYy
$(".divoutput").html(data1+ " " + data2);

Send a Javascript array in a mail

I have an HTML form to retrieve some options from checkboxes:
<form action="" method="post" id="menuform" name="menuform">
<fieldset>
<legend>Select a Menu</legend>
<label>
<input type="radio" name="selectedmenu" checked value="menu01" ape-qty='8' ent-qty='1' pes-qty='1' sor-qty='1' car-qty='1' pos-qty='1' data-price='95' />
<span>First Item</span>
</label>
...(more)...
</fieldset>
<fieldset>
<legend id='aperitivosPrompt'>Elegir Aperitivos</legend>
<label>
<input type='checkbox' name='aperitivos' value="1" />
<span>Item 1</span>
</label>
<label>
<input type='checkbox' name='aperitivos' value="2" />
<span>Item 2</span>
</label>
<label>
<input type='checkbox' name='aperitivos' value="3" />
<span>Item 3</span>
</label>
...(more)...
</fieldset>
<fieldset>
<input type="submit" value="Enviar" />
</fieldset>
</form>
Then I send this variables to a JavaScript file and I save all checkboxes options in multiple arrays
var menuform = document.getElementById('menuform'),
radios = document.getElementsByName('selectedmenu'),
aperitivos = document.getElementsByName('aperitivos'),
aperitivosPrompt = document.getElementById('aperitivosPrompt'),
totalPrice = document.getElementById('totalPrice'),
result = document.getElementById('result'),
aperitivosAllowed = 0,
currentSelectionAperitivos = [],
currency = '€';
function handleAperitivos(e) {
var count = getSelectedCountApe();
if (count > aperitivosAllowed) {
resetSelectApe();
} else {
currentSelectionAperitivos = getSelectedValuesApe();
}
}
...(more)...
function getSelectedCountApe() {
var count = 0;
for (var i = 0; i < aperitivos.length; i++) {
if (aperitivos[i].checked) count++;
}
return count;
}
...(more)...
So, how can I send these arrays named currentSelectionAperitivos = [] in an email? I want that after user selects all his options, I receive an email in my inbox with his selected options.
I think that I must connect this form and JS file with a PHP function and send emails from there. Anyway, how can I do this?
-EDITED-
I tried a solution with JSON:
for (var i = 0; i < aperitivos.length; i++) {
var item = {
"valor": i,
"etiqueta": aperitivos[i].value
};
currentSelectionAperitivos.push(item);
}
currentJSON = JSON.stringify({currentSelectionAperitivos:currentSelectionAperitivos});
console.log(currentJSON);
So now I get in browser console all "values" from fields <input> of the HTML form. But not only CHECKED values and anyway, what I need now is to get this JSON.stringify and send it by mail with PHP.
Write a PHP script to send the email, change the form action to post on this script.
Attention: this is untested.
Change your form to:
<form action="mail.php"...>
</form>
Create mail.php like
<?php
ob_start();
var_dump($_POST);
$result = ob_get_clean();
mail ( 'your#email.com' , 'subject' , $result);
?>
Otherwise you could use JSON.stringify and an API to send the E-Mail with JS.
I found a good solution for my needs. I get all 'checked' values and I create an email with theme.
So, HTML form:
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script type='text/javascript' src='http://sisyphus-js.herokuapp.com/assets/application-09059f9f54cc3c3bff98487cf866644b.js'></script>
</head>
<body>
<form action="configurador.php" method="post" id="menuform" name="menuform">
<fieldset>
<legend id='itemPrompt'>Choose Item</legend>
<label>
<input type='checkbox' name='item' value="Value#01" />
<span>Value#01</span>
</label>
(...more...)
<input type="submit" name="submit" value="Send" />
</fieldset>
</form>
</body>
So there I have all my 'checkboxes' with values and names. I made some JavaScript functions but most important one is this one where I retrieve all values and send theme in an email:
function sendMail() {
var mailbody = "My Configurator: \n\n"
+ $('input[name="item"]')
.map(function(id, box){ return (box.checked ? "[x]" : "[_]") + " " + box.value;})
.get()
.join("\n");
var link = "mailto:mail#mail.com"
+ "?cc="
+ "&subject=" + escape("Configurator - Subject")
+ "&body=" + escape(mailbody);
window.location.href = link;
}
$(function(){
$( "#menuform" ).sisyphus();
});
And it's OK with just this. But I'm getting all checkboxes, even not checked ones, in that email. And could be perfect if I don't have to open a client mail, just send that mail from my server automatically.
Any solution for this variation?

Form submit values not recognized in jQuery code

I have this form:
<form name="form" method="post">
<div>
<p>
Problem Name: <input type="text" size="20" name="problem_name"></input>
</p>
<p>
Explain the problem
</p>
<p>
<textarea name="problem_blurb" cols=60 rows=6 ></textarea>
</p>
</div>
<div>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Registration Successfully</span>
<input type="submit" class="button" value="Add Problem"></input>
</div>
<form>
and here is my JS:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" >
$(function()
{
$("input[type=submit]").click(function()
{
var name = $("#problem_name").val();
var problem_blurb = $("#problem_blurb").val();
alert ("name: " + name);
alert ("problem_blurb: " + problem_blurb);
var dataString = 'name='+ name + '&username=' + username + '&password=' + password + '&gender=' + gender;
if(name=='' || username=='' || password=='' || gender=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
I went through the basic jQuery tutorials, but still confused with their syntax. For some reason, these variables show up as undefined:
var name = $("#problem_name").val();
var problem_blurb = $("#problem_blurb").val();
alert ("name: " + name);
alert ("problem_blurb: " + problem_blurb);
Any idea what I am doing wrong?
# refers to id attributes, rather than names.
Use $('input[name="problem_name"]') to refer to the elements.
Add id="problem_name" and id="problem_blurb" respectively. The jQuery '#' selector looks for id attributes.
You can have both id and name attributes. id is the DOM identifier while name is the form input identifier.
The hash-tag selector tells it to look for that ID. In your HTML you only have those tags with a name attribute. Put the same value in the id attribute and you will be all set.
<input id="problem_name" type="text" size="20" name="problem_name"></input>
<textarea id="problem_blurb" name="problem_blurb" cols=60 rows=6 ></textarea>
You would also try ID in your elements, which is the identifier for # in jQuery.
<input type="text" size="20" id="problem_name">
Which also go for your Button.
If you have <input type="button" ... id="bn"> you can replace "input[type=submit]" (which in your case will activate ALL submit buttons on the page) with $("#bn").click(function() { .. });.

Categories

Resources