jQuery - placeholder values after submiting form contact - javascript

I want to improve my form contact using jQuery. I want to clear input fields after clicking and show placeholders values on submit button. I have placeholders in my input fields and want to load them into variable and show them after ajax post method.
<input type="text" name="name" placeholder="Name" data-error="Please write name">
and jQuery code:
form.on("submit", function(e) {
e.preventDefault();
var hasErrors = false;
$('div.error_message').remove(); // Remove any old errors when submitting the form
fields.each(function(i, elem) {
var field = $(elem),
empty = $.trim(field.val()) === "",
errors = field.data("error");
if (empty) {
hasErrors = true;
field.after('<div class="error_message">' + errors + '</div>'); // add new error messages
field.toggleClass("form_error", empty);
}
});
if (!hasErrors) {
var formData = $(this).serializeArray();
$.post(form.attr("action"), formData, function(data) {
console.log(data, true);
$(".przycisk").on("click", function() {
var placeholder = $("input[placeholder]");
console.log(placeholder);
$("input, textarea").val(placeholder);
});
} else {
}
return false;
});

you have to say wich attribute from input do you want to use.
in jquery is so: .attr('attributeName')
now you can select your any attribute (like placeholder)
change your code like this:
$("input, textarea").val(placeholder.attr('placeholder'));
see my code here :
https://codepen.io/miladfm/pen/ZyOEWX

Related

how to tweak form validator.js to only send form if checkbox is checked

I have made a contact form using the example at https://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form which works fine.
Now I would like to add a checkbox which the user has to check (besides a google recaptcha and the mandatory form fields) if he wants to be able to submit the form.
i think i have to tweak the validator.js file but since i don't know javascript, i have no idea how to edit the existing validator file.
HTML of additional checkbox:
<label>
<input type="chbox" name="chbox" id="chbox">Terms and conditions.
</label>
js:
function getValue($el) {
return $el.is('[type="checkbox"]') ? $el.prop('checked') :
$el.is('[type="radio"]') ? !!$('[name="' + $el.attr('name') + '"]:checked').length :
$el.val()
}
var Validator = function (element, options) {
this.options = options
this.validators = $.extend({}, Validator.VALIDATORS, options.custom)
this.$element = $(element)
this.$btn = $('button[type="submit"], input[type="submit"]')
.filter('[form="' + this.$element.attr('id') + '"]')
.add(this.$element.find('input[type="submit"], button[type="submit"]'))
this.update()
this.$element.on('input.bs.validator change.bs.validator focusout.bs.validator', $.proxy(this.onInput, this))
this.$element.on('submit.bs.validator', $.proxy(this.onSubmit, this))
this.$element.on('reset.bs.validator', $.proxy(this.reset, this))
this.$element.find('[data-match]').each(function () {
var $this = $(this)
var target = $this.data('match')
$(target).on('input.bs.validator', function (e) {
getValue($this) && $this.trigger('input.bs.validator')
})
})
this.$inputs.filter(function () { return getValue($(this)) }).trigger('focusout')
this.$element.attr('novalidate', true) // disable automatic native validation
this.toggleSubmit()
}
only if the mandatory fields are filled out and the checkbox and the recaptcha checks are made, the submit button should become clickable and the form can be submitted.
oh, i just found out myself that the html for the checkbox was incomplete. i added required="required". the complete line now is
<input type="checkbox" name="chbox" id="chbox" required="required">
and now finally works as intended.

Get Js Value in Laravel Controller

How do I get the js value in Laravel controller. I want to pass the value from the hidden fields to be saved in the db, but to my surprise it saves empty records for these fields. When I logged the values on the console, I am seeing it but it is not passed as the value to the controller. What better way am I to handle this?
public function store(UserContactRequest $userContactRequest)
{
$phone = $userContactRequest->phone_output;
if(Auth::user()) {
if($userContactRequest->isMethod('post')) {
$userContact = UserContact::firstOrNew(array('user_id'=>Auth::user()->id));
$userContact->phone = $phone;
$userContact->save();
return redirect()->route('userContactIndex')->with('message', 'Your question has been posted.');
}else{
return redirect('user/contact/create')->withErrors($userContactRequest)->withInput();
}
}
}
This is the blade file
<TH>FIELD</TH><TH>DECRIPTION</TH>
<input type="hidden" name="phone_output" id="phone_output">
<TR><TD><div>{!! Form::tel('phone', Input::old('phone'), ['class'=>'mid first-input-div', 'placeholder'=>'8023472436', 'id'=>'phone']) !!}</div></TD><TD class="font-description"><SPAN id="errNm1"><STRONG><I>FIRSTNAME</I></STRONG></SPAN> field requests the input of your surname or family name. Only <SPAN><STRONG><I>alphabets</I></STRONG></SPAN> are accepted as valid inputs. </TD></TR>
THis is the js file:
$("#phone").intlTelInput();
var input = $("#phone"),
output = $("#phone_output");
input.intlTelInput({
nationalMode: true,
utilsScript: "http://localhost:88/build/js/utils.js" // just for formatting/placeholders etc
});
// listen to "keyup", but also "change" to update when the user selects a country
input.on("keyup change", function() {
var intlNumber = input.intlTelInput("getNumber");
if (intlNumber) {
output.text("International: " + intlNumber);
console.log(intlNumber);
} else {
output.text("Please enter a number below");
}
});
You should use output.val() to set a value for the hidden input field.
You have used output.text() instead.
Updated snippet :
input.on("keyup change", function() {
var intlNumber = input.intlTelInput("getNumber");
if (intlNumber) {
output.val("International: " + intlNumber);
console.log(intlNumber);
} else {
output.val("Please enter a number below");
}
});

php and javascript form validation issue

I have created a form using bootstrap and am using javascript for form validation and then a php script to grab the post data and display it
the basic structure is the following and I have made this as minimal as I could to address this specific issue. The issue I am having is that the script to check for the form validation works perfectly in the <script> tags at the end of the body, but instead of preventing the page from being submitted as it should it still processes to the next page with the form's contents that are being made through the php post action when the form is indeed not filled out correctly.
Why is this? Should the form validation still not stop the page from moving on to the post data since the validation is returning false if the form has not been submitted correctly. All the form validation alerts pop up correctly and I;m getting no console errors after checking, or do I need to perform an additional check to only process the post data if the form is valid?
<html>
other tags.....
<body>
<form name = "OrderForm" action = "process_order.php" onsubmit = "orderbutton" method = "post">
a bunch of content, divs, checkboxes, etc
</form>
</body>
<script>
function CheckForm() {
var Name = document.getElementById("Name");
var fries = document.forms.OrderForm.FryRadio;
var fryyes = fries[0].checked
var fryno = fries[1].checked
var bool = true;
if ((Name.value == "" || Name.value == "Name") || (!(document.getElementById("SandwichRadio").checked || document.getElementById("WrapRadio").checked))) {
bool = false;
}
else if (!(fryyes || fryno)) {
bool = false;
}
if (!(bool)) {
alert("Please fill out all of the required fields.");
return false;
}
else {
alert("Your order is being submitted");
console.log("Submitted")
}
};
</script>
</html>
You should call function on submit , I dont know what are you doing with current onsubmit='...'
So use following, call function when you submit the form.
<form name = "OrderForm" action = "process_order.php" onsubmit = "return CheckForm()" method = "post">
a bunch of content, divs, checkboxes, etc
</form>
For demo : Check Fiddle
first of all what you can do is:
you do not need the !fryes in another if statement:
you can do it also in the first if:
if ((Name.value == "" || Name.value == "Name") || (!(document.getElementById("SandwichRadio").checked || document.getElementById("WrapRadio").checked)) || ( (!(fryyes || fryno))) {
bool = false;
}
also what you can do is if bool is false, disable your submit button if there is any?
you can also do an onchange on the texboxes, that way you can validate each text box or checkbox one by one. and have the bool true and false?
I did something like this on jquery long time ago, for validation, where I checked each texbox or dropdown against database and then validate, aswell..
The code is below
<script>
$(document).ready(function(){
var works=true;
//Coding for the captcha, to see if the user has typed the correct text
$('#mycaptcha').on('keyup',function(){
if($('#mycaptcha').val().length>=5){
$.post("user_test/captcha_check.php",
{
// userid: $("#userlogin").val(),
mocaptcha: $("#mycaptcha").val(),
},
function(data,status){
if(data==0){
document.getElementById("final_error").innerHTML="Captcha did not match";
works=false;
}
if(data==1){
works=true;
document.getElementById("final_error").innerHTML="";
}
});
}
});
//Works like a flag, if any mistake in the form it will turn to false
//Coding the submit button...
$('#submitbtn').on('click',function(){
var arrLang = [];
var arrPrf = [];
uid = $("#userid").val();
capc = $('#mycaptcha').val();
pwd = $("#pwd1").val();
fname = $("#fname").val();
lname = $("#lname").val();
email = $("#memail").val();
pass = $("#pwd2, #pwd1").val();
daysel = $('#dayselect').val();
monthsel = $('#monthselect').val();
yearsel = $('#yearselect').val();
agree_term = $('#agree_box').prop('checked');
//checks if the textboxes are empty it will change the flag to false;
if((!uid) || (!capc) ||(!fname) || (!lname) || (!email) || (!pass) || (!daysel) || (!monthsel) || (!yearsel) || (!agree_term)){
works=false;
}
if(!works){
document.getElementById('final_error').innerHTML ="<font size='1.3px' color='red'>Please fill the form, accept the agreement and re-submit your form</font>";
}
else{
works=true;
//A jquery function, that goes through the array of selects and then adds them to the array called arrLang
$('[id=lang]').each(function (i, item) {
var lang = $(item).val();
arrLang.push(lang);
});
//A jquery function, that goes through the array of select prof and then adds them to the array called arrprf
$('[id=prof]').each(function (i, item) {
var prof = $(item).val();
arrPrf.push(prof);
});
var data0 = {fname: fname, mlname : lname, userid : uid,password:pwd, emailid : email, mylanguage : arrLang, proficient : arrPrf, dob : yearsel+"-"+monthsel+"-"+daysel};
//var json = JSON2.stringify(data0 );
$.post("Register_action.php",
{
// userid: $("#userlogin").val(),
json: data0,
},
function(data,status){
if(data==1){
//alert(data);
window.location = 'Registered.php';
}
document.getElementById("userid_error").innerHTML=data;
});
}
});
//to open the agreement in a seperate page to read it..
$("#load_agreement").click(function () {
window.open("agreement.html", "PopupWindow", "width=600,height=600,scrollbars=yes,resizable=no");
});
//A code that loads, another page inside the agreement div
$( "#agreement" ).load( "agreement.html" );
//This part here will keep generating, duplicate of the language and profeciency box, incase someone needs it
$('#Add').click(function(){
//we select the box clone it and insert it after the box
$('#lang').clone().insertAfter("#lang").before('<br>');
$('#prof').clone().insertAfter("#prof").before('<br>');
});
//this part here generates number 1-31 and adds into month and days
i=0;
for(i=1; i<=31; i++){
$('#dayselect').append($('<option>', {value:i, text:i}));
if(i<=12){
$('#monthselect').append($('<option>', {value:i, text:i}));
}
}
//this code here generates years, will work for the last, 120 years
year=(new Date).getFullYear()-120;
i = (new Date).getFullYear()-16;
for(i; i>=year; i--){
$('#yearselect').append($('<option>', {value:i, text:i}));
}
//Regex Patterns
var pass = /^[a-z0-9\.\-\)\(\_)]+$/i;
var uname = /^[a-z0-9\.\-]+$/i;
var mname = /^[a-z ]+$/i;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
//When the Last Name texbox is changing this will be invoked
$("#fname").keydown(function(){
//comparing the above regex to the value in the texbox, if not from the box then send error
if(!mname.test($("#fname").val())){
//fill the textbox label with error
document.getElementById("fname_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid FirstName</font>";
$("#fname").css("border-color","rgba(255,0,0,.6)");
works=false;
}
else{
$("#fname").css("border-color","rgba(0,255,100,.6)");
document.getElementById("fname_error").innerHTML="";
works = true;
}
});//end of fname onchange
//When the Last Name texbox is changint this will be invoked
$("#lname").keydown(function(){
//comparing the above regex to the value in the texbox
if(!mname.test($("#lname").val())){
//fill the textbox label with error
document.getElementById("lname_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid LastName</font>";
$("#lname").css("border-color","rgba(255,0,0,.6");
works=false;
}
else{
$("#lname").css("border-color","rgba(0,255,100,.6)");
document.getElementById("lname_error").innerHTML="";
works = true;
}
});//end of lname on change
//When the userid textbox is chaning,this will be invoked
$("#userid").keydown(function(){
//comparing the above regex to the value in the texbox
if(!uname.test($("#userid").val())){
//fill the textbox label with error
document.getElementById("userid_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid UserId</font>";
$("#userid").css("border-color","rgba(255,0,0,.6");
works=false;
}
/*
else if($("#userid").val().length<4){
//fill the textbox label with error
document.getElementById("userid_error").innerHTML="<font color='red' size='2px' family='verdana'>Minimum user length is 4</font>";
$("#userid").css("border-color","rgba(255,0,0,.6");
//disable the submit button
//$('#submitbtn').attr('disabled','disabled');
works=false;
}
*/
else{
$("#userid").css("border-color","rgba(0,0,0,.3)");
$.post("user_test/user_email_test.php",
{
// userid: $("#userlogin").val(),
userid: $("#userid").val(),
},
function(data,status){
document.getElementById("userid_error").innerHTML=data;
});
works = true;
}
});//end of change
//When the userid textbox is chaning,this will be invoked
$("#memail").keydown(function(){
//comparing the above regex to the value in the texbox
if(!emailReg.test($("#memail").val())){
//fill the textbox label with error
document.getElementById("email_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid Email</font>";
$("#memail").css("border-color","rgba(255,0,0,.6");
works=false;
}
else{
works = true;
$.post("./user_test/user_email_test.php",{
useremail: $("#memail").val(),
},
function(data,status){
document.getElementById("email_error").innerHTML=data;
$("#memail").css("border-color","rgba(0,255,0,.3)");
works = true;
});
}
});//end of change
//When the userid textbox is chaning,this will be invoked
$("#pwd2").keyup(function(){
//checking length of the password
if($("#pwd2").val().length<10){
document.getElementById("pwd_error").innerHTML="<font color='red' size='2px' family='verdana'>Please enter a password minimum 10 characters</font>";
//$('#submitbtn').attr('disabled','disabled');
$("#pwd1, pwd2").css("border-color","rgba(0,255,100,.6)");
works=false;
}
//checking if the password matches
else if($("#pwd1").val()!=$("#pwd2").val()){
document.getElementById("pwd_error").innerHTML="<font color='red' size='2px' family='verdana'>Passwords do not match</font>";
//$('#submitbtn').attr('disabled','disabled');
works=false;
$("#pwd1, pwd2").css("border-color","rgba(0,255,100,.6)");
}
else{
$("#pwd1, #pwd2").css("border-color","rgba(0,0,0,.3)");
document.getElementById("pwd_error").innerHTML="";
//comparing the above regex to the value in the texbox and checking if the lenght is atleast 10
if(!pass.test($("#pwd2").val())){
//fill the textbox label with error
document.getElementById("pwd_error").innerHTML="<font color='red' size='1px' family='verdana'>Your password contains invalid character, Please use: a-z 0-9.( )_- only</font>";
$("#pwd1, #pwd2").css("border-color","rgba(255,0,0,.6");
works = false;
}
else{
$("#pwd1 , #pwd2").css("border-color","rgba(0,255,100,.6)");
works = true;
}
}
});//end of change
});//end of document ready
</script>

How to prevent submitting the HTML form's input field value if it empty

I have HTML form with input fields. Some of inputs can be empty, i.e. the value is "".
<input name="commentary" value="">
Just now, when commentary field is not set, it appears in submit url like: &commentary=
How I can remove empty inputs from the submit url, so when the commentary input is empty it would not be passed at all.
Thank you very much.
Update
Thanks to minitech answer, I could resolve it. JavaScript code is below:
$('#my-form-id').submit(function() {
var commentary = $('#commentary').val();
if (commentary === undefined || commentary === "") {
$('#commentary').attr('name', 'empty_commentary');
} else {
$('#commentary').attr('name', 'commentary');
}
});
The only reason I have prefixed field name with "empty_" is that IE passes empty name in URL anyway.
This can only be done through JavaScript, as far as I know, so if you rely on this functionality you need to restructure. The idea, anyway, is to remove the name attribute from inputs you don’t want included:
jQuery:
$('#my-form-id').submit(function () {
$(this)
.find('input[name]')
.filter(function () {
return !this.value;
})
.prop('name', '');
});
No jQuery:
var myForm = document.getElementById('my-form-id');
myForm.addEventListener('submit', function () {
var allInputs = myForm.getElementsByTagName('input');
for (var i = 0; i < allInputs.length; i++) {
var input = allInputs[i];
if (input.name && !input.value) {
input.name = '';
}
}
});
You might also want to reset the form afterwards, if you use a listener and cancel.
I prefer not to alter the input elements (changing their names, or flagging them as disabled and so), because if you go back you could get a broken form.
Here is my solution instead, which relies on FormData:
window.addEventListener('load', function() {
let forms = document.getElementsByClassName('skipEmptyFields');
for (let form of forms) {
form.addEventListener('formdata', function(event) {
let formData = event.formData;
for (let [name, value] of Array.from(formData.entries())) {
if (value === '') formData.delete(name);
}
});
}
});
You probably don't want to match radio buttons. And if the form contains select's, you'll need to match them too.
With jQuery, you might use something like this:
$('#form-id').submit(function() {
$(this).find('input[type!="radio"][value=""],select:not(:has(option:selected[value!=""]))').attr('name', '');
});
Instead of using a submit-type input, use a button-type input for form submission. The JavaScript handler for the button-type input should call form's submit() method after checking that commentary is non-empty. You should also alert the user to their mistake (better with a red text on the page rather than the pop-up produced by alert()).
Remember that you should not rely solely on client-side input validation, though since it is always possible to send the form from a modified page or directly in HTTP.
Thankyou #Ryan
This is my full solution for this.
I use Jersey and #BeanParam and this fixes the problem of "" & null inputs
$('#submitForm').click(function() {
var url = "webapi/?";
var myForm = document.getElementById('myFormId');
var allInputs = myForm.getElementsByTagName('input');
for (var i = 0; i < allInputs.length; i++) {
var input = allInputs[i];
if (input.value != "" && input.name != "submitForm") {
url += input.name +'='+input.value+'&';
}
}
console.log(url);
$.ajax({
method : "GET",
url : url,
data : {
// data : "json",
// method: "GET"
},
success : function(data) {
console.log("Responce body from Server: \n" + JSON.stringify(data));
$("#responce").html("");
$("#responce").html(JSON.stringify(data));
},
error : function(jqXHR, textStatus, errorThrown) {
console.log(textStatus);
console.log('Error: ' + errorThrown);
}
});
});

Obtain form input fields using jQuery?

I have a form with many input fields.
When I catch the submit form event with jQuery, is it possible to get all the input fields of that form in an associative array?
$('#myForm').submit(function() {
// get all the inputs into an array.
var $inputs = $('#myForm :input');
// not sure if you wanted this, but I thought I'd add it.
// get an associative array of just the values.
var values = {};
$inputs.each(function() {
values[this.name] = $(this).val();
});
});
Thanks to the tip from Simon_Weaver, here is another way you could do it, using serializeArray:
var values = {};
$.each($('#myForm').serializeArray(), function(i, field) {
values[field.name] = field.value;
});
Note that this snippet will fail on <select multiple> elements.
It appears that the new HTML 5 form inputs don't work with serializeArray in jQuery version 1.3. This works in version 1.4+
Late to the party on this question, but this is even easier:
$('#myForm').submit(function() {
// Get all the forms elements and their values in one step
var values = $(this).serialize();
});
The jquery.form plugin may help with what others are looking for that end up on this question. I'm not sure if it directly does what you want or not.
There is also the serializeArray function.
Sometimes I find getting one at a time is more useful. For that, there's this:
var input_name = "firstname";
var input = $("#form_id :input[name='"+input_name+"']");
$('#myForm').bind('submit', function () {
var elements = this.elements;
});
The elements variable will contain all the inputs, selects, textareas and fieldsets within the form.
Here is another solution, this way you can fetch all data about the form and use it in a serverside call or something.
$('.form').on('submit', function( e )){
var form = $( this ), // this will resolve to the form submitted
action = form.attr( 'action' ),
type = form.attr( 'method' ),
data = {};
// Make sure you use the 'name' field on the inputs you want to grab.
form.find( '[name]' ).each( function( i , v ){
var input = $( this ), // resolves to current input element.
name = input.attr( 'name' ),
value = input.val();
data[name] = value;
});
// Code which makes use of 'data'.
e.preventDefault();
}
You can then use this with ajax calls:
function sendRequest(action, type, data) {
$.ajax({
url: action,
type: type,
data: data
})
.done(function( returnedHtml ) {
$( "#responseDiv" ).append( returnedHtml );
})
.fail(function() {
$( "#responseDiv" ).append( "This failed" );
});
}
Hope this is of any use for any of you :)
http://api.jquery.com/serializearray/
$('#form').on('submit', function() {
var data = $(this).serializeArray();
});
This can also be done without jQuery using the XMLHttpRequest Level 2 FormData object
http://www.w3.org/TR/2010/WD-XMLHttpRequest2-20100907/#the-formdata-interface
var data = new FormData([form])
Had a similar issue with a slight twist and I thought I'd throw this out. I have a callback function that gets the form so I had a form object already and couldn't easy variants on $('form:input'). Instead I came up with:
var dataValues = {};
form.find('input').each(
function(unusedIndex, child) {
dataValues[child.name] = child.value;
});
Its similar but not identical situation, but I found this thread very useful and thought I'd tuck this on the end and hope someone else found it useful.
This piece of code will work
instead of name, email enter your form fields name
$(document).ready(function(){
$("#form_id").submit(function(event){
event.preventDefault();
var name = $("input[name='name']",this).val();
var email = $("input[name='email']",this).val();
});
});
Associative? Not without some work, but you can use generic selectors:
var items = new Array();
$('#form_id:input').each(function (el) {
items[el.name] = el;
});
jQuery's serializeArray does not include disabled fields, so if you need those too, try:
var data = {};
$('form.my-form').find('input, textarea, select').each(function(i, field) {
data[field.name] = field.value;
});
Don't forget the checkboxes and radio buttons -
var inputs = $("#myForm :input");
var obj = $.map(inputs, function(n, i) {
var o = {};
if (n.type == "radio" || n.type == "checkbox")
o[n.id] = $(n).attr("checked");
else
o[n.id] = $(n).val();
return o;
});
return obj
Seems strange that nobody has upvoted or proposed a concise solution to getting list data. Hardly any forms are going to be single-dimension objects.
The downside of this solution is, of course, that your singleton objects are going to have to be accessed at the [0] index. But IMO that's way better than using one of the dozen-line mapping solutions.
var formData = $('#formId').serializeArray().reduce(function (obj, item) {
if (obj[item.name] == null) {
obj[item.name] = [];
}
obj[item.name].push(item.value);
return obj;
}, {});
$("#form-id").submit(function (e) {
e.preventDefault();
inputs={};
input_serialized = $(this).serializeArray();
input_serialized.forEach(field => {
inputs[field.name] = field.value;
})
console.log(inputs)
});
I had the same problem and solved it in a different way.
var arr = new Array();
$(':input').each(function() {
arr.push($(this).val());
});
arr;
It returns the value of all input fields. You could change the $(':input') to be more specific.
Same solution as given by nickf, but with array input names taken into account
eg
<input type="text" name="array[]" />
values = {};
$("#something :input").each(function() {
if (this.name.search(/\[\]/) > 0) //search for [] in name
{
if (typeof values[this.name] != "undefined") {
values[this.name] = values[this.name].concat([$(this).val()])
} else {
values[this.name] = [$(this).val()];
}
} else {
values[this.name] = $(this).val();
}
});
I hope this is helpful, as well as easiest one.
$("#form").submit(function (e) {
e.preventDefault();
input_values = $(this).serializeArray();
});
If you need to get multiple values from inputs and you're using []'s to define the inputs with multiple values, you can use the following:
$('#contentform').find('input, textarea, select').each(function(x, field) {
if (field.name) {
if (field.name.indexOf('[]')>0) {
if (!$.isArray(data[field.name])) {
data[field.name]=new Array();
}
data[field.name].push(field.value);
} else {
data[field.name]=field.value;
}
}
});
Inspired by answers of Lance Rushing and Simon_Weaver, this is my favourite solution.
$('#myForm').submit( function( event ) {
var values = $(this).serializeArray();
// In my case, I need to fetch these data before custom actions
event.preventDefault();
});
The output is an array of objects, e.g.
[{name: "start-time", value: "11:01"}, {name: "end-time", value: "11:11"}]
With the code below,
var inputs = {};
$.each(values, function(k, v){
inputs[v.name]= v.value;
});
its final output would be
{"start-time":"11:01", "end-time":"11:01"}
I am using this code without each loop:
$('.subscribe-form').submit(function(e){
var arr=$(this).serializeArray();
var values={};
for(i in arr){values[arr[i]['name']]=arr[i]['value']}
console.log(values);
return false;
});
For multiple select elements (<select multiple="multiple">), I modified the solution from #Jason Norwood-Young to get it working.
The answer (as posted) only takes the value from the first element that was selected, not all of them. It also didn't initialize or return data, the former throwing a JavaScript error.
Here is the new version:
function _get_values(form) {
let data = {};
$(form).find('input, textarea, select').each(function(x, field) {
if (field.name) {
if (field.name.indexOf('[]') > 0) {
if (!$.isArray(data[field.name])) {
data[field.name] = new Array();
}
for (let i = 0; i < field.selectedOptions.length; i++) {
data[field.name].push(field.selectedOptions[i].value);
}
} else {
data[field.name] = field.value;
}
}
});
return data
}
Usage:
_get_values($('#form'))
Note: You just need to ensure that the name of your select has [] appended to the end of it, for example:
<select name="favorite_colors[]" multiple="multiple">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
When I needed to do an ajax call with all the form fields, I had problems with the :input selector returning all checkboxes whether or not they were checked. I added a new selector to just get the submit-able form elements:
$.extend($.expr[':'],{
submitable: function(a){
if($(a).is(':checkbox:not(:checked)'))
{
return false;
}
else if($(a).is(':input'))
{
return true;
}
else
{
return false;
}
}
});
usage:
$('#form_id :submitable');
I've not tested it with multiple select boxes yet though but It works for getting all the form fields in the way a standard submit would.
I used this when customising the product options on an OpenCart site to include checkboxes and text fields as well as the standard select box type.
serialize() is the best method. # Christopher Parker say that Nickf's anwser accomplishes more, however it does not take into account that the form may contain textarea and select menus. It is far better to use serialize() and then manipulate that as you need to. Data from serialize() can be used in either an Ajax post or get, so there is no issue there.
Hope this helps somebody. :)
// This html:
// <form id="someCoolForm">
// <input type="text" class="form-control" name="username" value="...." />
//
// <input type="text" class="form-control" name="profile.first_name" value="...." />
// <input type="text" class="form-control" name="profile.last_name" value="...." />
//
// <input type="text" class="form-control" name="emails[]" value="..." />
// <input type="text" class="form-control" name="emails[]" value=".." />
// <input type="text" class="form-control" name="emails[]" value="." />
// </form>
//
// With this js:
//
// var form1 = parseForm($('#someCoolForm'));
// console.log(form1);
//
// Will output something like:
// {
// username: "test2"
// emails:
// 0: ".#....com"
// 1: "...#........com"
// profile: Object
// first_name: "..."
// last_name: "..."
// }
//
// So, function below:
var parseForm = function (form) {
var formdata = form.serializeArray();
var data = {};
_.each(formdata, function (element) {
var value = _.values(element);
// Parsing field arrays.
if (value[0].indexOf('[]') > 0) {
var key = value[0].replace('[]', '');
if (!data[key])
data[key] = [];
data[value[0].replace('[]', '')].push(value[1]);
} else
// Parsing nested objects.
if (value[0].indexOf('.') > 0) {
var parent = value[0].substring(0, value[0].indexOf("."));
var child = value[0].substring(value[0].lastIndexOf(".") + 1);
if (!data[parent])
data[parent] = {};
data[parent][child] = value[1];
} else {
data[value[0]] = value[1];
}
});
return data;
};
All answers are good, but if there's a field that you like to ignore in that function? Easy, give the field a property, for example ignore_this:
<input type="text" name="some_name" ignore_this>
And in your Serialize Function:
if(!$(name).prop('ignorar')){
do_your_thing;
}
That's the way you ignore some fields.
Try the following code:
jQuery("#form").serializeArray().filter(obje =>
obje.value!='').map(aobj=>aobj.name+"="+aobj.value).join("&")

Categories

Resources