Convert form with form arrays into a vaild json object - javascript

My form looks like this.
<form>
<input type="text" name="pic" value="test" />
<input type="text" name="person[0].name" value="Bob" />
<input type="text" name="person[0].age" value="25" />
<input type="text" name="person[1].name" value="Jim"/>
<input type="text" name="person[1].age" value="30" />
</form>
Is their a method that can take in any form and if the name of several form elements is the same then make them into an array under the initial name in json.
The json object would ideally look like
{
"pic" : "test",
"person":[
{"name":"Bob", "age":"25"},
{"name":"Jim", "age":"30"}
]
}

I found a library that handles this
form2js

Related

How can I handle duplicate inputs name?

I have a dynamic form which probably has duplicate input names.
$(".add_more_staff").on("click", function(){
var $newMember = $(this).siblings('.company_members').clone();
$newMember.insertBefore($(this));
})
a, input{
display: block;
margin-bottom: 5px;
}
input{
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post">
<div class="company_members">
<input class="staff_name" type="text" name="name" required placeholder="name" />
<input class="staff_mobile" type="text" name="mobile" required placeholder="mobile" />
<hr />
</div>
<input type="button" class="add_more_staff" value="Add more staff" />
<input type="submit" value="register_company_staffs" />
</form>
In the code above, you will have two inputs named mobile (or name) if you click on Add more staff button once.
Now I want to know, how should I get it in the PHP codes? According to some tests, $_POST['mobile'] contains the last input value. So how can I get all inputs value in PHP?
Should I make different names for new inputs in jQuery like name="mobile-n" (n = 1, 2 ..)
Should I use array-name for inputs like name="mobile[]" ?
Or what?
Try like this:
<div class="company_members">
<input class="staff_name" type="text" name="name[]" required placeholder="name" />
<input class="staff_mobile" type="text" name="mobile[]" required placeholder="mobile" />
</div>
in PHP:
$staff_names = $_POST['name'];
$staff_mobiles = $_POST['mobile'];
try this with jquery, during appending the html, you can add dynamic increment variable to like
staff_name_1, staff_name_2, staff_mobile_1, staff_mobile_2
with this, you can easily save or define the unique names, like I am showing you on simple example:
var a=0;
$(".add_more_staff").on("click", function(){
$(".company_members").each(function(){
a++;
$(".staff_name").attr('name', $(".staff_name").attr('name')+a);
});
});
Hope you can my idea.
Please try below it will contains data in groups, so you can easily loop it after post data and your JQuery code seems fine.
<div class="company_members">
<input class="staff_name" type="text" name="data[0][name]" required placeholder="name" />
<input class="staff_mobile" type="text" name="data[0][mobile]" required placeholder="mobile" />
</div>
<div class="company_members">
<input class="staff_name" type="text" name="data[1][name]" required placeholder="name" />
<input class="staff_mobile" type="text" name="data[1][mobile]" required placeholder="mobile" />
</div>

Copy multiple input fields to other matching input fields with jQuery/Javascript

I have a dummy form and the actual form in which at some point I want to copy all the input values from the dummy form across to the real form.
The dummy fields will have the same names as the real form (so I can match them up).
So in dummy form:
<input name="item1" value="field1" />
<input name="item2" value="field1" />
<input name="item3" value="field1" />
and in real form:
<input name="item1" value="" />
<input name="item2" value="" />
<input name="item3" value="" />
I assume I'll need to iterate over each input in dummy form (using jQuery .each() ?) while collecting the name and value in an JS object.
Then iterate over each input in the real form, matching the name as the selector and setting the value (perhaps this can be done in the one .each() function ???)
I've started with the following code which only grabs the values (and index) into an array, but because I need two values (name and value, and index is irrelevant) I assume I'll need an object not an array, but really not sure where to begin with that.
var inputValues = [];
$("#dummyForm input").each(function() {
inputValues.push($(this).val());
});
Any help or advice much appreciated.
Map them like
$('#DummyForm [name]').each(function() {
var name = $(this).attr('name');
$('#RealForm [name="' + name + '"]').val($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form id="DummyForm">
<input name="item1" value="field1" />
<input name="item2" value="field2" />
<input name="item3" value="field3" />
</form>
<form id="RealForm">
<input name="item1" value="" />
<input name="item2" value="" />
<input name="item3" value="" />
</form>
You could do something like below:
$('#dummy input').each(function(){
if($('#real input[name='+$(this).prop('name')+']').length == 1)
$('#real input[name='+$(this).prop('name')+']').val($('#dummy input[name='+$(this).prop('name')+']').val())
});
Here is my Fiddle...

Chrome 41 password saving makes wrong choice when used with Dojo validation

Chrome's "Save Password" feature apparently makes a simple choice when offering to remember passwords: It looks at the value of the previous input field in the DOM and offers to key the password to that value. So if you have this username/password combo:
<form>
<input value="myname" />
<input value="mypassword" />
</form>
the browser will offer to save the password "mypassword" under the key "myname".
This presents a problem when using Dojo ValidationTextBox however, because the Dojo parser inserts an invisible INPUT control that contains a character "X" used as a validation icon (simplified HTML view):
<form>
<div>
<input value="X" />
<input value="myname" />
</div>
<div>
<input value="X" />
<input value="mypassword" />
</div>
</form>
Under this circumstance Chrome offers to remember "mypassword" under the name of "X", which is awkward.
Is it possible to override this behavior in Chrome? Or do we need to rewrite this functionality in Dojo?
Add name properties to the validation widgets:
this.username = new ValidationTextBox({ name: 'username' });
this.password = new ValidationTextBox({ name: 'password' });
Or declaratively:
<input type="text" name="username" data-dojo-type="dijit/form/ValidationTextBox" />
<input type="text" name="password" data-dojo-type="dijit/form/ValidationTextBox" />
This will produce nodes with name attributes which Chrome will be able to use to associate the value with a key. Your simplified HTML view would then look like this:
<form>
<div>
<input value="X" />
<input name="username" value="myname" />
</div>
<div>
<input value="X" />
<input name="password" value="mypassword" />
</div>
</form>
I've figured out how you can make this to work. When you use the name attribute with the appropiate values(username, password) the username value will be the input value above the password input.
1. Surround your fields with a form
<form method="post">
<input type="text" autocomplete="username" data-dojo-props="selectOnClick: true, uppercase: true" data-dojo-type="dijit/form/ValidationTextBox" required="required" />
</form>
2. Add an autocomplete to your input field with the value 'username' and 'password'
<input type="text" autocomplete="username" data-dojo-props="selectOnClick: true, uppercase: true" data-dojo-type="dijit/form/ValidationTextBox" required="required" />
<input type="password" autocomplete="password" data-dojo-props="selectOnClick: true, uppercase: true" data-dojo-type="dijit/form/ValidationTextBox" required="required" />
3. Add a button to submit or just a regular button
<input type="submit" value="send" />
See the fiddle

Submitting 2D array form input using AJAX in Javascript

I have a form as follows:
<form name="chat" id="chat" action="" onsubmit="sendMessage()">
<a name="chat"> </a>
<input type="text" name="chat" id="chat" size="38" maxlength="50" vertical-align="middle">
<input type="hidden" name="action" id="action" value="checkresponse">
<input type="hidden" name="response_Array[sessionid]" id="response_Array[sessionid]" value="keu88lh88ini89dgnccob54f27"><br>
<input type="text" name="response_Array[top]" id="response_Array[top]" value="a">
<input type="text" name="response_Array[second]" id="response_Array[second]" value="b"><br>
<input type="text" name="response_Array[third]" id="response_Array[third]" value="c"><br>
<input type="text" name="response_Array[fourth]" id="response_Array[fourth]" value="d"><br>
<input type="text" name="response_Array[input][0]" id="response_Array[input][0]" value="input 0"><br>
<input type="text" name="response_Array[that][0]" id="response_Array[that][0]" value="that 0"><br>
<input type="submit" name="submit" id ="submit" value="SEND" style="width: 45px">
</form>
When the user clicks Submit, I need to send all the input fields to the server.
But, the page should not get refreshed. So, I have created sendMessage(),in which I have used XMLHttpRequest object to send the form submit request.
To read input fields, I have used in sendMessage():
var infoStr = "chat="+document.forms[0]['chat'].value;
infoStr += "&action="+document.forms[0]['action'].value;
I want to know how should I read the 2D array :response_Array and parse it into a JSON string so that it can be passed to the php server code.
It is so simple
var infoStr=""
for(var i=0;i<document.forms[0].elements.length;i++)
{
infoStr+=document.forms[0].elements[i].name+"="+document.forms[0].elements[i].value+"&";
}
alert(infoStr); // You will have the full name value pairs.
Hope this solves your problem.

jQuery serialize function with multple forms

I'm using the jQuery .serialize function and can't get it to serialize the proper form on submit.
my js code:
function getquerystring(form) {
return $("form").serialize();
}
my forms:
<div class="leave_message_box">
<form name="leave_message_form">
<input type="text" name="clock_code" placeholder="Clock Code" />
<input type="text" name="message" placeholder="Message (Blank for none)"/>
<input type="hidden" name="type" value="leave_message" />
<input value="Leave Message" type="button" onclick='JavaScript:xmlhttpPost("clockin.php", "leave_message_form")'></p>
</form>
</div>
<div class="outside_job_box">
<form name="outside_job_form">
<input type="text" name="clock_code" placeholder="Clock Code" />
<input type="text" name="message" placeholder="Message (Blank for none)"/>
<input type="hidden" name="type" value="ouside_job" />
<input value="Outside Job" type="button" onclick='JavaScript:xmlhttpPost("clockin.php", "outside_job_form")'></p>
</form>
</div>
I must be doing something wrong in passing the variable. the full code # pastie. The function I have does work, however, its always the last form that gets submitted.
Using this code:
$("form")
will find all the <form> elements in your document.
Given that form is a string containing the name of the form, what you want instead is this:
$("form[name='" + form + "']")
Looking at your supplied code, I have this suggestion. Instead of passing the form name to your function, why not just pass the form itself?
<button onclick="xmlhttpPost('blah', this.form)">
You also don't need to put javascript: in the onclick, onfocus, onwhatever properties.
I would suggest putting an ID attribute on the form and then using that ID as an explicit selector for jQuery:
<div class="outside_job_box">
<form id="outside_job_form" name="outside_job_form">
<input type="text" name="clock_code" placeholder="Clock Code" />
<input type="text" name="message" placeholder="Message (Blank for none)"/>
<input type="hidden" name="type" value="ouside_job" />
<input value="Outside Job" type="button" onclick='JavaScript:xmlhttpPost("clockin.php", "outside_job_form")'></p>
</form>
</div>
Then you would select and serialize it like this;
var f = $("#outside_job_form").serialize();
Not only making your code more effecient but more readable, in my opinion.
If the sole purpose is to encode simple text into URL format then use encodeURIComponent().

Categories

Resources