Send only filled fields via GET - javascript

Look at simple form below:
<form method="GET" action="index.php">
<input type="text" name="price_min" >Min
<input type="text" name="price_max" >Max
</form>
When I send form with filled only one field, in my url I get empty values for not filled keys
(ex. index.php?price_min=).
Question:
How to remove empty keys from url?

You can parse serialized string and remove blank values. Then you can use post to necessary api using jQuery.
Sample
JSFiddle
$("#btn").on("click", function() {
var formjson = $("#frmTest").serialize();
var result = formjson.split("&").filter(function(val) {
return val.split("=")[1].length > 0;
}).join("&")
console.log("Serialized String:", formjson);
console.log("Processed String:", result);
// $.get('action.php', formjson, function(response){ ... })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form id="frmTest">
<input type="text" name="price_min">Min
<input type="text" name="price_max">Max
</form>
<button id="btn">Test Serialize</button>

Use jQuery to send the fields like this
$('your_form').submit(function() {
var min_price = $("#min_price").val();
var max_price = $("#max_price").val();
var string = "";
if(min_price.length > 0){
string += "min_price="+min_price
}
if(max_price.length > 0){
string += "&max_price="+max_price
}
window.location.href = 'index.php?'+string;
});
Hope it helps!

Related

Serialize form and change input names (remove the array part of the input names)

I want to serialize my html form and submit it to my sever via ajax, but before submitting the form, I want to rename the variable names and remove the initiali part, which is: BranchViewModels[0]. for example, I want to change:
change: BranchViewModels[0].BranchName to: BranchName
change: BranchViewModels[1].AddressViewModel.AddressId to : AddressViewModel.AddressId
Basically when I generate form, all the input names are rendered as an array, but before submitting the form, I want to get rid of array section of the input name (BranchViewModels[0]. in this example).
I have explained why I am doing this here
I have also created a jsfiddle for the following example.
function updateBranch() {
$('.save-branch-button').click(function() {
var branchForm = $(this).closest('form');
var serializedform = branchForm.find('.form :input').serialize();
alert('I want to change the input names in this serialized form: \n\n' + serializedform );
// 1. iterated through serialized form
//
// remove BranchViewModels[i]. from the name, e.g.
// replace: BranchViewModels[0].BranchName
// with: BranchName
// 2. Submit the form
/* $.ajax({
url: "/my-server",
data: {branchViewModel: <-- serialized model},
dataType: 'json',
type: "POST"}); */
});
}
jQuery(document).ready(function($) {
updateBranch();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onsubmit="return false;" novalidate="novalidate">
<div class="form">
<div class="form-group">
<label>Branch name</label>
<input class="form-control" data-val="true" id="BranchViewModels_0__BranchName" name="BranchViewModels[0].BranchName" type="text" value="branch 1">
</div>
<hr />
<div class="form-group">
<label>Branch location</label>
<div>
<input data-val="true" id="BranchViewModels_0__AddressViewModel_AddressId" name="BranchViewModels[0].AddressViewModel.AddressId" value="1956">
</div>
<div>
<input class="address-street-address" data-val="true" id="BranchViewModels_0__AddressViewModel_StreetAddress" name="BranchViewModels[0].AddressViewModel.StreetAddress" value="Wellington 6011, New Zealand">
</div>
</div>
<input type="button" class="btn btn-primary-action save-branch-button" value="Save">
</div>
</form>
function updateBranch() {
$('.save-branch-button').click(function() {
var branchForm = $(this).closest('form');
var serializedform = branchForm.find('.form :input').serializeArray();
console.log(serializedform);
const obj = {};
for(let d of serializedform){
obj[d.name.split('.').pop()] = d.value
}
console.log(obj);
}
Return serialize data to Deserialize then change to you want anything Hope this help you.
console.log(deparam(serializedform));
function deparam(query) {
var pairs, i, keyValuePair, key, value, map = {};
// remove leading question mark if its there
if (query.slice(0, 1) === '?') {
query = query.slice(1);
}
if (query !== '') {
pairs = query.split('&');
for (i = 0; i < pairs.length; i += 1) {
keyValuePair = pairs[i].split('=');
key = decodeURIComponent(keyValuePair[0]);
value = (keyValuePair.length > 1) ? decodeURIComponent(keyValuePair[1]) : undefined;
map[key] = value;
}
}
return map;
}

jQuery adding variable content into DIV

I am creating contact form on my website, but i got stuck. I don't know how to put content from variable after each inputs on my website. I can show them into console.log and works perfect but i don't know how to put it on website.
Here's the code:
(function($) {
$(document).ready(function() {
var form = $(".contact_form"),
fields = $("[data-error]");
fields.on("click", function() {
$(this).removeAttr('placeholder');
});
fields.on("blur", function() {
var field = $(this);
field.toggleClass("form_error", $.trim(field.val()) === "");
});
form.on("submit", function(e) {
var hasErrors = false;
fields.each(function(i, elem) {
var field = $(elem),
empty = $.trim(field.val()) === "",
errors = field.data("error");
console.log(errors);
// HERE IS ERROR VAR
// sth here to put it into html
field.toggleClass("form_error", empty);
if (empty) {
hasErrors = true;
}
});
if (!hasErrors) {
form.submit();
} else {
e.preventDefault();
}
});
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" accept-charset="utf-8" class="contact_form">
<input type="text" placeholder="Imię" data-error="Podaj imię">
<input type="text" placeholder="Nazwisko" data-error="Podaj nazwisko">
<input type="email" placeholder="E-mail" data-error="Podaj poprawny adres e-mail">
<input type="text" placeholder="Kontakt" data-error="Podaj poprawny numer telefonu">
<textarea name="message" class="textarea_field" placeholder="WIADOMOŚĆ" data-error="Wpisz treść wiadomości"></textarea>
<button type="submit" class="przycisk">Wyślij</button>
</form>
Firstly note that presumably you're trying to check that the fields all have a value. If so, you should put the error message generation logic in the if (empty) code block.
To actually create the HTML for the messages you can use the after() method to insert the error messages after the related input element. If you also wrap the errors in an element, such as a span, which has a class you can easily use that to remove() the elements when the form is submit to be re-evaluated. Try this:
(function($) {
$(document).ready(function() {
var form = $(".contact_form"),
fields = $("[data-error]");
fields.on("click", function() {
$(this).removeAttr('placeholder');
});
fields.on("blur", function() {
var field = $(this);
var valid = $.trim(field.val()) !== "";
field.toggleClass("form_error", !valid).next('span.form_error').remove();
if (!valid)
field.after('<span class="form_error">' + $(this).data('error') + '</span>'); // add new error messages
});
form.on("submit", function(e) {
var hasErrors = false;
$('span.form_error').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('<span class="form_error">' + errors + '</span>'); // add new error messages
field.toggleClass("form_error", empty);
}
});
if (!hasErrors) {
form.submit();
} else {
e.preventDefault();
}
});
});
})(jQuery);
span.form_error {
color: #C00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" accept-charset="utf-8" class="contact_form">
<input type="text" placeholder="Imię" data-error="Podaj imię">
<input type="text" placeholder="Nazwisko" data-error="Podaj nazwisko">
<input type="email" placeholder="E-mail" data-error="Podaj poprawny adres e-mail">
<input type="text" placeholder="Kontakt" data-error="Podaj poprawny numer telefonu">
<textarea name="message" class="textarea_field" placeholder="WIADOMOŚĆ" data-error="Wpisz treść wiadomości"></textarea>
<button type="submit" class="przycisk">Wyślij</button>
</form>
Use text() for adding string to element or html() for adding html code.
Example:
var text = 'hello world';
$('div#textHere').text(text);
var htmlCode = "<strong>Hello</strong> World";
$('div#htmlHere').html(htmlCode);
Documentation for text() and for html().
When you want to get form field values you use $('#id').val(); the val will get value from form fields. And then you can use $('#id').html('Enter val here') that's it.
use can use text() or html()
Different:
1)If you retrieve text only, u can use text()
2)If you retrieve html element with text, then u can use html();
Eg 1 : -
var text1="hello world";
$(".text").text(text1) ==> hello world
$(".text").html(text1) ==> hello world
Eg 2 : -
var text2="<h1>hello world</h1>";
$(".text").text(text2) ==> '< h1>hello world< /h1>'
$(".text").html(text2) ==>hello world`

How can send array as an data using ajax

Please see attached jsfiddle link, I need to collect data from multiple forms and combined the data as Single data array send it to server(spring mvc controller) to persist using ajax.post
Please let me know best way to do it, will my array be converted to Json by ajax call or I have to do some magic on it.
Thanks
http://jsfiddle.net/6jzwR/1/
<form id="form1" name="formone" class="myclass">
<input type="text" id="txt11" name="txt11" value="name1" />
<input type="text" id="txt12" name="txt12" value="name2" />
</form>
<form id="form1" name="formtwo" class="myclass">
<input type="text" id="txt21" name="txt21" value="name3" />
<input type="text" id="txt22" name="txt22" value="name4" />
</form>
<input type="button" id="button" value="Click Me" />
(function ($) {
$(document).ready(function () {
alert("serialize data :" + $('.myclass').length);
var mydata = null;
$('#button').on('click', function (e) {
$('.myclass').each(function () {
alert("serialize data :" + $(this).serialize());
if ((mydata === null) || (mydata === undefined)) {
mydata = $(this).serializeArray();
alert("My data is null");
} else {
mydata = $.merge(mydata, $(this).serializeArray());
alert("My data final data after merger " + test);
}
});
});
});
}(jQuery));
Try this:
var array = $('input[type="text"]').map(function() {
return $(this).val();
}).get();
alert(JSON.stringify(array));
Demo.
You can put all the forms' data in an array and join them with &
var formdata = []
$('.myclass').each(function(){
formdata.push($(this).serialize());
});
var data = formdata.join('&');
http://jsfiddle.net/6jzwR/3/

How do I keep the previous value sent to JSON?

I would like to store the value of a input to JSON (on submit). If the User fill out the input again then submit I would like to add the new value to JSON keeping the previous one.
I use the following to add the input value to JSON but I'm not sure how to keep the previous value sent to JSON.
http://jsfiddle.net/ABE4T/
HTML:
<form method="post" name="myForm" id="myForm">
<input type="text" name="element" />
<input type="submit" value="Add" name="submit" />
</form>
<div id="display"></div>
Javascript:
$.fn.serializeObject = function()
{
var arrayData = this.serializeArray();
var objectData = {};
$.each(arrayData, function(){
if(objectData[this.name] != null){
if(!objectData[this.name].push){
objectData[this.name] = [objectData[this.name]];
}
objectData[this.name].push(this.value || '');
}
else{
objectData[this.name] = this.value || '';
}
});
return objectData;
};
$(document).ready(function(){
$("#myForm").submit(function(){
$('#display').text(JSON.stringify($("#myForm").serializeObject()));
return false;
});
});
Use .append() function instead of .text() function.
DEMO fiddle
You can maintain an array to hold all the values like this
$(document).ready(function(){
var values = [];
$("#myForm").submit(function(){
values.push($("#myForm").serializeObject());
$('#display').text(JSON.stringify(values));
return false;
});
});
Working Fiddle
You are overwriting the value in #display.
Change this line
$('#display').text(JSON.stringify($("#myForm").serializeObject()));
to
$('#display').text($('#display').text() + JSON.stringify($("#myForm").serializeObject()));
Fiddle

how to add the input values in an array

i just like to ask regarding adding data in a array. But the data which i wanted to put is from a table of input boxes.. Here's the code that i've been practicing to get data:
http://jsfiddle.net/yajeig/4Nr9m/69/
I have an add button that everytime I click that button, it will store data in my_data variable.
i want to produce an output in my variable something like this:
my_data = [ {plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"}]
and if i would add another data again, it will add in that variable and it be something like this:
my_data = [ {plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"},
{plank:"2",thickness:"5",width:"6",length:"2",qty:"1",brdFt:"50"}]
the code that i have right now is really bad, so please help.
Currently my output:
1,4,6,4,1
You should be able to iterate over all of the textboxes using the following:
function add(e) {
var obj = {};
$('#addItem input[type="text"]')
.each(function(){obj[this.name] = this.value;});
myItems.push(obj);
}
Where myItems is a global container for your items and #addItem is your form.
Updated jsfiddle.
If you use a form and a submit button then you should be able to implement a non-JavaScript method to add your information so that the site will be accessible to people without JavaScript enabled.
Try this, sorry for modifying your form, but it works well:
HTML:
<form method="post" action="#" id="add_plank_form">
<p><label for="plank_number">Plank number</label>
<p><input type="text" name="plank_number" id="plank_number"/></p>
<p><label for="plank_width">Width</label>
<p><input type="text" name="plank_width" id="plank_width"/></p>
<p><label for="plank_length">Length</label>
<p><input type="text" name="plank_length" id="plank_length"/></p>
<p><label for="plank_thickness">Thickness</label>
<p><input type="text" name="plank_thickness" id="plank_thickness"/></p>
<p><label for="plank_quantity">Quantity</label>
<p><input type="text" name="plank_quantity" id="plank_quantity"/></p>
<p><input type="submit" value="Add"/>
</form>
<p id="add_plank_result"></p>
Javascript:
$(document).ready(function() {
var plank_data = Array();
$('#add_plank_form').submit(function() {
// Checking data
$('#add_plank_form input[type="text"]').each(function() {
if(isNaN(parseInt($(this).val()))) {
return false;
}
});
var added_data = Array();
added_data.push(parseInt($('#plank_number').val()));
added_data.push(parseInt($('#plank_width').val()));
added_data.push(parseInt($('#plank_length').val()));
added_data.push(parseInt($('#plank_thickness').val()));
added_data.push(parseInt($('#plank_quantity').val()));
$('#add_plank_form input[type="text"]').val('');
plank_data.push(added_data);
// alert(JSON.stringify(plank_data));
// compute L x W x F for each plank data
var computed_values = Array();
$('#add_plank_result').html('');
for(var i=0; i<plank_data.length; i++) {
computed_values.push(plank_data[i][1] * plank_data[i][2] * plank_data[i][3] / 12);
$('#add_plank_result').append('<input type="text" name="plank_add[]" value="' + computed_values[i] + '"/>');
}
return false;
});
});
Iterate through all keys, and add the values.
(code written from mind, not tested)
var added = { };
for (var i = 0; i < my_data.length; i ++) {
var json = my_data[i];
for (var key in json) {
if (json.hasOwnProperty(key)) {
if (key in added) {
added[key] += json[key];
} else {
added[key] = json[key];
}
}
}
}
You can use the javascript array push function :
var data = [{plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"}];
var to_add = [{plank:"2",thickness:"5",width:"6",length:"2",qty:"1",brdFt:"50"}];
data = data.concat(to_add);
Sorry I only glanced at the other solutions.
$(document).ready(function() {
var myData=[];
var myObject = {}
$("input").each(function() {
myObject[this.id]=this.value
});
alert(myObject["plank"])
myData.push(myObject)
});

Categories