return a json from my html page - html

I have created a HTML code to build an user form that will contain information that people write inside the texts. This page also has a button that should take all the entered information and convert it into a json file.
I have never done this before, so I have no idea how I can do that. As far as I read, I understand that I need a local server to send the html code to it so it can return the json, but the process to do this is absolutely unclear for me.
My code in html is this:
<!DOCTYPE html>
<html>
<header>
<h1>My Promo</h1>
<h2>Get insights out of an endless see of data...</h2>
<link rel="stylesheet" href="mycss.css">
</header>
<form action="http://localhost/" method="post">
<!-- Input label -->
<div class="formgroup" id="name-form">
<label for="name">What is your banner?*</label>
<input type="text" name="banner" />
</div>
<!-- Input label -->
<div class="formgroup" id="name-form">
<label for="name">Name of current promo*</label>
<p>(write a short name, e.g: "DPE17")</p>
<input type="text" name="CurrentPromo" />
</div>
<div class="submit">
<input type="submit" value="Get my data" />
</div>
</form>
</html>
Then, when I click on the button "Get my data" it does nothing.
Can you give me the process to capture the json from this?
Many thanks!

As you did not mention any specific JSON structure I think below code will work for you. You will have to customize based on your needs.
I will recommend you to find and check different javascript libraries and see what suits you best for your client side application.(jQuery is easiest to learn)
Also check if it is a REST server. Based on that decide on your client side javascript framework. (Angular is good choice for REST based applications)
function onSubmitForm( myForm ){
var formjson = JSON.stringify( $(myForm).serializeArray() ); // <-----------
console.log( formjson );
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<header>
<h1>My Promo</h1>
<h2>Get insights out of an endless see of data...</h2>
<link rel="stylesheet" href="mycss.css">
</header>
<form action="http://localhost/" method="post" class="myform" onsubmit='return onSubmitForm(this)'>
<!-- Input label -->
<div class="formgroup" id="name-form">
<label for="name">What is your banner?*</label>
<input type="text" name="banner" />
</div>
<!-- Input label -->
<div class="formgroup" id="name-form">
<label for="name">Name of current promo*</label>
<p>(write a short name, e.g: "DPE17")</p>
<input type="text" name="CurrentPromo" />
</div>
<div class="submit">
<input type="submit" value="Get my data" />
</div>
</form>
</html>

Related

Saving the value of a checkbox in an array when clicked (jQuery)

I'm trying to make a joke generator. The user can choose between Programming, Miscellaneous and Dark jokes (or two / all of them but cannot choose none). Right now, for my Javascript and HTML, I have this:
$("#first-input").val("Programming");
$("#middle-input").val("Miscellaneous");
$("#bottom-input").val("Dark");
let checkboxes = $(".content-top input[type=checkbox]");
let submitButton = $("button[type=submit]");
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Joke</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<form action="/joke" method="POST">
<div class="section">
<label><span>*</span> Select a category / categories:</label>
<div class="content content-top">
<input type="checkbox" name="category" id="first-input">
<h5>Programming</h5>
<br>
<input type="checkbox" name="category" id="middle-input">
<h5>Miscellaneous</h5>
<br>
<input type="checkbox" name="category" id="bottom-input">
<h5>Dark Jokes</h5>
</div>
</div>
<button type="submit">Generate Joke</button>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
The HTML I have right now are three checkboxes with the same name attribute, but with different values set (values were set in Javascript above). How do I use jQuery to make it so that once the submit button is clicked, there is an array, and the items in the array are the ones the user checked?
So for example:
If the user selects the "Programming", "Miscellaneous" and "Dark" check boxes, the array would have the 3 items (the three items would be "Programming", "Miscellaneous" and "Dark"). Then if the user proceeds to uncheck the "Dark" checkbox (so now only the "Programming" and "Miscellaneous" checkboxes are checked), the array would also remove the "Dark" item and would now only have 2 items.
I've been trying a lot of things and searching on Google, and tried using "input:checked", is(), etc. but I couldn't figure out how to get it to work.
Question:
How do I get an array, and the items in the array are the values of the checkboxes the user checked (e.g. "Programming", "Dark", etc.) with no repeats, and if the user, for example, initially selected all three checkboxes, and then proceeds to uncheck the "Dark" checkbox, the array should also remove "Dark" as one of it's items.
I've been stuck on this for hours and would really appreciate any help, thanks!
First, change your checkboxes to declare their values in the HTML:
<input type="checkbox" name="category" id="first-input" value="programming">
<h5>Programming</h5>
<br>
<input type="checkbox" name="category" id="middle-input" value="miscellaneous">
<h5>Miscellaneous</h5>
<br>
<input type="checkbox" name="category" id="bottom-input" value="dark">
<h5>Dark Jokes</h5>
Add the following onclick attribute to your submit button:
<button type="submit" onclick="submit(event)">Generate Joke</button>
Then add the following script tag after your inclusion of jQuery:
<script type="text/javascript">
window.submit = event => {
event.preventDefault();
let checkedValues = Array.from($('input:checked')).map(input => input.value);
// ... looks like, e.g., ["programming", "miscellaneous"]
// ... do stuff with checkedValues here...
console.log(checkedValues);
};
</script>
I added the event.preventDefault() thing so that the form doesn't actually send anything to the server. It seems like you'll need that if you want to do things in JS first.
The whole thing should look like this:
<form id="form" action="/joke" method="POST">
<div class="section">
<label><span>*</span> Select a category / categories:</label>
<div class="content content-top">
<input type="checkbox" name="category" id="first-input" value="programming">
<h5>Programming</h5>
<br>
<input type="checkbox" name="category" id="middle-input" value="miscellaneous">
<h5>Miscellaneous</h5>
<br>
<input type="checkbox" name="category" id="bottom-input" value="dark">
<h5>Dark Jokes</h5>
</div>
</div>
<button type="submit" onclick="submit(event)">Generate Joke</button>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
window.submit = event => {
event.preventDefault();
let checkedValues = Array.from($('input:checked')).map(input => input.value);
// ... looks like, e.g., ["programming", "miscellaneous"]
// ... do stuff with checkedValues here...
console.log(checkedValues);
};
</script>
I don't think you need those few lines of JS at the top of your question.
Add the value attribute to your inputs then get all checkboxes iterate through them then push the values to the array, the elements in the array will be removed each time you click submit which means you will always get the new values checked by the user pushed to the result array
results = []
let submitButton = $("button[type=submit]");
submitButton.click(function(e) {
var $checkboxes = $('input[name=category]:checked');
e.preventDefault()
results.splice(0,results.length)
$checkboxes.each(function(){
results.push($(this).val())
});
console.log(results)
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Joke</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<form action="/joke" method="POST">
<div class="section">
<label><span>*</span> Select a category / categories:</label>
<div class="content content-top" id="checkb">
<input type="checkbox" name="category" id="first-input" value="Programming">
<h5>Programming</h5>
<br>
<input type="checkbox" name="category" id="middle-input" value="Miscellaneous">
<h5>Miscellaneous</h5>
<br>
<input type="checkbox" name="category" id="bottom-input" value="Dark Jokes">
<h5>Dark Jokes</h5>
</div>
</div>
<button type="submit">Generate Joke</button>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
I don't do jQuery for years, but if you want to sent an array you have to ending element's names with [] and set a value for each.
here it is in javascript
const DomParser = new DOMParser()
, myForm = document.getElementById('my-form')
;
function newCategory(val)
{
let elm = `<input type="hidden" name="category[]" value="${val}">`
return DomParser.parseFromString( elm, 'text/html').body.firstChild
}
myForm.oninput=()=>
{
while (el=myForm.querySelector('input[name="category[]"]')) el.remove();
myForm.querySelectorAll('input[data-category]:checked').forEach(el=>
{
myForm.appendChild( newCategory( el.dataset.category ) )
})
}
label, button {
display: block;
float: left;
clear: both;
}
button { margin-top: 1em;}
<form id="my-form" action="/joke" method="POST">
<label>
<input type="checkbox" data-category="Programming">
Programming
</label>
<label>
<input type="checkbox" data-category="Miscellaneous">
Miscellaneous
</label>
<label>
<input type="checkbox" data-category="Dark Jokes">
Dark Jokes
</label>
<button type="submit">Generate Joke</button>
</form>

Calculation result not displaying after user input HTML

I'm completing an assignment in HTML where we're supposed to create a page that uses at least one function to perform a mathematical calculation based on user input. I've got the code written below, but when I hit the "calculate" button I've coded in, nothing displays on the screen. Could someone tell me what I'm doing wrong? Here is my code:
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<Title>Goals Against Average Calculator</Title>
<body>
<script src="modernizr.custom.05819.js"></script><!--Links to file containing modernizer library-->
<!-- Navigation -->
<nav>
<ul class="w3-navbar w3-black">
<li>Home</li> <!--Link to Home Page-->
<li>NHL Teams</li><!--Link to Page of NHL Teams-->
<li>AHL Teams</li><!--Link to Page of AHL Teams-->
<li>WHL Teams</li><!--Link to Page of WHL Teams-->
<li>G.A.A. Calculator</li><!--Link to Page of WHL Teams-->
</ul>
</nav>
<header>
<h1 style="text-align:center;">Goals Against Average Calculator</h1><!--Title of Page-->
</header>
<article>
<form>
<fieldset>
<label for="GoalsAllowed">
Enter Number of Goals Allowed
</label>
<input type="Goals" id="GoalsAllowed" /><!--Input for Goals Allowed-->
</fieldset>
<fieldset>
<label for="MinutesPlayed">
Enter Minutes Played
</label>
<input type="MinPlayed" id="MPlayed" /><!--Input for Minutes Played-->
</fieldset>
<fieldset>
<label for="GameLength">
Regulation Game Length
</label>
<input type="Minutes" id="MinGame" /><!--Input for Length of Regulation Game-->
</fieldset>
<fieldset>
<button type="button" id="button">Calculate</button><!--Calculation Button-->
</fieldset>
<fieldset>
<p>Goals Against Average</p>
<p id="GAA"> </p>
</fieldset>
</form>
</article>
<script>
function convert() {
var Goals = document.getElementById("GoalsAllowed").value;
var Minutes = document.getElementById("MinutesPlayed").value;
var GameLength = document.getElementById("GameLength").value;
var GAA = (Goals * GameLength) / Minutes;
document.getElementById("GAA").innerHTML = GAA;
}
document.getElementById("button").
addEventListener("click", convert, false);
</script>
</body>
</html>
You do not have inputs with IDs MinutesPlayed and GameLength. There is an error that you cannot access property value of null.
Your JavaScript code should look as follow:
function convert() {
var Goals = document.getElementById("GoalsAllowed").value;
var Minutes = document.getElementById("MPlayed").value;
var GameLength = document.getElementById("MinGame").value;
var GAA = (Goals * GameLength) / Minutes;
document.getElementById("GAA").innerHTML = GAA;
}
you can have another alternative here using jQuery
you can include it locally by downloading the file or use google CDN as shown below
<!DOCTYPE html>
<html>
<head>
<title>Enjoy</title>
</head>
<body>
<article>
<form>
<fieldset>
<label for="GoalsAllowed">
Enter Number of Goals Allowed
</label>
<input type="Goals" id="GoalsAllowed" /><!--Input for Goals Allowed-->
</fieldset>
<fieldset>
<label for="MinutesPlayed">
Enter Minutes Played
</label>
<input type="MinPlayed" id="MPlayed" /><!--Input for Minutes Played-->
</fieldset>
<fieldset>
<label for="GameLength">
Regulation Game Length
</label>
<input type="Minutes" id="MinGame" /><!--Input for Length of Regulation Game-->
</fieldset>
<fieldset>
<button type="button" id="button">Calculate</button><!--Calculation Button-->
</fieldset>
<fieldset>
<p>Goals Against Average</p>
<h1 id="GAA"> </h1>
</fieldset>
</form>
</article>
<!--
include a jquery file am using jquery-2.1.1.min.js
you can find a later version
-->
<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
var number_of_goals, minutes_played, regulation_game_length, GAA = ""; //initialize all the variables that we are going to use
$(document).on('click','#button', function(e){ //this is to check if the button with id button has been clicked
e.preventDefault(); //here you prevent its default action so that it does not refresh the page
number_of_goals = $('#GoalsAllowed').val(); //get the value entered for the number of goals
minutes_played = $('#MPlayed').val(); //get the value entered for the minutes played
regulation_game_length = $('#MinGame').val(); //capture the regulation game length
GAA = (number_of_goals * regulation_game_length) / minutes_played; //compute using your formular based on the values you have captured
$('#GAA').html(GAA); //print the result in your h1 tag that has id GAA
});
</script>
</body>
</html>

[HTML]how to upload values in the <fieldset> element if the <fieldset> tag is outside of the <form> tag

Here is the HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Javascript</title>
</head>
<body>
<form action="/check" id="demo" method="post" name="demo">
<input type="text" name="username" />username
<button type="button"
onclick="form.change_color.style.backgroundColor='#00FF00';">change
fieldset background</button>
<button type="button"
onclick="activateFieldset()">activate fieldset</button>
<input type="submit" value="submit" />
</form>
<fieldset form="demo" name="change_color">
<input type="password" name="password" />password
</fieldset>
<fieldset form="demo" disabled="disabled" name="license" id="license">
<input type="text" name="license_id" />license_id
</fieldset>
<script>
function activateFieldset(){
var e = document.getElementById("license");
e.disabled = "";
}
</script>
</body>
</html>
I fill in a, b and c into the username, change_color and license_id text box, but the browser only upload the data in username.
I tried Chrome/Opera/Firefox, they all worked like that.
Can anyone tell me why the browser doesn't upload the data in the element?
Thanks a lot!
Unlike some commenters state, it is very possible to have reassociateable elements out of a form, trough the use of an explicit FORM attribute, according to HTML5 RFC (though I agree that it is nicer to have them all grouped within the form).
And in your case, though you have specified well the form attribute in the fieldset, it happens that the elements which must have the form attribute are the INPUT ones.

How to trigger my input type=button with enter?

I'm using this form I found :
<FORM METHOD="POST" ENCTYPE="x-www-form-urlencoded">
<input type="text" id="Password"/>
<input type="button" id="Access" onclick="document.location=Password.value" VALUE="Accès"/>
</FORM>
It works fine for what I want to do, but I would like to allow the command to be triggered by pressing enter too. I have read a solution using the submit type instead and also a solution adding
onkeydown="if (event.keyCode == 13) document.getElementById('Access').click()" in the text input.
Neither works so I don't know if I'm misusing them or if my document.location=Password.value cannot be used this way. If so, could you indicate me the simplest solution to replace it without using php or js file because I don't really understand that. This website will not be public so I don't really care about security or if it's not the right way to do.
EDIT : Considering the answer you gave me are not fully working (jlbruno's one does not work neither on enter or on click, riad's one only works on click), here is the full code of my page with riad's solution, please tell me if something could interfere
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">
<head>
<title>JVPW Cloud - Le Nuage de la JVPW !</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" media="screen" type="text/css" title="Design" href="design.css" />
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
</head>
<body>
<p><center><img src="logo.png" width="1000" height="400" /></center></p>
<p><span style="font-family:Verdana"><b>Tout l'univers de la JVPW pour seulement 9.99 $</b></span></p>
<h1>Bienvenue</h1>
<p>Si vous disposez d'un early access gratuit, entrez le code ci-dessous et appuyez sur Accès (pas Entrée !)</p>
<FORM METHOD="POST" ENCTYPE="x-www-form-urlencoded">
<input type="text" id="Password" onkeydown="if (event.keyCode == 13) document.getElementById('Access').click()" />
<input type="button" id="Access" onclick="window.location=document.getElementById('Password').value ;" VALUE="Accès"/>
</FORM>
</body>
</html>
I wouldn't recommend having inline event handlers, but that said I'll keep doing it for an example.
You should change your button to a submit button, and move your current onclick into an onsubmit on the form.
<FORM METHOD="POST" ENCTYPE="x-www-form-urlencoded" onsubmit="document.location=Password.value">
<input type="text" id="Password"/>
<input type="submit" id="Access" VALUE="Accès"/>
</FORM>
You can try this.
<FORM METHOD="POST" ENCTYPE="x-www-form-urlencoded">
<input type="text" id="Password" onkeydown="if (event.keyCode == 13) document.getElementById('Access').click()" />
<input type="button" id="Access" onclick="doSubmitWork();" VALUE="Accès"/>
</FORM>
<script type="text/javascript">
function doSubmitWork(){
window.location = 'mywebsite.com/'+document.getElementById('Password').value ;
}
</script>
JS FIDDLE DEMO
I did the following and it works for me. I hope is helps you.
<form name="frm" method="post">
<input type="password" name="psw">
<input type="submit" value="Enter">
</form>

I have a need to perform two actions on a simple input form? I have read and tried all previous answers on this subject with no success

The following code shows how I am trying to first write info to .txt file and then have the custom search performed. If I remark out the action in Button2, Button1 works fine and writes text to .txt. When I open Button2 to do search, it appears that the .php in Button1 is ignored and Button2 presents custom search, however, there is write to .txt file. I have tried everything I can find, including all in one .php file, but the second action seems to take control and won't allow the first action to run.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>If NOT found to right ENTER Your</title>
<script language="Javascript">
<!--
function OnButton1()
{
// Action used to write to .txt file only
document.Form1.action = "open-close.php";
}
function OnButton2()
{
// Action performs custom google search
document.Form1.action = "http://www.google.com";
}
-->
</script>
</head>
<body>
<h3><span style="color: #00ff00;">If NOT found to right ENTER Your Topic Here! </span></h3>
<style type="text/css">
#import url(http://www.google.com/cse/api/branding.css);
</style>
<div class="cse-branding-right" style="background-color:#999999;color:#000000">
<div class="cse-branding-form">
<form id="cse-search-box" target="_blank" name="Form1">
<div>
<input type="hidden" name="cx" value="" />
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" name="q" size="55" />
<input type="submit" name="sa" value="Search" Onclick="OnButton1(); OnButton2();"/>
</div>
</form>
</div>
<div class="cse-branding-logo">
<img src="http://www.google.com/images/poweredby_transparent/poweredby_999999.gif" alt="Google" />
</div>
<div class="cse-branding-text">
Your Custom Search
</div>
</div>
</body>
</html>
Call OnButton1() on button click and from within the function onButton1() call onButton2():
<input type="submit" name="sa" value="Search" Onclick="OnButton1();"/>
function OnButton1()
{
// Action used to write to .txt file only
document.Form1.action = "open-close.php";
OnButton2();
}