Replace Javascript variables using a web form - javascript

How do i replace variables in a javascript file by using a web form such as below.
The idea is that i can make changes to the javascript variables by submitting changes through a web form.
Thanks in advance
HTML FIle
<html>
<body>
<FORM action="auction_time_var.js" method="post" id="adminForm">
<P>
<LABEL for="name">Name: </LABEL>
<INPUT type="text" id="firstname"><BR>
<LABEL for="price">Price: </LABEL>
<INPUT type="text" id="lastname"><BR>
<LABEL for="dueTime">Due Time: </LABEL>
<INPUT type="text" id="email"><BR>
<LABEL for="location">Location: </LABEL>
<INPUT type="text" id="location"><BR>
<LABEL for="urlPhoto">Photo url: </LABEL>
<INPUT type="text" id="photo_url"><BR>
<LABEL for="description">Description: </LABEL><br>
<textarea rows="4" cols="50" name="comment" form="adminForm">
Enter text here...</textarea>
<INPUT type="submit" value="Send">
</P>
</FORM>
</body>
</html>
Javascript file
var data = [
{name: "Title 1", price:"$100", countdown: "April 2, 2014 15:41:00", location:"Brisbane", description:"awesome stuff", highestBidder: "Highest bidder 1", },
];

You should use jQuery Populate plugin to fill form data.
You need to do 3 things to have Populate automatically fill an HTML form with the correct values:
Include the blank HTML form in the body of the page
Get the relevant form data, e.g. user information, into JSON format
Output the JSON format as the first agument of the Populate call
The basic form for using Populate is:
Syntax
$(selector).populate(JSON, options)
to populate a very simple form, you might output the following code after the form body:
Example
$('#form-simple').populate({
'name':'Title 1',
'price':'$100',
...
...
});
Check this Demo
you put your JSON data to show you result. Hope this help you!

To access variables from <input> (if you mean this)
var data = [document.getElementById("firstname").value,
document.getElementById("lastname").value,
document.getElementById("email").value,
document.getElementById("location").value,
document.getElementById("photo_url").value];
To edit them:
data[0]="new_value"; //firstname
data[1]="new_value"; //lastname
data[2]="new_value"; //email
data[3]="new_value"; //location
data[4]="new_value"; //photo_url

It's hard to understand exactly what you're trying to do, but I think if you're wanting to convert a form to a JavaScript object you could try using the serializeArray function with a small jQuery extention serializeObject.
function getVariables() {
var formObj = $('#adminForm').serializeObject();
console.log(formObj);
}
This will return an object like:
formObj.comment = "A test entry"
formObj.email = "01/01/2014"
formObj.firstname = "Mark"
formObj.lastname = "10.00"
formObj.location = "Town"
formObj.photo_url = "http://www.example.com"
JSFiddle: http://jsfiddle.net/7FZCf/
Inspired from this post:
Convert form data to JavaScript object with jQuery

Related

Can't get my simple JavaScript Event Handler working

I am trying to get an event handler on an HTML form. I am just trying t get the simplest thing working, but I just cannot see what I am missing.
It is part of a wider project, but since I cannot get this bit working I have reduced it down the most very basic elements 1 text field and a button to try and see what it is I am missing.
All I want to do is get some text entered and flash up message in a different area on the screen.
The user enters text into the input field (id=owner).
The plan is that when the button (id="entry") is pressed the event handler (function "entry") in the entry.js file should cause a message to display.
I don't want the form to take me to a different place it needs to stay where it is
I just want some form of text to go in the: <div id="feedback" section.
When I can get it working: I intend the create the text from the various text fields that get entered.
I Know that this is beginner stuff & I know that I have reduced this down such that it barely worth thought but I would welcome any input please & thank you.
HTML code is:
<form method="post" action="">
<label for="owner">Input Owner: </label>
<input type="text" id="owner" />
<div id="feedback"></div>
<input type="submit" value="enter" id="entry" />
</form>
<script src="entry.js"></script>
Code for entry.js is:
function entry() {
var elOwner = document.getElementById('owner');
var elMsg = document.getElementByID('feedback');
elMsg.textContent = 'hello';
}
var elEntry = document.getElementById('entry');
elEntry.onsubmit=entry;
I have tried:
Adding in a prevent default:
window.event.preventDefault();
doing this through an event Listener:
elEntry.addEventListener('submit',entry,false);
using innerHTML to post the message:
elMsg.innerHTML = "
At present all that happens is that the pushing submit reloads the page - with no indication of any text being posted anywhere.
One issue is that you have a typo, where getElementById capitalized the D at the end.
Another is that preventDefault() should be called on the form element, not the input.
Here's a working example that corrects those two mistakes.
function entry(event) {
var elOwner = document.getElementById('owner');
var elMsg = document.getElementById('feedback');
elMsg.textContent = 'hello';
event.preventDefault();
}
var entryForm = document.getElementById('entry').form;
entryForm.onsubmit = entry;
<form method="post" action="">
<label for="owner">Input Owner: </label>
<input type="text" id="owner" />
<div id="feedback"></div>
<input type="submit" value="enter" id="entry" />
</form>
I also defined a event parameter for the handler. I don't remember is window.event was ever standardized (it probably was), but I'd prefer the parameter.
Be sure to keep your developer console open so that you can get information on errors that may result from typos.
var elEntry = document.getElementById('entry');
elEntry.addEventListener("click", function(e) {
e.preventDefault();
var elMsg = document.getElementById('feedback');
elMsg.textContent = 'hello';
});
<form method="post" action="">
<label for="owner">Input Owner: </label>
<input type="text" id="owner" />
<div id="feedback"></div>
<input type="submit" value="enter" id="entry" />
</form>

How to urlencode angularjs ng-model realtime

Recently I've started a new project and would like to do some angularjs magic. The problem is i'm not skilled enough in angularjs or javascript to know how I could do it. One requirement is that it has to be in realtime without reloading a page.
So let me start with my questions now. I've got a simple input field and a display section that instantly shows everything that I type in. However I want the display part to be modified on the fly.
<div id="form" class="form-wrap" ng-app="" />
<form action="index.php" method="post" id="form" />
<input type="text" name="url" id="url" value="" ng-model="name" />
<input type="submit" name="form_submit" id="form_submit" value="GOTO" />
</form>
https://example.com/index.php?url={{name}}
</div>
I'm already doing a validation in javascript but I dont know if it needs to be done in javascript or somehow in de anguarjs code itself. Just to be sure my javascript validation code:
<script>
$('<div class="loading"><span class="bounce1"></span><span class="bounce2"></span><span class="bounce3"></span></div>').hide().appendTo('.form-wrap');
$('<div class="success"></div>').hide().appendTo('.form-wrap');
$('#form').validate({
rules: {
url: { required: true, url: true }
},
messages: {
url: {
required: 'Address is requ!red',
url: 'Address is not val!d (https://www.nu.nl)'
}
},
errorElement: 'span',
errorPlacement: function(error, element){
error.appendTo(element.parent());
},
});
</script>
As you might guess by now I want the {{name}} value to be urlencoded realtime so that an url like: https://www.google.nl/?q=a b c will be changed to https://www.google.nl/?q=a%20b%20c However, how should I do this?
Thanks in advance!
Hi you can call a function on ng-change to encode name into url format like below.
I have create a function urlFormat which take name value and convert it to url format and push new variable urlname back.
<div id="form" class="form-wrap" ng-app="" />
<form action="index.php" method="post" id="form" />
<input type="text" name="url" id="url" value="" ng-model="name" ng-change="urlFormat(name)" />
<input type="submit" name="form_submit" id="form_submit" value="GOTO" />
</form>
https://example.com/index.php?url={{urlname}}
</div>
And create that function inside your controller like
$scope.urlFormat = function (name) {
$scope.urlname = encodeURI(name)
}

HTML/Javascript only - Showing form results on a different page

I want to make it so:
User fills out a form
User clicks Submit
Redirect user to a page that thanks him for his registration and show him a summary of the information he entered.
Basically, I want to transfer form values set in one HTML file to another.
<html>
<head>
</head>
<body>
<form>
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname"><br>
Address: <input type="text" name="address"><br>
City: <input type="text" name="city"><br>
State: <input type="text" name="state"><br>
Zip: <input type="text" name="zip"><br>
Phone Number: <input type="text" name="phone"><br>
Affiliation:<br>
<input type="radio" name="affil" value="demo">Democrat<br>
<input type="radio" name="affil" value="green">Green Party<br>
<input type="radio" name="affil" value="liber">Liberterian<br>
<input type="radio" name="affil" value="repub">Republican<br>
<input type="radio" name="affil" value="None">Unafiiliated<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
I only want to do this with HTML/Javascript and not PHP or ASP
You have to submit the GET request to the page. The form variables should be encoded in the URL and you can extract them.
See this answer for an implementation of the extractor.
A very easy way to do it would be to use HTML5 Web Storage. It's very easy to use, but not supported on every browser (only modern ones). One way to learn how to use it and which browsers are supported is to check out this link: http://www.w3schools.com/html/html5_webstorage.asp
Just store your values from your form in Javascript (using jQuery or regular javascript). Register a "submit" event handler so that you can save the form values before redirecting the user to the new page. When you get to your new page, then read the storage to retrieve the values.
$("form").submit(function() {
var values = {
firstname: $('input[name=firstname]').val(),
lastname: $('input[name=lastname]').val(),
address: $('input[name=address]').val(),
city: $('input[name=city]').val(),
state: $('input[name=state]').val(),
zip: $('input[name=zip]').val(),
phone: $('input[name=phone]').val(),
affil: $('input[name=affil]:checked').val()
},
formAsString = JSON.stringify(values);
sessionStorage.setItem("myForm", formAsString);
});
On your second page, you can read the values saved on the first page. I've omitted any error checking that you would definitely want to make sure that saved data exists.
function readFormValues() {
var savedFormValues = sessionStorage.getItem("myForm"),
savedFormAsObject = JSON.parse(savedFormValues),
html = "";
html += "<p>Thanks for registering!<br>";
html += "Summary:<br />";
html += "First Name: " + savedFormAsObject.firstname + "<br />";
html += "Last Name: " + savedFormAsObject.lastname + "<br />";
// etc.
}
You could also accomplish the same thing, following the same process, by using cookies instead of Web Storage.
Or, like other answers said, stick all of the values in the URL on your redirect, and then read them out of the URL when you get to your new page.

data-bind multiple text boxes to display in one text box

I'm using a Kendo edit box that a user can enter the different parts of a SQL connection string (server name, database, user name and password). I also have a text box that will show the user the entire connection string as they type.
My question is how can I data-bind each of the four text boxes (server, database, user and password) to one text box as the user enters data into each one.
Also, the user requested seperate fields.
Thanks in advance,
Dan Plocica
Doing it using Kendo UI would be:
HTML:
<div id="form">
<label>Server : <input type="text" class="k-textbox" data-bind="value: server"></label><br/>
<label>Database : <input type="text" class="k-textbox" data-bind="value: db"></label><br/>
<label>User : <input type="text" class="k-textbox" data-bind="value: user"></label><br/>
<label>Password : <input type="password" class="k-textbox" data-bind="value: password"></label><br/>
<div id="connections" data-bind="text: connection"></div>
</div>
JavaScript:
$(document).ready(function () {
var model = kendo.observable({
server : "localhost:1521",
db : "database",
user : "scott",
password : "tiger",
connection: function () {
return this.get("user") + "/" +
this.get("password") + "#" +
this.get("server") + ":" +
this.get("db");
}
});
kendo.bind($("#form"), model);
});
In the HTML there are two parts:
The input files where I define each input to what field it is bound in my model.
A div where I found its text to connection function in my model that creates a string from the different values.
This is automatically updated and you can freely edit each input.
You might decorate the input as I did setting it's CSS class to k-textbox, that's optional. The only important thing is the data-bind="value : ...".
The JavaScript, is just create and Observable object with the fields and methods that we want.
Running example here: http://jsfiddle.net/OnaBai/xjNMf/
I will write solution using jQuery JavaScript library, and you should use jQuery because its much easier and easier to read and also to avoid errors in different browsers.
**HTML**
Server: <input type="text" id="server"/><br/>
Database: <input type="text" id="database"/><br/>
Username: <input type="text" id="username"/><br/>
Password: <input type="text" id="password"/><br/>
<br/>
Full CS: <input type="text" id="solution"/><br/>
JS
<script type="text/javascript">
var _template = 'Data Source=%server%;Initial Catalog=%db%;Persist Security Info=True;User ID=%user%;Password=%pass%';
$(document).ready(function(){
$('#server,#database,#username,#password').keyup(function(){ updateSolution();});
});
function updateSolution(){
var _t = _template.replace('%server%', $('#server').val()).replace('%db%', $('#database').val()).replace('%username%', $('#username').val()).replace('%pass%', $('#password').val());
$('#solution').val(_t);
};
</script>

Requesting specific values from an html input via Javascript

I'm trying to find a way to be able to do the following. I want to be able to get certain things from a form. In this case, I only want the "value" field and NOT the "name" field.
<div class="searchbox_team" style="margin: 0 0 10px 0; z-index: 50;">
<script type="text/javascript">
function customSearch()
{
var x = document.customSearch;
x.replace("customSearch=", "");
return x;
}
</script>
<form name="leSearch" action="/search/node/" onsubmit="return customSearch()" id="search-block-form" class="search-form">
<input type="text" name="customSearch" value="" id="edit-search-block-form-1" class="searchbox_input" title="Enter the terms you wish to search for." />
<input type="submit"/>
</form>
</div>
I have tried using the following in my function.
var x = document.customSearch.value;" but that is not working.
Can anyone shed some light on this?
It sounds like you want the value of the input for customSearch. If so then just use the following
var value = document.getElementById('edit-search-block-form-1').value;
Your input tag already has an id value hence the most efficient and simplest way to search for it is using getElementById.
hmm, so to get things from the form, you'll want to specifiy like so:
document.forms.leSearch.elements["customSearch"].value;
EDIT:
try adding a hidden field that stores the value onclick and then get that from the post or get array in your action file.. I think onsubmit call is to blame
<form name="leSearch" action="/search/node/" onclick="document.getElementById('myhiddenfield').value = customSearch()" id="search-block-form" class="search-form" method="post">
<input type="text" name="customSearch" value="" id="edit-search-block-form-1" class="searchbox_input" title="Enter the terms you wish to search for." />
<input type="hidden" value="" id="myhiddenfield" />
<input type="submit"/>
</form>
EDIT 2:
I think I figured it out.. the url was appending the field names because it was defaulting to "get" method mode.. set the action=/node/search/" and method="post"
<form method="post" action="/search/node/" onsubmit="this.action = '/search/node/' + document.getElementById('edit-search-block-form-1').value;">

Categories

Resources