I'm working on a basic distance converter and clicking the form to submit keeps redirecting to the somephpfile.php (which doesn't exist as this is an exercise) instead of posting the converted number in kilometers (mi > km) to the div "container bottom." Here is what I've got so far, any help would be much appreciated:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Miles to Kilometers Converter</title>
<!--/ /-------- Normalize CSS --------/ /-->
<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css" rel="stylesheet">
<!--/ /-------- Google Fonts --------/ /-->
<link href="https://fonts.googleapis.com/css?family=Oswald|PT+Sans&display=swap" rel="stylesheet">
<!--/ /-------- My Styles --------/ /-->
<link href="styles.css" rel="stylesheet">
</head>
<body>
<h1>Miles to Kilometers Converter</h1>
<div class="container top">
<p>Type in a number of miles and click the button to convert the distance to kilometers.</p>
<form method="post" action="somephpfile.php" id="convert">
<input type="number" name="distance" id="distance" placeholder="distance">
<input type="submit" name="convertdist" value="Convert Distance">
</form>
</div>
<div class="container bottom" id="answer">
<h2 class="invisible">Answer goes here</h2>
</div>
<script>
var miles = parseInt(document.getElementById("distance").value);
var kilometers = (miles * 1.609344);
var answer = document.createElement("P");
answer.innerHTML = `"${miles} miles converts to ${kilometers} kilometers"`;
document.getElementsByName("convertdist").addEventListener("click", function(event){
event.preventDefault();
document.getElementById("answer").appendChild();
});
</script>
</body>
</html>
<form method="post" action="somephpfile.php" id="convert">
<input type="number" name="distance" id="distance" placeholder="distance">
<input type="submit" name="convertdist" value="Convert Distance">
</form>
This form will be submitted when you click on the submit button. Make the form as follows.
<form id="convert"> <!-- Taken out the attributes method and action -->
<input type="number" name="distance" id="distance" placeholder="distance">
<input type="button" name="convertdist" value="Convert Distance" onclick="convert()"> <!-- Changed the button type submit->button -->
</form>
For JavaScript, you have to enclose the JS logic in a function or so, and call it during onclick of the submit button, like:
<script>
function convert(){
var miles = parseInt(document.getElementById("distance").value);
var kilometers = (miles * 1.609344);
var answer = document.createElement("P");
answer.innerHTML = `"${miles} miles converts to ${kilometers} kilometers"`;
document.getElementById("answer").appendChild(answer);
}
</script>
Things you got wrong are:
Conversion + Appending the answer should be callable, meaning it should be a function.
The conversion function should be invoked whenever the button is clicked. So, it should be bound to the onclick event of the convert button.
Any HTML form with a button of type submit will be submitted to the target specified by action attribute no matter what, unless you block that with event.preventDefault() in your JS. You did that, but not where it should have been done.
The following in your code makes no sense from where you have put it.
document.getElementsByName("convertdist").addEventListener("click", function(event){
event.preventDefault();
document.getElementById("answer").appendChild();
});
Put the working version in this fiddle. Find time to check out.
Related
I am new to Javascript (like I really know nothing) and I have to program a Picross game for my school. My teachers gave me an HTML home page for the game and I can't touch it. This page has a form with action pointing on itself but with parameters on the URL. Here is the code :
<!doctype html>
<html>
<head>
<title>Picross editor & player</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="picross.css" type="text/css">
<script src="picross.js"></script>
</head>
<body>
<nav>
<section>
<h2>Create a grid</h2>
<form action="picross.html" method="get">
<input type="hidden" name="edit">
<table>
<tr><td>Lignes :</td><td><input type="number" name="lines" value="10" min="5" max="20"></td></tr>
<tr><td>Colonnes :</td><td><input type="number" name="cols" value="10" min="5" max="20"></td></tr>
</table>
<input type="submit" value="Create !">
</form>
</section>
</nav>
</body>
</html>
My job is to only work on picross.js and I have no idea how to render a blank page (or a grid) if the form has been submitted because when I try to detect the submit, the HTML page renders just after my catch. I also have to do it on the same page, when no parameters are given it's the home page from my teachers but when the form is submitted, the game opens in the same picross.html but with ?lines=x&cols=y or something like this. Here is what I've tried :
window.onload = function() {
var form = document.querySelector("form");
form.onsubmit = submitted.bind(form);
}
function submitted(e) {
console.log("catch");
console.log(e);
}
This writes catch in the console for a tenth of a sencond and then the HTML renders just after. So what I'm looking for is when the form is submitted, the JS code should render a grid (or a blank page, I can work on the grid later) to play the picross game.
Thank for your help
JavaScript is really easy and fun, you can always google anything you want to make and/or learn in javascript/html or any web technology.
As I understood from your question, you want to open a new window when the button is clicked, so to do that you have to first turn off the default behavior of the form, and to do that you can use the parameter e that passed in the event callback submitted.
JavaScript events
e.preventDefault()
This will prevent the page from reloading.
Next, to open a new window, you can use window object.
Window object.
window.open(....)
Full example:
window.onload = function() {
var form = document.querySelector("form");
form.onsubmit = submitted.bind(form);
}
function submitted(e) {
e.preventDefault();
console.log("catch");
var myWindow = window.open("", "Yaay", "width=200,height=100");
myWindow.document.write("<p>Peace begins with a smile</p>");
}
<!doctype html>
<html>
<head>
<title>Picross editor & player</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="picross.css" type="text/css">
<script src="picross.js"></script>
</head>
<body>
<nav>
<section>
<h2>Create a grid</h2>
<form action="picross.html" method="get">
<input type="hidden" name="edit">
<table>
<tr><td>Lignes :</td><td><input type="number" name="lines" value="10" min="5" max="20"></td></tr>
<tr><td>Colonnes :</td><td><input type="number" name="cols" value="10" min="5" max="20"></td></tr>
</table>
<input type="submit" value="Create !">
</form>
</section>
</nav>
</body>
</html>
I hope I explained clearly.
Note: Run code snippet might not work, because popups are not allowed.
i want to make my local static html website password protected with some js, so that when i open my local html file in my pc, it comes with a form to fill up my user id and my own password, which i have saved and when i hit enter that should open my index.html file only when password is correct.
currently my code is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<Form>
<!-- user-id -->
<input type="text">
<!-- user-password -->
<input type="password">
<button onclick="window.open('./index.html')"> Enter
</button>
</Form>
<script>
// pls-help-me-idk-how-to-code-js
</script>
</body>
</html> ``
Its not a proper way to do it. You need a backend for that inorder to properly execute that. But if it just to play around you can have an alert box and just compare their value : if right it displays.
First, you have to add an id or a class to that inputs in order to select them within the script section. Afterward, you can select them and add any value you want.
Such as:
<form>
<!-- user-id -->
<input id="user" type="text" />
<!-- user-password -->
<input id="pass" type="password" />
<button onclick="window.open('./index.html')">Enter</button>
</form>
<script>
document.getElementById("user").value = "UsernameOrId";
document.getElementById("pass").value = "SomePassword";
</script>
In order to compare, you should get the right password from somewhere like a database or some service, but since this is purely for learning purposes you can hardcode it in the script for checking. So, the final solution can be similar to this:
<body>
<form>
<!-- user-id -->
<input id="user" type="text" />
<!-- user-password -->
<input id="pass" type="password" />
<button id="btn">Enter</button>
</form>
<script>
const myPass = "SomePassword";
document.getElementById("user").value = "UsernameOrId"; // predefining the value simulating is saved and by default filled up
document.getElementById("pass").value = myPass; // predefining the value simulating is saved and by default filled up
const btn = document.getElementById("btn"); // getting the button to control its behavior on click event
btn.addEventListener("click", function () {
const passWhenClickingTheBtn = document.getElementById("pass").value;
if (myPass === passWhenClickingTheBtn) { // checking the value entered for pass
window.open("./index.html");
}
});
</script>
Iam appending a form from desktop view and adding it to mobile view (including scripts) using append() . Since Iam appending same class name and ID for form elements., on submitting form., it is identifying the mobile layout form and passing empty value on trying to get value using document.getElementsByClassName('txtbox').value.
As per my requirement., I need to give index to identify each form while appending. like document.getElementsByClassName('txtbox')[0].value. I have done an approach for same. But not getting how to increment index value on appneding. I have created plunker for same. Please let me know what I have missed.
Here is the sample code
$(document).ready(function(){
var data = $(".div1").html();
$(".div2").append(data);
$("form").submit(function(){
console.log(document.getElementsByClassName('txtbox').value);
/*console.log(document.getElementsByClassName('txtbox')[0].value);
console.log(document.getElementsByClassName('txtbox')[1].value) ; */
});
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="div1">
// data to be copied
<form class="search-container" onsubmit="event.preventDefault();window.open(abc/cde/+'?q='+document.getElementsByClassName('txtbox').value),'_self');">
<input type="text" class="txtbox" id="txtbox" placeholder="enter here...">
<input type="submit" name="submit" /></form>
</div>
<div class="div2">
//data to be appended
</div>
</body>
</html>
You may use $(this).find() to select .txtbox inside the form.
$("form").submit(function() {
console.log($(this).find('.txtbox').val());
return false; // for debugging
});
Also, please note that id should be unique in the documnt.
I have passed form object inside function call and used that param to identify current form.
$(document).ready(function(){
var data = $(".div1").html();
$(".div2").append(data);
});
function submitForm(form){
var txtValue = $(form).find('.txtbox').val();
console.log(txtValue);
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="div1">
// data to be copied
<form class="search-container" onsubmit="event.preventDefault();submitForm(this);">
<input type="text" class="txtbox" id="txtbox" placeholder="enter here...">
<input type="submit" name="submit" /></form>
</div>
<div class="div2">
//data to be appended
</div>
</body>
</html>
You can iterate through you class list like so:
var txtboxes = document.getElementsByClassName("txtbox");
for(var i = 0; i < txtboxes.length; i++){
// ... process each element here
$(txtboxes[i]).append(data);
}
I am trying to create a prompt dialog box using alertifyjs that has multiple input boxes. I have managed to create the dialog box to show the multiple boxes but I cant seem to make a reference to the inputs that user provides.
I want to write if statement that carries out action based on user input when they press OK. However, the OK button doesnt seem to be working and also the if-statements don't work as well. I am not sure what I might be doing wrong, can someone please help me.
Below is my code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/alertifyjs#1.11.1/build/css/alertify.min.css"/>
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/alertifyjs#1.11.1/build/css/themes/bootstrap.min.css"/>
<script src="//cdn.jsdelivr.net/npm/alertifyjs#1.11.1/build/alertify.min.js"></script>
</head>
<body>
<div style="display:none;" >
<div id="dlgContent">
<p> Enter Value One </p>
<input class="ajs-input" id="inpOne" type="text" value="Input One Default Value"/>
<p> Enter Value Two </p>
<input class="ajs-input" id="inpTwo" type="text" value="Input two default Value"/>
</div>
</div>
<!-- the script -->
<script>
var dlgContentHTML = $('#dlgContent').html();
$('#dlgContent').html("");
alertify.confirm(dlgContentHTML).set('onok', function(closeevent, value) {
var inpOneVal = $('#inpOne').val();
var inpTwoVal = $('#inpTwo').val();
updateListItems(inpOneVal,inpTwoVal);
if (inpOneVal == "test" && inpTwoVal == "test") {
alertify.success('Successful');
} else {
alertify.error('Wrong')
}
}).set('title',"Update");
</script>
</body>
</html>
Link to JSfiddle: http://jsfiddle.net/1qouxdkc/4/
In your script you call a function named updateListItems(inpOneVal,inpTwoVal);
As that function is not declared anywhere, it errors, so with that temporarily commented out, it works.
Stack snippet
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/alertifyjs#1.11.1/build/css/alertify.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/alertifyjs#1.11.1/build/css/themes/bootstrap.min.css" />
<script src="https://cdn.jsdelivr.net/npm/alertifyjs#1.11.1/build/alertify.min.js"></script>
</head>
<body>
<div style="display:none;">
<div id="dlgContent">
<p> Enter Value One </p>
<input class="ajs-input" id="inpOne" type="text" value="Input One Default Value" />
<p> Enter Value Two </p>
<input class="ajs-input" id="inpTwo" type="text" value="Input two default Value" />
</div>
</div>
<!-- the script -->
<script>
var dlgContentHTML = $('#dlgContent').html();
$('#dlgContent').html("");
alertify.confirm(dlgContentHTML).set('onok', function(closeevent, value) {
var inpOneVal = $('#inpOne').val();
var inpTwoVal = $('#inpTwo').val();
//updateListItems(inpOneVal,inpTwoVal);
if (inpOneVal == "test" && inpTwoVal == "test") {
alertify.success('Successful');
} else {
alertify.error('Wrong')
}
}).set('title', "Update");
</script>
</body>
</html>
So just code for fun, but I am stuck here. Basically I want to make a HTML app (don't worry about this part) and I want to change JSON content (that is in another file) to be the value of the <input>.
<head>
<meta charset="UTF-8">
<title>PassMan</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
var User = document.getElementById('1');
var Pass = document.getElementById('2');
var Acc = document.getElementById('3');
</script>
</head>
<body>
<form>
<button type="button" onclick="newPass()">Add pass</button>
<input id="1" name="" value="Username">
<input id="2" type="text" value="Pass">
<input id="3" value="Social account">
</form>
</body>
I want this - When the button is pressed, tha value of the three inputs go to JSON file as a new object.