Reputation: 1108
I have a number of variables in my script that I would like to be able to edit through the HTML side of the program. This way if changes need to be made to the program, the script can be left well alone and changes can be made through the HTML.
Here are the variables I would like to edit in the HTML:
var numberToComplete = 2;
var xAxis = 8;
var yAxis = 6;
var populationAmount = 2;
Is there any way of doing this, if so how?
Upvotes: 1
Views: 8494
Reputation: 3811
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Testing Variable Capturing</title>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script>
var numberToComplete = 0;
var xAxis = 0;
var yAxis = 0;
var populationAmount = 0;
function setValues() {
numberToComplete = $("#numberToComplete").val();
xAxis = $("#xAxis").val();
yAxis = $("#yAxis").val();
populationAmount = $("#populationAmount").val();
}
function getValues() {
$("#result").text("numberToComplete: " + numberToComplete + " | xAxis: " + xAxis + " | yAxis: " + yAxis + " | populationAmount: " + populationAmount);
}
</script>
</head>
<body>
numberToComplete : <input id="numberToComplete" type="text"/><br/>
xAxis: <input id="xAxis" type="text"/><br/>
yAxis: <input id="yAxis" type="text"/><br/>
populationAmount: <input id="populationAmount" type="text"/><br/>
<input type="button" onclick="setValues();" value="Set Values" />
<input type="button" onclick="getValues();" value="Get Values" /><br/>
<div id="result"></div>
</body>
</html>
The above code illustrates a simple form which captures the values typed in by the user and sets the values equal to the variables you want. This example makes use of a jQuery reference.
Upvotes: 1
Reputation: 4617
This way you can pass values from html form and you won't have to change your script
<input type='text' id='numberToComplete'>
<input type='button' id='mybutton' value='mybutton'>
$("#mybutton").click(function(){
var numberToComplete = ($("#numberToComplete").val()=='')? 2:$("#numberToComplete").val() ;
var xAxis = 8;
var yAxis = 6;
var populationAmount = 2;
});
DEMO
Upvotes: 0
Reputation: 201588
HTML as such cannot do such things, but you can have an event handler that does the job, e.g.
<label for=n>Number to complete:</label>
<input id=n value=3 onchange="numberToComplete = this.value">
Exactly how you do this depends on the context.
Upvotes: 1
Reputation: 2554
you can write a function which will use eval
to execute the javascript and set the value
Upvotes: 0