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

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>

Related

Set hidden form field from URL paramater

I'm trying to set the value of a hidden field in my form through a URL parameter.
Here is the form:
<form accept-charset="UTF-8" action="/thanks" class="infusion-form" method="POST">
<input name="inf_field_LeadSourceId" type="hidden" value="null" />
<input class="infusion-field-input" id="inf_field_FirstName" name="inf_field_FirstName" placeholder="First Name *" type="text" required/>
<input class="infusion-field-input" id="inf_field_Email" name="inf_field_Email" placeholder="Email *" type="text" required/>
<div class="infusion-submit">
<button class="infusion-recaptcha" type="submit">Submit</button>
</div>
</form>
I need to set the value of this field, specifically:
<input name="inf_field_LeadSourceId" type="hidden" value="null" />
with a url parameter.
Ideally, I would like it to be something like this:
https://website.com/page?leadsource=123
So it would set that field to have the value of "123"
I tried doing this using the javascript code below, but no luck :(
<script>
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? 120 : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var LeadId = getParameterByName("leadsource");
jQuery(".infusion-form input[name='inf_field_LeadSourceId']").val(LeadId);
</script>
Any advice on how I can tweak my javascript to prefill my form with the URL parameter?
JavaScript isn't the best with URL parameters. If I'm understanding your question correctly, it'd probably be ideal for you to simply inject the parameter directly into the HTML field with PHP (requiring no JavaScript).
<input name="inf_field_LeadSourceId" type="hidden" value="<?php echo $_GET['leadsource']; ?>" />
Here's the javascript I used to base my solutions filling Infusionsoft hidden fields values.
Also may also try to debug your javascript flow to see if you're catching and parsing the value properly (for example, adding conlose.log(var) line).

Auto-Populated fields in a dynamic model not submitting

I need help on populating an object with the value of a text input field in a dynamic created form. In my controller i declared $scope.models={}. The last input field in the form below which has a default value g.quant1 is populated by a value from the server but after submitting the form, the value is not passed. Viewing the object this way {{models | json}}shows empty, it only submits the last input value if the value is entered only then does models get populated with the value
<div class="list" ng-repeat="g in dcs | filter:{age:'26'}">
<div class="item item-input item-stacked-label">
{{g.zidname}} </br>L: <input type="text" id="lll{{$index}}" ng-model="models['l' + $index]" name="lf{{u.gidname}}"><p>{{$index}}</p>
</br>B: <input type="text" id="bbb{{$index}}" ng-model="models['b' + $index]" name="bf{{y.gidname}}">
<!--<p>data.b{{$index}}</p>-->
</br>D: <input type="text" id="ddd{{$index}}" ng-model="models['d' + $index]" name="df{{d.gidname}}">
<!--<p>data.d{{$index}}</p>-->
</br>NUM: <input type="text" id="nummm{{$index}}" ng-model="models['num' + $index]" name="numf{{y.gidname}}">
</br>Certified Rate: <input type="text" id="crrr{{$index}}" ng-model="models['cr' + $index]" name="cre{{y.gidname}}">
<input type="text" ng-model="models['quan' + $index]" ng-value="g.quant1" >
</div>
</div>
my controller
$scope.insert50=function(){
var link = 'http://...';
$http.post(link, {user: $scope.models
}).success(function(data){
alert(data);
});
}
I had a workaround with all your problems and created a separate plunker for the solution. I am not sure what you are doing with name. For validations of each field, you need to set unique name for it and you need to add required or ng-required attribute based on your requirement. In plunker, I included validation for the last field which you can refer. Can you check this and let me know whether everything is working fine as you expected?

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.

Replace Javascript variables using a web form

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

JQuery validate triggered every time the browser gets the focus

I am using jquery validation plugin to validate my form. I have one field that I don't want to validate but in some way it is validated anyway and I get the error message "Please enter no more than 5 characters."
The field that is validated is a type=file field and I use it together with the Fynework jQuery MultiForm plugin. It's not validated when I try to submit the form, only when I chose file that has a name longer than 5 characters (I think, short names work long doesn't).
I have tried adding the class .ignore to the field that is validated and added that the ignore rule to my validat(), not difference in behaviour.
What can the problem be?
Here is my validat() method, I also include the point at which I add that method:
function addNewTicketValidation(){
$("#newticketform").validate({
ignore: ".ignore",
errorContainer: "#messageBox1",
errorLabelContainer: "#messageBox1 ul",
wrapper: "li",
debug:true,
rules: {
title: "required",
description: "required"
},
messages: {
title: "Titel saknas",
description: "Beskrivning saknas"
}
});
}
$("#newticketmanu").live('click',function(event){
$("#adminarea").load("http://" + hostname + "/" + compdir + "/modules/core/newticket/newticket.php", function(){
$('#my_file_element').MultiFile();
addNewTicketValidation();
});
});
My form:
<form method="post" enctype="multipart/form-data" id="newticketform" class="MultiFile-intercepted" novalidate="novalidate">
<input type="hidden" value="2000000" name="MAX_FILE_SIZE">
<label for="title">Rubrik</label> <input type="text" name="title" id="title"><br><br>
<label for="description">Beskrivning</label> <textarea name="description" id="description" cols="50" rows="15"></textarea><br>
<div id="my_file_element_wrap" class="MultiFile-wrap"><input type="file" maxlength="5" name="file[]" id="my_file_element" class="multi ignore MultiFile-applied" value=""><div id="my_file_element_wrap_list" class="MultiFile-list"></div></div>
<div id="files_list"></div>
<input type="submit" value="Upload" name="upload">
</form>
What can the problem be and how to fix it?
Thanks!
Remove the maxlength="5" attribute from the file input. This is read by the validation plugin and added as a rule (line 812 here https://github.com/jzaefferer/jquery-validation/blob/1.9.0/jquery.validate.js). Checking the specifications (http://www.blooberry.com/indexdot/html/tagpages/i/inputfile.htm), max length still means character length even on a file input, so if you want to limit the user to 5 file uploads you'll need some other method of achieving this.

Categories

Resources