How do i modify this code to get the intended outcome.
This is what i get from this code.
{"name":"abc","identifier":"abc_one","number":"55","description":"This is a description"}
But i want a json object like this,
{"project":
{"name":"abc",
"identifier":"abc_one",
"number":"55",
"description":"This is a description"}
}
Please look at the code i have at the moment. It Need to be warped by a another object call "project".
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$('form').submit(function() {
$('#result').text(JSON.stringify($('form').serializeObject()));
return false;
});
});
<form action="" method="post">
First Name:<input type="text" name="name" maxlength="12" size="12"/> <br/>
Last Name:<input type="text" name="identifier" maxlength="36" size="12"/> <br/>
number:<input type="number" name="number" maxlength="36" size="12"/> <br/>
<textarea wrap="physical" cols="20" name="description" rows="5">Enter your favorite quote!</textarea><br/>
Select a Level of Education:<br/>
<p><input type="submit" /></p>
</form>
All you need to change is following
return o;
To
return {"project":o}
in serializeObject function.
Related
I am novice in JS , and following is the code I found on Stackoverflow itself Can someone please explain on how this serialization takes place in the function below, stepwise process? Also once the serealization is done , how to parse through the JSON object to retrieve the info in tabular form ?
JAVASCRIPT
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="demon.js"></script>
</head>
<body>
<h2>Form</h2>
<form action="" method="post">
First Name:<input type="text" name="Fname" maxlength="12" size="12"/> <br/>
Last Name:<input type="text" name="Lname" maxlength="36" size="12"/> <br/>
Gender:<br/>
Male:<input type="radio" name="gender" value="Male"/><br/>
Female:<input type="radio" name="gender" value="Female"/><br/>
Favorite Food:<br/>
Steak:<input type="checkbox" name="food[]" value="Steak"/><br/>
Pizza:<input type="checkbox" name="food[]" value="Pizza"/><br/>
Chicken:<input type="checkbox" name="food[]" value="Chicken"/><br/>
<textarea wrap="physical" cols="20" name="quote" rows="5">Enter your favorite quote!</textarea><br/>
Select a Level of Education:<br/>
<select name="education">
<option value="Jr.High">Jr.High</option>
<option value="HighSchool">HighSchool</option>
<option value="College">College</option></select><br/>
Select your favorite time of day:<br/>
<select size="3" name="TofD">
<option value="Morning">Morning</option>
<option value="Day">Day</option>
<option value="Night">Night</option></select>
<p><input type="submit" /></p>
</form>
<h2>JSON</h2>
<pre id="result">
</pre>
</body>
</html>
This is what the code is doing
// create a jQuery plugin
$.fn.serializeObject = function() {
// return object to store the values
var o = {};
// call serializeArray on the form to get [{name: 'something', value: 'something'}]
var a = this.serializeArray();
// iterate over the serialized array
$.each(a, function() {
// if the value has already been defined on the object
if (o[this.name] !== undefined) {
// check if the value is not an array
if (!o[this.name].push) {
// it's not so instantiate a new array with the value in it
o[this.name] = [o[this.name]];
}
// add the value to the array of values
o[this.name].push(this.value || '');
} else {
// we are dealing with a new value so set it to the json object
o[this.name] = this.value || '';
}
});
// return the json serialized object from the plugin
return o;
};
Contact form variables are not passing into javascript. basically javascript fail on validation. On debug, I am getting "undefined is not a function." I have several seperators on this page. If i put identical code inside a seperate page like "contact.html" variables pass into javascript.
My understanding is that HTML tag id="contact-form" for some reason does not pass into the function.
Java Script
function code_contactvalidation() {
// Add form.special data (required for validation)
$('form.special input, form.special textarea').each(function() {
this.data = {};
this.data.self = $(this);
var val = this.data.self.val();
this.data.label = (val && val.length) ? val : null;
this.data.required = this.data.self.attr('aria-required') == 'true';
});
// Special form focus & blur
$('form.special input, form.special textarea').focus(function() {
with (this.data) {
console.log('focusing');
if ( label && self.val() == label) self.val('');
else return;
}
}).blur(function() {
with (this.data) {
if ( label && self.val().length == 0 ) self.val(label)
else return;
}
});
// initialize captcha
var randomcaptcha = function() {
var random_num1=Math.round((Math.random()*10));
var random_num2=Math.round((Math.random()*10));
document.getElementById('num1').innerHTML=random_num1;
document.getElementById('num2').innerHTML=random_num2;
var n3 = parseInt(random_num1) * parseInt(random_num2);
$('#captcharesult').attr('value', n3);
$('#buttonsubmit').attr('value','Submit');
};
randomcaptcha();
//initialize vars for contact form
var sending = false,
sent_message = false;
$('#contact-form').each(function() {
var _this = this;
this.data = {};
this.data.self = $(this);
this.data.fields = {};
this.data.labels = {};
this.data.notification = this.data.self.find('.notification');
_.each(['name','email','subject'], function(name) {
_this.data.fields[name] = _this.data.self.find(_.sprintf('input[name=%s]', name));
_this.data.labels[name] = _this.data.fields[name].val();
});
}).validate({
errorPlacement: function() {},
highlight: function(element) { $(element).addClass('invalid'); },
unhighlight: function(element) { $(element).removeClass('invalid'); },
submitHandler: function(form) {
if (sending) return false;
if ( sent_message ) { alert('Your message has been sent, Thanks!'); return false; }
var field, valid = true;
with (form.data) {
_.each(fields, function(field, name) {
if ( $.trim(field.val()) == labels[name] ) { valid = false; field.addClass('invalid'); } else { field.removeClass('invalid'); }
});
}
if (valid) {
sending = true;
$('#ajax-loader').show();
form.data.self.ajaxSubmit({
error: function(errorres) {
$('#ajax-loader').hide();
randomcaptcha();
form.data.notification.removeClass('sucess').addClass('error').find('span:first-child').html('Unable to send message (Unknown server error)');
form.data.notification.animate({opacity: 100}).fadeIn(500);
},
success: function(res) {
sending = false;
$('#ajax-loader').hide();
if (res == 'success') {
sent_message = true;
form.data.notification.removeClass('error').addClass('success').find('span:first-child').html('Your message has been sent!');
form.data.notification.animate({opacity: 100}).fadeIn(500);
$('#formName').val("");
$('#formEmail').val("");
$('#formSubject').val("");
$('#formMessage').val("");
$('#formcheck').val("");
} else if (res == 'captchaerror') {
randomcaptcha();
form.data.notification.removeClass('sucess').addClass('error').find('span:first-child').html('Captcha Error');
form.data.notification.animate({opacity: 100}).fadeIn(500);
} else {
randomcaptcha();
form.data.notification.removeClass('sucess').addClass('error').find('span:first-child').html('Unable to send message (Unknown server error)');
form.data.notification.animate({opacity: 100}).fadeIn(500);
}
}
});
}
return false;
}
});
}
HTML
<section id="contact">
<div class="container">
<div class="row text-center">
<div id="principal" data-align="left">
<div class="form_group_contact">
<script type="text/javascript" src="js/jquery.validate.pack.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
<form class="contactForm special validate" id="contact-form" action="sendmsg.php" method="post">
<p><input id="formName" name="name" type="text" value="Name" class="required" /></p>
<p><input id="formEmail" name="email" type="text" value="Email" class="required email" /></p>
<p><input id="formSubject" name="subject" class="last required" type="text" value="Subject" /></p>
<p><textarea id="formMessage" name="message" class="required margin20" rows="4" cols="83"></textarea></p>
<div class="form_captcha margin20">
<p>Captcha Recognition (<span id="num1"></span> * <span id="num2"></span>) =
<input type="hidden" id="captcharesult" name="captcha_result" value=""/>
<input type="text" class="required number" maxlength="3" size="3" id="formcheck" name="captcha" value=""/>
</p>
</div>
<p class="notification" style="display: none;"><span></span> <span class="close" data-action="dismiss"></span></p>
<p><input type="submit" value="" class="margin20" id="buttonsubmit" /><img id="ajax-loader" alt="" src="./images/ajax-loader.gif" /></p>
</form>
</div>
</div>
</div>
</div>
</section>
if ( label && self.val().length == 0 ) self.val(label)
There needs to be a semicolumn (;) to end that line ;)
Also, you call "each" on the contact-form which makes me think you expect more than one contact-form. You will need to set the identifier as "class" rather than "id" in the HTML and use "." in the jQuery selector rather than "#".
Now you got those little things fixed, please try it out in Firefox. Google is very vague with javascript errors, Firefox will give you a better error message. Please share it with us so I can edit this post with a final solution.
So, I have this code
<script>
function validate(f) {
var ok = true;
if (f.id.value === '' || f.id.value === null) {
ok = false;
}
return ok;
}
function validate2(f) {
var ok = true;
if (f.name.value === '' || f.name.value === null) {
ok = false;
}
return ok;
}
</script>
<form action="#" method="post">
<input type="text" name="id"/>
<input type="text" name="name"/>
<input type="submit" name="send_id" value="Send ID"/>
<input type="submit" name="send_name" value="Send Name"/>
</form>
How can I do it to validate the form depending on which submit is used?
I want to execute validate(); if the Send Id button is clicked and validate2() if we use the other one.
You can do this:
<form id="myForm" action="#" method="post">
<input type="text" name="id"/>
<input type="text" name="name"/>
<input type="submit" name="send_id" value="Send ID" onclick="return validate();" />
<input type="submit" name="send_name" value="Send Name" onclick="return validate2();" />
</form>
This way when your functions return false (meaning the form is not valid) the submit is interrupted.
And get your f parameter manually.
function getForm() {
return document.getElementById("myForm");
}
function validate() {
var f = getForm();
var ok = true;
if (f.id.value === '' || f.id.value === null) {
ok = false;
}
return ok;
}
function validate2() {
var f = getForm();
var ok = true;
if (f.name.value === '' || f.name.value === null) {
ok = false;
}
return ok;
}
You have to give an id to your form as show above.
Have another function as checkValidate() or something as you like and check it on click of both the buttons
<script>
function checkValidate(buttonName) {
if(buttonName == 'send_id'){
return validate();
}else{
return validate2();
}
}
function validate() {
var ok = true;
if (f.id.value === '' || f.id.value === null) {
ok = false;
}
return ok;
}
function validate2() {
var ok = true;
if (f.name.value === '' || f.name.value === null) {
ok = false;
}
return ok;
}
</script>
<form action="#" method="post">
<input type="text" name="id"/>
<input type="text" name="name"/>
<input type="submit" name="send_id" value="Send ID" onclick="return checkValidate(this.name)"/>
<input type="submit" name="send_name" value="Send Name" onclick="return checkValidate(this.name)"/>
</form>
I hope it helps...
Not tested.. but something like that...
$( "input[name='send_id']" ).click(function(event) {
event.preventDefault()
validate();
$("form").submit();
});
$( "input[name='send_name']" ).click(function(event) {
event.preventDefault()
validate2();
$("form").submit();
});
Is there a way to simplify my javascript code below?
It works but I am quite sure that there must be a way to reduce what evidently shows my elementary javascript skills, and of course, I am trying to improve my understanding.
My HTML Code is just a simple form:
<div>
<form action="">
<input type="text" name="firstname" id="un1" value="First Name"/>
<input type="text" name="surname" id="un2" value="Surname" />
<input type="text" name="username" id="un3" value="Email Address"/>
<input type="button" value="Register!" />
</form>
</div>
My Javascript Code (unobtrusive):
window.onload = function(){
//Field Manoeuvre1
document.getElementById("un1").onclick = fieldClear1;
document.getElementById("un1").onfocus = fieldClear1;
document.getElementById("un1").onblur = fieldReplace1;
//Field Manoeuvre2
document.getElementById("un2").onclick = fieldClear2;
document.getElementById("un2").onfocus = fieldClear2;
document.getElementById("un2").onblur = fieldReplace2;
//Field Manoeuvre3
document.getElementById("un3").onclick = fieldClear3;
document.getElementById("un3").onfocus = fieldClear3;
document.getElementById("un3").onblur = fieldReplace3;
}
//Field Manoeuvre1
function fieldClear1(){
if(document.getElementById("un1").value == "First Name"){
document.getElementById("un1").value = "";
}
}
function fieldReplace1(){
if(document.getElementById("un1").value == ""){
document.getElementById("un1").value = "First Name";
}
}
//Field Manoeuvre2
function fieldClear2(){
if(document.getElementById("un2").value == "Surname"){
document.getElementById("un2").value = "";
}
}
function fieldReplace2(){
if(document.getElementById("un2").value == ""){
document.getElementById("un2").value = "Surname";
}
}
//Field Manoeuvre3
function fieldClear3(){
if(document.getElementById("un3").value == "Email Address"){
document.getElementById("un3").value = "";
}
function fieldReplace3(){
if(document.getElementById("un3").value == ""){
document.getElementById("un3").value = "Email Address";
}
}
SOLUTION 1:
HTML:
<div>
<form action="">
<input type="text" name="firstname" id="un1" class="myInput" value="First Name"/>
<input type="text" name="surname" id="un2" class="myInput" value="Surname" />
<input type="text" name="username" id="un3" class="myInput" value="Email Address"/>
<input type="button" value="Register!" />
</form>
</div>
JS:
var defaultValues = {
un1 : 'First Name',
un2 : 'Surname',
un3 : 'Email Address'
}
var elements = document.querySelectorAll('.myInput');
for (var i=0; i<elements.length; i++) {
elements[i].addEventListener(['click', 'focus'], function(){
if (this.value === defaultValues[this.id]) this.value = '';
});
elements[i].addEventListener('blur', function(){
if (this.value === '') this.value = defaultValues[this.id];
});
}
PS: The code is not compatible with all browsers. If you aim for browser compatibility, you should probably use a library that abstracts away the differences (ex: jQuery).
SOLUTION 2:
No change in HTML
JS:
window.onload = function(){
var field;
//Field Manoeuvre1
field = document.getElementById('un1');
field.onclick = fieldClear.bind(field, 'First Name');
field.onfocus = fieldClear.bind(field, 'First Name');
field.onblur = fieldReplace.bind(field, 'First Name');
//Field Manoeuvre2
field = document.getElementById('un2');
field.onclick = fieldClear.bind(field, 'Surname');
field.onfocus = fieldClear.bind(field, 'Surname');
field.onblur = fieldReplace.bind(field, 'Surname');
//Field Manoeuvre3
field = document.getElementById('un3');
field.onclick = fieldClear.bind(field, 'Last Name');
field.onfocus = fieldClear.bind(field, 'Last Name');
field.onblur = fieldReplace.bind(field, 'Last Name');
}
function fieldClear(value){
if(this.value === value) this.value = '';
}
function fieldReplace(value){
if(this.value === '') this.value = value;
}
DEMO: http://jsbin.com/ekoJuQE/1/edit
Use either jquery or html5
Html5 solution:
Add parameter placeholder to input like this
<input name="firstname" type="text" placeholder="First name" />
Jquery (plus attribute data-placeholder="text shown in field" on html input fields:
$(window).on("load", function(){
$("#un1, #un2, #un3").on("click, focus", fieldClear(this));
$("#un1, #un2, #un3").on("blur", fieldReplace(this));
});
function fieldClear(obj) {
$(obj).val('');
}
function fieldReplace(obj) {
$(obj).val($(obj).data('placeholder'));
}
Delegated event handling can shorten things up a bit. If you pick up jQuery, then add classes or select by element type. Also add a data attr.
<input type="text" name="surname" id="un2" value="Surname" data-placeholder="Surname"/>
$('form').on('click, focus', 'input', function(e){
$(this).val("");
});
$('form').on('blur', 'input', function(){
$(this).val($(this).attr('data-placeholder'));
});
I am new to jquery and i think this is just a basic problem. `
<input type="text" name="text1" value=""></input>
<input type="text" name="text2" value=""></input>
<input type="text" name="text3" value=""></input>
<input type="text" name="text4" value=""></input>
<input type="text" name="text5" value=""></input>
<input type="submit" value="submit"></input>
<pre id="result">
</pre>
</form>`
This is my html form and i am using following jquery function to produce json object
$.fn.serializeObject = function()
{
var o = {};
var d={};
var a = this.serializeArray();
$.each(a, function(i,n) {
o['name'] = n['name'];
o['content'] =(n['value']);
});
return o;
};
$(function() {
$('form').submit(function() {
$('#result').text(JSON.stringify($('form').serializeObject()));
return false;
});
});
on runnig the above html i am getting the output {"name":"text5","content":"sdsd"}
just the final text field. i know am wrong somewhere . can someone help me to fix it. thanks in advance
That's because you are overwriting object's properties and the last values win, you can use an array and it's push method.
$.fn.serializeObject = function () {
var o = [];
var a = this.serializeArray();
$.each(a, function (i, n) {
o.push({
name: n['name'],
content: n['value']
})
});
return o;
};
http://jsfiddle.net/kxM3e/
Using jQuery map method:
$.fn.serializeObject = function () {
return this.find('input, textarea, select').map(function(){
return { name: this.name, content: this.value };
}).get();
};