Get all the form input fields from a Page - html

So basically, I have a lot of form fields (About 50 or so). Doing an AJAX request is going to be astronomically big, and it will most likely just make my code look ugly and unreadable. Is there anyway to gather all form data from a page and do an AJAX request?

If you had the names of the object for each input box like:
<input type="text" data-ajax="MyAjaxObjectName1" />
You could recurse through all of the inputs in this way:
var ajaxObject = {};
$('#myContainer input[type=text]').each(function() {
var inputObject = $(this).data('MyAjaxObjectName1')
ajaxObject[inputObject] = $(this).val()
}
That is the simplest way I can think of to recurse through every field that you have. Although, you'd have to update the HTML to include those attributes

The jQuery 'serialize' method:
Description: Encode a set of form elements as a string for submission.
See https://api.jquery.com/serialize/

I suggest to use $.serializeArray() on the form element.
It returns an array with each name and value of form inputs.
Docu & examples: https://api.jquery.com/serializeArray/

Related

The character of the textarea input is turned to object

for example
in
input name:1111,ss:1111,... => {name:1111,ss:1111,...}
A method of turning characters into objects
I can't find a good way to do it
So, you need this method or what?
if need method, it's simple: just get value of textarea, wrap text into quotes, add braces and call on it JSON.parse()
var textarea = document.getElementById("id-of-textarea");
var value = textarea.value;
var wrapped = "{"+value.replace(/(\w+)/g, '"$1"') + "}";
var result = JSON.parse(wrapped);
But, you should expect any values that user can input, so it's not good idea to use textarea for input some data.
As per the structure of you input I would suggest you to use different textfields to capture data rather than having it into a single textarea. Like this, you will be able to iterate over those and fetch their value and store them in form of an object or a map
Your HTML:
<input id="name" value="1111"/>
<input id="ss" value="2222"/>
...
Your script (JQuery/Javascript):
var data = {};
$('input').each(function () {
data[$(this).attr("id")] = $(this).val();
});

enter term into hidden form field with html and css possible?

I have created a form in HTML/CSS on my website.
Now, my idea is to give out links that would contain some string (basically like an affiliate link) and would like that string to be entered in a hidden form field to be submitted, or somehow else, have that string in the submitted data.
is there an easy way to do this?
There are two ways of approaching this, both of which use a GET variable in the link you distribute.
First off, let's assume that--for example's purpose--your special string is abc123. You would then distribute a link that follows the form http://example.com/my/form/?affiliate=abc123.
Assuming that, here are two solutions, one in PHP and another in Javascript.
PHP Solution
This one is fairly easy, as long as you're just setting a hidden field.
<input type='hidden' name='affiliate' value='<?= htmlspecialchars($_GET['affiliate'], ENT_QUOTES, 'UTF-8'); ?>' />
Update: Added htmlspecialchars() call to escape any input, to prevent security issues with users setting the GET variable manually.
Javascript Solution
HTML
<input type='hidden' id='affiliate-input' name='affiliate' />
Javascript
This solution relies on jQuery. If you want a pure JS solution, let me know.
var $_GET = {};
// When the page loads, set the input value
$(document).ready(function(){
setupGetVariables();
var affiliateId = $_GET["affiliate"];
$("#affiliate-input").val(affiliateId);
});
function setupGetVariables()
{
if(document.location.toString().indexOf('?') !== -1) {
var query = document.location
.toString()
// get the query string
.replace(/^.*?\?/, '')
// and remove any existing hash string (thanks, #vrijdenker)
.replace(/#.*$/, '')
.split('&');
for(var i=0, l=query.length; i<l; i++) {
var aux = decodeURIComponent(query[i]).split('=');
$_GET[aux[0]] = aux[1];
}
}
}
The setupGetVariables() method was helped by this answer.

HTML Form - submit array of ID's of selected divs

I have an array of divs which can be selected (change background colour on click to signify that to the user).
I want a way to submit the ids of all of these divs to my app, though can't see a 'nice' way of doing this; at the moment the only thing I can see to do is have a button that onclick triggers a javascript function that gets the id's and sends them back to my server in a POST.
Is there a way of creating a multiple select input on a form which uses divs instead of checkboxes or a multi-select list, or a better way of doing what I'm attempting?
Assuming you add the class selected when a user 'selects' the div:
var data = {};
$(".classOfDivs.selected").each(function(){
data[$(this).prop('id')] = 'true';
}
$.ajax({
url : 'ajaxPage.php',
type : 'POST',
dataType : 'text',
cache: false,
data: data,
success : function(text){alert('Saved: '+text);},
error: function(){alert('Did not reach server');}
});
Use the success function to process the returned text as needed. dataType can be changed to html, JSON, etc. See the .ajax() documentation.
Have a hidden input for each div, all with the same name but with a different id. When a div is clicked update the corresponding hidden input with the id. Then when you submit through a standard form POST all of those values will be available through the name you specified.
Since this is an app, what you could do is store everything in HTML5 localstorage using the JQuery javascript library.
Here's how to do it step by step:
Create a jquery array
on click, get div id and store it in the array with a key/value pair
if clicked again, remove it from the array
have some event listener like a "submit" button to store the value of your array to localstorage
Here is a jsfiddle I had that has exactly what you are talking about: http://jsfiddle.net/CR47/bqfXN/1/
It goes into a little more depth but the jquery should be exactly what you need.
The reason this is better than submitting with POST or using ajax is because since you say this is an app, you will be able to use this method offline, where as post or ajax would require a connection to a server running php.
var skinCare=[]; //the array
$('.skinCare').click(function(){ //onclick
var value = event.target.className.split(" ")[0]; //get classname, you would get id
var index = skinCare.indexOf(value); //gets where the location in
//the array this code is
if($(this).hasClass('selected')){ //when a div is clicked it gets
//$('.skinCare').removeClass('selected'); //the class "selected" and adds
skinCare.splice(index, 1); //to array, then another click
} else if($.inArray(value, skinCare) == -1){ //removes it from array
skinCare.push(value);
}
});
$('.submitbutton').click(function(){
localStorage.setItem('Skin Care', JSON.stringify(skinCare));
});

Save input data to localStorage on button click

I am trying to build my first web application. In my app I need to have a settings panel, but I have no idea how to do it. I've been searching the web and came across a HTML5 localStorage, which I believe might be the best way to do the things. But the problem is I have no idea how to use it.
<input type='text' name="server" id="saveServer"/>
How can I save data from input to localStorage when user clicks the button? Something like this?
<input type='text' name="server" id="saveServer"/>
<button onclick="save_data()" type="button">Save/button>
<script>
function saveData(){
localStorage.saveServer
}
</script>
The localStorage object has a setItem method which is used to store an item. It takes 2 arguments:
A key by which you can refer to the item
A value
var input = document.getElementById("saveServer");
localStorage.setItem("server", input.val());
The above code first gets a reference to the input element, and then stores an item ("server") in local storage with the value of the value of that input element.
You can retrieve the value by calling getItem:
var storedValue = localStorage.getItem("server");
This worked for me. For setting I placed .value behind the var and called the var in the setItem:
var input = document.getElementById('saveServer').value;
localStorage.setItem('server', input);
For getting the text back:
document.getElementById('saveServer').value = localStorage.getItem('server');

MVC 3 Passing Variables Between Actions

I'm working on a website where I need to pass variables between actions. The variables are actually input fields. Here is some example markup.
<table>
<tr>
<td><input type="checkbox" name="major/1" value="1" checked /></td>
</tr>
<tr>
<td><input type="radio" name="major/2" value="1" checked /></td>
<td><input type="radio" name="major/2" value="2" /></td>
</tr>
</table>
Next Page
I basically want the values of those passed through a pagination system so it can be all used by the end. How could I accomplish this? Preferably without the use of a form surrounding the entire page.
The only way to pass input form elements from one page to another is through a form post. You can certainly pass data via session or similar, but that's not passing them in form elements.
I don't understand you reluctance to use a form. hidden fields are form elements. They're used in forms. That's their purpose. You want to use form elements but not use a form? That's pretty pointless.
EDIT:
I think your problem is that you don't truly understand the way a browser and server work. They only communicate via get and post commands. Therefore, the only way to send an input to the server is via a post, and a post must contain a form. That's how a browser sends it's data.
There's a lot of things you could do via javascript, but all of those things would be a lot messier than just doing your post.
I could see two possible methods. First, use hidden input fields inside the postback form. This will ensure variables from the current iteration get saved to the model on postback:
#Html.HiddenFor(model=>model.Field1)
The second would be to save whatever you need to TempData on the controller side and retrieve it on the next postback:
TempData["tempkey"] = MyModel;
I think that whether the best solution is one of these (or something else) depends on what your model and controller logic looks like.
The easiest way to accomplish this without using a form would be to use jQuery or javascript to grab the values and append them as url variables, assuming that is an acceptable approach. The other way would be to capture the values, send them ahead of time via ajax, and have your backend store them as session variables prior to following the link First, give the link a class name to listen to...
$('.navigation').on('click', '.pagelink', function(e){
e.preventDefault();
// url variables method
var theUrl = ($(this).attr('href')) + '?';
var ajaxUrl = $(this).attr('href');
// needed for ajax method
var theVals = new Object();
$.each('table input', function() {
// needed for ajax method
var theName = $(this).attr('name');
theVals[theName] = $(this).val();
// url variables method
theUrl = theUrl + theName + '=' + $(this).val() + '&';
});
// url variables method
theUrl = theUrl.substr(0, theUrl.length - 2);// removes ending ampersand
window.location = theUrl;
// the ajax session method
$.ajax({
url : [MVC path to store session variables - ex: /ajax/setsession/],
type : 'POST',
data : theVals,
success : function(data) {
if(data) {
// do something with data, like display success message
window.location = ajaxUrl;
}
}
});