How do I keep the previous value sent to JSON? - javascript

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

Related

Possibility to find a clicked number in a value using jQuery

I want to learn, can we find the same number in two input values.
For example:
<input type="hidden" id="multinumber" value="1,2,3,4,5">
<input type="hidden" id="justonenumber" value="3">
<div class="click">Click and test the same number</div>
JS
$(document).ready(function(){
$("body").on("click",".click", function(){
var multiple = $("#multinumber").val();
var single = $("#justonenumber").val();
});
});
When onClick event on the .click button then check the same number in the #multinumber and #justonenumber input values and get the result in an alert box.
Is there a way to do this ? Anyone can help me here please?
Just use indexOf or includes on your multiple string. :)
$(document).ready(function(){
$("body").on("click",".click", function(){
var multiple = $("#multinumber").val();
var single = $("#justonenumber").val();
var doesMultipleIncludeSingle = multiple.includes(single);
// OR
var doesMultipleIncludeSingle = multiple.indexOf(single) > -1;
});
});
As per the problem explained in the comment, it seems the requirement does involve splitting the array.
$(document).ready(function(){
$("body").on("click",".click", function(){
var multiple = $("#multinumber").val().split(',');
var single = $("#justonenumber").val();
var doesMultipleIncludeSingle = multiple.includes(single);
// OR
var doesMultipleIncludeSingle = multiple.indexOf(single) > -1;
});
});
You can get the value of first input box. Split it by , and check with .indexOf for the other input. If it's there, you can put the result in alert box like
$(".click").click(function(){
var x = $("#multinumber").val().split(",");
var y = $("#justonenumber").val();
if(x.indexOf(y) > 0){
alert(x.find(o=> o==y))
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="hidden" id="multinumber" value="1,2,3,4,5">
<input type="hidden" id="justonenumber" value="3">
<div class="click">Click and test the same number</div>
is this what you want?
$(document).ready(function(){
$("body").on("click",".click", function(){
var multiple = $("#multinumber").val();
var single = $("#justonenumber").val();
if(multiple.indexOf(single) > -1) alert(single + " is found");
else alert(single + " isn't found");
});
});

Send only filled fields via GET

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!

Execute code when textboxes have data

I have a project which I have to calculate the coordenates between two points. The first coordenates are calculated once the user enters in three text boxes the street, province and city.
How can I execute the code I have in PHP once the user fills out all three boxes and not before?
<form name="form" action="" method="post">
<input type="text" name="provincia" id="provincia">
<input type="text" name="municipio" id="municipio">
<input type="text" name="calle" id="calle">
<input type="submit" value="¡Buscar!"/>
</form>
This is the form the user has to fill in. Once the user writes in all three (without mattering the order) I have php code which Im not sure if it can execute once these boxes have values.
What should I have to use to accomplish this? Ajax? Jquery? Javascript?
Not really sure,
thanks.
are you looking for this?
$(document).ready(function () {
var flag = false;
$("input[type=text]").change(function () {
flag = true;
$("input[type=text]").each(function () {
if ($(this).val().trim() == "") {
flag = false;
}
});
if (flag) {
alert("all have values");
$("input[type=submit]").trigger("click");
}
alert(values);
});
});
edit
<form name="form" action="" method="post">
<input type="text" class="tobeChecked" name="provincia" id="provincia">
<input type="text" class="tobeChecked" name="municipio" id="municipio">
<input type="text" class="tobeChecked" name="calle" id="calle">
<input type="submit" value="¡Buscar!"/>
</form>
$(document).ready(function () {
var flag = false;
$(".tobeChecked").change(function () {
var values = "";
flag = true;
$(".tobeChecked").each(function () {
values += $(this).val().trim() + "+";
if ($(this).val().trim() == "") {
flag = false;
}
});
if (flag) {
alert("all have values");
$("input[type=submit]").trigger("click");
}
});
});
Create a function to validate the required field for those three text boxes and once all are filled with values execute your script:
$('#provincia,#municipio,#calle').blur(function(){
if($('#provincia').val() !="" && $('#municipio').val() !="" && $('#calle').val() !=""){
// Do your process here
}
});
You can use jquery validate plugin to validate these 3 input fields on the client side itself, In that way, the user cannot submit the form until he completely fills the input fields.
Give your Button an ID like:
<input type="submit" id="button" value="¡Buscar!"/>
Then you can do this in JQuery:
$("#button").click(function(){
//Get the value of the fields
var textfield1 = document.getElementById("provincia").value;
var textfield2 = document.getElementById("municipio").value;
var textfield3 = document.getElementById("calle").value;
//Check if Values are filled
if ( !textfield1.match(/\S/) || !textfield2.match(/\S/) || !textfield3.match(/\S/))
{
//execute your script
}
I hope it helps.
use jquery .change() function
$( "#provincia" ).change(function() {
//you can do something here
alert( "Handler for .change() called." );
});

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/

Grab values from checked checkboxes and put them in an array using Javascript/jQuery

I want to get the values of checked checkboxes with the name="car_type[]" and alert the final array with all the values.
How to do that? So far, I have this code. But it's not working. I don't know how to loop through checked checkboxes properly and add the values to the array car_type_arr. I also cannot alert the final array using alert(car_type_arr);. Thanks for any help.
$().ready(function(){
$('.prettycheckbox').click(function(e) {
e.preventDefault();
var car_type_arr = [];
$("input:checkbox[name=car_type]:checked").each(function()
{
// here I need to add values to array like in php
// e.g. $car_type_arr[] = $the_grabbed_value;
// but using javascript syntax
// How to do that?
});
// then I need to alert the array, how to do that in JS?
alert(car_type_arr);
return false;
});
});
You can use map
var car_type_arr = $("input:checkbox[name=car_type]:checked").map(function() {
return this.value;
}).get();
console.log(car_type_arr);
Try below code:
<input type="checkbox" name="chkBox" value="xxx">
<input type="checkbox" name="chkBox" value="xxx1">
<input type="checkbox" name="chkBox" value="xxx2">
<input type="button" id="btnBox">
$(document).ready(function(){
$("#btnBox").click(function(){
var car_type_arr = [];
$("input:checkbox[name=chkBox]:checked").each(function() {
car_type_arr.push($(this).val());
alert(car_type_arr);
});
});
});
Demo: http://jsfiddle.net/XDpBP/
Try this:
$("input:checkbox[name=car_type]:checked").each(function()
{
car_type_arr.push($(this).val());
});
your code should look like,
$().ready(function(){
$('.prettycheckbox').click(function(e) {
e.preventDefault();
var car_type_arr = [];
$("input:checkbox[name=car_type]").each(function()
{
if($(this).is(':checked')){
car_type_arr.push($(this).val());
}
});
alert(car_type_arr);
return false;
});
});
$("input:checkbox[name=car_type]:checked").each(function() {
car_type_arr.push($(this).val());
});

Categories