I am developing an app in Django. In my forms it is possible to have dependent fields. I would like to use this plugin. However, field dependencies may vary depending on the user's choices.
The fields in my forms look more or less like this:
<input type="text" name="name1" data-dependency="id_name2" class="textinput textInput form-control" id="id_name1">
The data-dependency attribute indicates which fields this field depends on. So in this case the name1 field will somehow depend on the name2 field.
I wrote this sample script to dynamically add dependencies:
$('document').ready(function(){
var name = document.getElementById("id_name1");
var data_dependency = name.getAttribute('data-dependency');
var dependencies = data_dependency.split(";")
var i =0;
for(i=0; i<dependencies.length; i++){
var d = dependencies[i];
var elem = document.getElementById(d);
$(name).dependsOn({
'#id_name2' : {
values: ['yes']
}
});
}
});
At this point, I have a fixed id #id_name2 on which depends field name1 . Is there any way to pass on any element taken from the dependencies?
A simple working example (you only need to download two scripts):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="dependsOn.min.js"></script>
<script>
$('document').ready(function(){
var element = document.getElementById("myText2");
var data_dependency = element.getAttribute('data-dependency');
var dependencies = data_dependency.split(";")
var i =0;
for(i=0; i<dependencies.length; i++){
var d = dependencies[i];
var tmp = document.getElementById(d);
$(element).dependsOn({
'#myText1' : {
values: ['yes']
}
});
}
});
</script>
</head>
<body>
<form id="myForm">
<label for="myText1">Type yes</label>
<input type="type" id="myText1">
<label for="myText2">Input</label>
<input type="text" id="myText2" value="" data-dependency="myText1">
</form>
</body>
</html>
The key to solving the problem was to know that dependsOn accepts the dictionary as an argument.
It is enough to create a suitable dictionary and pass it on as an argument.
So the solution is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="dependsOn.min.js"></script>
<script>
function get_id(element) {
return '#' + element.id;
};
$('document').ready(function(){
var element = document.getElementById("myText2");
var data_dependency = element.getAttribute('data-dependency');
var dependencies = data_dependency.split(";")
var i =0;
for(i=0; i<dependencies.length; i++){
var d = dependencies[i];
var tmp = document.getElementById(d);
var data = {}
data[get_id(tmp)] = {values: ['yes'] }
$(element).dependsOn(data);
}
});
</script>
</head>
<body>
<form id="myForm">
<label for="myText1">Type yes</label>
<input type="type" id="myText1">
<label for="myText2">Input</label>
<input type="text" id="myText2" value="" data-dependency="myText1">
</form>
</body>
Related
I have the following code below:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="OrderUp.css">
<title>OrderUp</title>
</head>
<body>
<form onsubmit="return results();" method="post" action="results.html" >
Name : <input name = "name" type= "text" id="name">
<br>
<input value = "Submit" type = "submit" >
</form>
</body>
</html>
Another HTML page:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="OrderUp.css">
<title>Results</title>
</head>
<body>
<h2> Your Form Has Been Submitted </h2>
<script type="text/javascript">
function results() {
var name = document.getElementbyId('name').value;
document.write(name);
}
</script>
</body>
</html>
I am trying to pass on the value 'name' and retrieve it on a different html page (results.html). How do I accomplish this? I am not sure what I am doing wrong. Please help. Thank you!
pass the variable in the url using GET like :
<form method="get" action="result.html" >
Name : <input name = "name" type= "text" id="name">
<br>
<input value = "Submit" type = "submit" >
</form>
and retrieve it in the other page like :
<h2> Your Form Has Been Submitted </h2>
<script>
let params = (new URL(document.location)).searchParams;
let name = params.get("name");
console.log(name) // this is your variable
document.querySelector('h2').innerText += name;
</script>
One way is: you could use the 'get' method on the form, and not 'post':
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>OrderUp</title>
</head>
<body>
<!-- Use method 'GET', not 'POST', to pass the form values via the url in the address bar -->
<form method="GET" action="results.html">
Name :
<input name="name" type="text">
<br>
<input value="Submit" type="submit">
</form>
</body>
</html>
Then, in result.html, use javascript to extract the name value from the page url.
result.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Results</title>
</head>
<body>
<h2> Your Form Has Been Submitted </h2>
<span>Name Submitted: </span>
<span id="name-label"></span>
<script type="text/javascript">
// Get the value passed in the url by the form
var querystring = location.search;
// => ?name=Roger
// Remove the '?' at the beginning
var nameValuePair = querystring.replace(/^\?/, '');
// => name=Roger
// Split into parts
var parts = nameValuePair.split('=');
// The name is the second value
var name = parts[1];
// Set the name in the HTML element.
document.getElementById('name-label').innerHTML = name;
</script>
</body>
</html>
You cannot simply take a function from one html and put it into another. Using pure JavaScript and HTML the best way to accomplish this would be to make a JavaScript file, put the function there and load it on both pages. That way if you edit the function in one place, it will change in both.
The code would look like this:
Page 1:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="OrderUp.css">
<title>OrderUp</title>
</head>
<body>
<form onsubmit="return results();" method="post" action="results.html" >
Name : <input name = "name" type= "text" id="name">
<br>
<input value = "Submit" type = "submit" >
</form>
<script type="text/javascript" src="results.js"></script>
</body>
</html>
Page 2:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="OrderUp.css">
<title>Results</title>
</head>
<body>
<h2> Your Form Has Been Submitted </h2>
<script type="text/javascript" src="results.js"></script>
</body>
</html>
results.js
function results() {
var name = document.getElementbyId('name').value;
document.write(name);
}
Probably the simplest would be to append it to the url:
<script>
function goToResults() {
window.location = "results.html#" + document.getElementbyId('name').value;
}
document.getElementById("submit").onclick = goToResults;
</script>
<input id = "name" />
<button id = "submit" > Submit </ button>
And on results.html just get it from the location:
document.body.innerHTML += document.location.href.split("#")[1];
You need a way to save the information you want to share between pages. There are many options for javascript each with pros and cons
use the uri hash:
location.hash = myValue / var retrieveValue = location.hash;
use localstorage:
localStorage.setItem("key", "value"); / localStorage.getItem("key");
also document.cookie is an option, (you can look that one up as it's slightly more involved to implement with many good answes already around)
Please read the form and javascript carefully. My goal is grab text input value 'a' and 'b' then total integer value will be dynamically set to text input id called- 'x'. How can i set dynamic javascript value to html text input? Also it should be real time updating so user can see the total value of a+b on x. x is actually displaying the value and will be submitting this value if 'submit' button pressed.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js" type="text/javascript"></script>
</head>
<body>
<form method="post">
<input type="text" id="a" value="5">
<input type="text" id="b" value="2">
<input type="text" id="x" value="dynamic_value_from_javascript">
<input type="submit" name="submit" value="submit">
</form>
<script type='text/javascript'>
$('#a').keyup(updatetxt);
$('#a').keydown(updatetxt);
var a = $('#a');
var b = $('#b');
var x = a+b;
function updatetxt() {
$('#x').val($(x).val());
}
</script>
</body>
</html>
Check this fiddle I have made recently,It will update real time. let me know if any query occurs
$(function() {
$( "#a" ).keyup(function() {
var a = $('#a').val();
var b = $('#b').val();
var c = parseInt(a) + parseInt(b);
$('#c').val(c);
});
$( "#b" ).keyup(function() {
var a = $('#a').val();
var b = $('#b').val();
var c = parseInt(a) + parseInt(b);
$('#c').val(c);
});
});
<input type="text" id="a" value="1"/><br>
<input type="text" id="b" value="2"/><br>
<input type="text" id="c" value=""/><br><br>
My Jsfiddle link
There are a few problems with your code, I have fixed them below:
You need to get values of a and b during the keyup events.
You need subscribe to keyup events of both a and b inputs.
In order to add integer values, you can use parseInt
Call updatetxt for the first time without any events, so that it can set the total value based on default values in the inputs
$('#a').keyup(updatetxt);
$('#b').keyup(updatetxt);
function updatetxt() {
var a = $('#a').val();
var b = $('#b').val();
var x = parseInt(a) + parseInt(b);
$('#x').val(x);
}
updatetxt();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="a" value="5">
<input type="text" id="b" value="2">
<input type="text" id="x" value="">
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 7 years ago.
I can't determine what is 'null'. I think it may be the form button, because of the form and button ids aren't the same... The console is saying the problem is on the 'button1.onclick = createParagraph;' line. Please help.
Below is my javascript
//global variables for user input
var noun1;
var noun2;
var adjective1;
var adjective2;
var verb1;
var verb2;
var paragraph1 = "hello, did this work?"
var button1 = document.getElementById("pushMe")
//to retrieve values from user input, and write to global variables
function handleSubmit(form) {
noun1 = form.querySelector('input[name=noun1]').value;
noun2 = form.querySelector('input[name=noun2]').value;
adjective1 = form.querySelector('input[name=adjective1]').value;
adjective2 = form.querySelector('input[name=adjective2]').value;
verb1 = form.querySelector('input[name=verb1]').value;
verb2 = form.querySelector('input[name=verb2]').value;
return false;
}
//to write paragraph to the DOM
function createParagraph () {
var element = document.createElement("p");
var content = document.createTextNode("paragraph1");
var location = document.getElementById("placeholder");
element.appendChild(content);
document.body.insertBefore(element,location);
}
//run it all!
button1.onclick = createParagraph;
Below is HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href='https://fonts.googleapis.com/css?family=Lato:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="stylesheets/madlib.css">
<script src="randomMad.js"></script>
<title>Mad Libs!</title>
</head>
<header>
</header>
<body>
<form onsubmit="return handleSubmit(this)" id="form1">
<h1>Choose your words!</h1>
<fieldset>
<label>First Noun: <input type="text" name="noun1" ></label><br>
<label>Second Noun: <input type="text" name="noun2"></label><br>
<label>First Adjective: <input type="text" name="adjective1"></label><br>
<label>Second Adjective: <input type="text" name="adjective2"></label><br>
<label>First Verb: <input type="text" name="verb1"></label><br>
<label>Second Verb: <input type="text" name="verb2"></label><br>
</fieldset>
<button type="submit" id="pushMe">Create Mad Lib</button>
</form>
<div id="placeholder">
</div>
</body>
You are missing ; in some of your lines..
See
var paragraph1 = "hello, did this work?"
var button1 = document.getElementById("pushMe")
Kindly add a ; at the end of that two lines.
UPDATE
The error may be causing because you are trying to access the element before the DOM has finished loading. Thus to solve that problem, you can just move
<script src="randomMad.js"></script>
to the end of <body> .
I have two codes, one is form.html:
<!DOCTYPE html>
<html>
<head>
<script src="D:\frameworks\jquery-1.11.3.js"></script>
<meta charset="ISO-8859-1">
<title>Form</title>
<script type="text/javascript">
$(function(){
$("#sub").on("click", function(){
sessionStorage.n1 = $("#no1").val();
sessionStorage.n2 = $("#no2").val();
location.href = "main.html";
});
});
</script>
</head>
<body>
No1:<input type="text" id="no1">
No2:<input type="text" id="no2">
<br>
<input type="button" value="Submit" id="sub">
</body>
</html>
and the other is main.html:
<!DOCTYPE html>
<html>
<head>
<script src="D:\frameworks\jquery-1.11.3.js"></script>
<meta charset="ISO-8859-1">
<title>Main</title>
<script type="text/javascript">
var n1_arr = new Array();
var n2_arr = new Array();
$(function(){
n1_arr.push(sessionStorage.getItem("n1"));
n2_arr.push(sessionStorage.getItem("n2"));
$("#a").click(function(){
location.href = "form.html";
});
$("#s").click(function(){
for(var i = 0; i < n1_arr.length; i++)
{
alert(n1_arr[i] + " and " + n2_arr[i]);
}
});
});
</script>
</head>
<body>
<input type="button" value="Add" id="a">
<input type="button" value="Show" id="s">
</body>
</html>
I want these to work like this:
First, main.html will open, and on clicking on the 'Add' button, the form.html will open in the same browser tab. The user will enter two numbers in the text boxes with id's no1 and no2. The user will then click on 'Submit' and then again, main.html should open(again in the same browser tab). The user will continue to do this for as long as he wants. On clicking the 'Show' button, alerts of all the values entered by the user, separately in pairs, will occur. How can I achieve this? In this case, only the last entered pair is alerted.
first you have to run the command on console:
sessionStorage.clear();
main.html
<!DOCTYPE html>
<html>
<head>
<script src="D:\frameworks\jquery-1.11.3.js"></script>
<meta charset="ISO-8859-1">
<title>Main</title>
<script type="text/javascript">
var n1_arr = JSON.parse(sessionStorage.getItem("n1")) || [];
var n2_arr = JSON.parse(sessionStorage.getItem("n2")) || [];
$(function(){
$("#a").click(function(){
location.href = "form.html";
});
$("#s").click(function(){
for(var i = 0; i < n1_arr.length; i++)
{
alert(n1_arr[i] + " and " + n2_arr[i]);
}
});
});
</script>
</head>
<body>
<input type="button" value="Add" id="a">
<input type="button" value="Show" id="s">
</body>
</html>
form.html
<!DOCTYPE html>
<html>
<head>
<script src="D:\frameworks\jquery-1.11.3.js"></script>
<meta charset="ISO-8859-1">
<title>Form</title>
<script type="text/javascript">
$(function(){
$("#sub").on("click", function(){
var n1 = sessionStorage.n1 || [];
if(n1.length > 0){
n1 = JSON.parse(sessionStorage.n1);
}
n1.push($("#no1").val());
sessionStorage.n1 = JSON.stringify(n1);
var n2 = sessionStorage.n2 || [];
if(n2.length > 0){
n2 = JSON.parse(sessionStorage.n2);
}
n2.push($("#no2").val());
sessionStorage.n2 = JSON.stringify(n2);
location.href = "main.html";
});
});
</script>
</head>
<body>
No1:<input type="text" id="no1">
No2:<input type="text" id="no2">
<br>
<input type="button" value="Submit" id="sub">
</body>
</html>
It would appear you are overwriting your existing n1 and n2 values.
sessionStorage stores key value pairs, with the value being a string. When you do sessionStorage.setItem('n1', 'test') it will overwrite the existing value.
What you need to do is read the existing value (it will be a string), parse it, append your new value on the end, then insert the whole object back into storage. When storing an object it will be best to stringify it as JSON first.
If you need to store complex objects like arrays etc you may find it better to use indexedDB.
https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
All I want to do is disable the button if there's no content in ftemp. If there is, I want the button to enable and check if it is numeric. Then I can send the ftemp to the next page. My html :
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function content()
{
var ftemp = document.getElementById("ftemp");
if (ftemp.value=="")
{
var convert = document.getElementById("convert").disabled=true;
document.getElementById("error").innerHTML = "";
}
else
{
isNumeric()
}
}
function isNumeric()
{
var ftemp = document.getElementById("ftemp");
if (isNaN(ftemp))
{
var convert = document.getElementById("convert").disabled=true;
document.getElementById("error").innerHTML = "Enter only numbers";
}
else
{
var convert = document.getElementById("convert").disabled=false;
document.getElementById("error").innerHTML = "";
}
}
</script>
</head>
<body onload="content()">
<form method="get" action="celsius">
<p>
<label>
Enter a temperature in Fahrenheit:
</label>
</p>
<p>
<input required id="ftemp" title="Enter only numbers!" size="3"
maxlength="3" onkeyup="content()"/>
<button id="convert" name="convert">Convert to Celsius</button>
</p>
<p id="error" name="error">
</p>
</form>
</body>
</html>
Inside isNumeric():
You are checking: isNaN(ftemp) where ftemp is a DOM element so it cannot be a number. Change to isNaN(parseInt(ftemp.value, 10)).
You have error here:
if (isNaN(ftemp))
Change it to:
if (isNaN(ftemp.value))
The ftemp is a DOM Object. You need to pass the value here.
Fiddle: http://jsbin.com/ocibuc/2