Convert serialized string that contains &, = to Object? - javascript

$('#submit-form').click(function(){
var data_serialize = $("#form").serialize();
$("input[type='checkbox']:not(:checked)").each(function(e){
data_serialize += "&"+this.name+'=0';
});
$("input[type='checkbox']:checked").each(function(e){
data_serialize += "&"+this.name+'=1';
});
console.log(data_serialize);
})
The above code gives me a string
companyName=&contactName=&role=&email=&phone=&desctiption=&websiteURL=&tc-check=0
like this. How can I make it as an Object?

It will convert this string to an javascript object.
var yourString = 'companyName=&contactName=&role=&email=&phone=&desctiption=&websiteURL=&tc-check=0';
var yourObj = JSON.parse('{"' + yourString.replace(/=/g,'":"').replace(/&/g, '","') + '"}');
console.log(JSON.stringify(yourObj));

You can easily loop through the form controls building an object via brackets notation:
$('#submit-form').click(function(){
var obj = {};
$("#form").find("input, textarea, select").each(function() {
var type = this.type.toLowerCase();
if (this.name && !this.disabled && type !== "button" && type !== "submit") {
if (type === "checkbox") {
obj[this.name] = this.checked ? 1 : 0;
} else {
obj[this.name] = $(this).val();
}
}
});
console.log(obj);
});
Note that we skip disabled inputs and inputs without names, as that's the standard for forms (it's what HTML does, and what serialize does). The above preserves your non-standard handling of checkboxes.
Example:
$('#submit-form').click(function(){
var obj = {};
$("#form").find("input, textarea, select").each(function() {
var type = this.type.toLowerCase();
if (this.name && !this.disabled && type !== "button" && type !== "submit") {
if (type === "checkbox") {
obj[this.name] = this.checked ? 1 : 0;
} else {
obj[this.name] = $(this).val();
}
}
});
console.log(obj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<input name="btn" type="button" value="Buttons are ignored">
<input name="text1" type="text" value="text here">
<input name="cb1" type="checkbox" checked>
<input name="cb2" type="checkbox">
<select name="s1">
<option value="foo" selected>foo</option>
<option value="bar">bar</option>
</select>
<textarea name="ta">testing</textarea>
<input name="text-disabled" type="text" disabled value="don't include me">
<input type="text" value="Ignore me I don't have a name">
<input type="button" id="submit-form" value="Submit">
</form>

Related

Converting Form Elemnt in Javascript object

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;
};

How to get value from one form and post to the another form using javascript?

I am having two forms in same page,
Form 1 ID : home /
Form 2 ID : contact
I need the values filled in the form(home) in the text box of form2(contact) once the send button clicked.
<form id="home" method="get" action="#portfolio" role="form">
<select class="form-control" id="pd_howmuch">
<option>HOW MUCH ?</option>
<option>$100</option>
<option>$200</option>
</select>
<input id="pd_fname" type="text" name="name">
<input id="pd_lname" type="text" name="surname">
<input id="pd_zipcode" type="tel" name="zipcode">
<input id="pd_applynowbt" type="submit" value="Send">
</form>
<section id="portfolio">
<form id="contact" method="post" action="contact.php" role="form">
<select class="form-control" id="howmuch1">
<option>HOW MUCH ?</option>
<option>$100</option>
<option>$200</option>
</select>
<input id="fname1" type="text" name="name">
<input id="lname2" type="text" name="surname">
<input id="zipcode2" type="tel" name="zipcode">
<input id="applynowbt" type="submit" value="Submit">
</form>
</section>
Ok If I am understanding you correctly you wish to populate information from the first form to the second one.
So for this task to be accomplish you need to attach an event handler to the second form and prevent the default behavior
Working demo Hope to help you
var homeForm = document.getElementById("home");
var contactForm = document.getElementById("contact");
contactForm.addEventListener("submit", function(e) {
e.preventDefault();
contactForm.elements.item(0).value = homeForm.elements.item(0).value
contactForm.elements.item(1).value = homeForm.elements.item(1).value
contactForm.elements.item(2).value = homeForm.elements.item(2).value
contactForm.elements.item(3).value = homeForm.elements.item(3).value
}, false);
var sourceForm = document.getElementById("source-form");
var targetForm = document.getElementById("target-form");
function findTargetNode(nodeName, name) {
var targetElems = targetForm.elements;
for (var i = 0; i < targetElems.length; i++) {
var elem = targetElems.item(i);
if (elem.nodeName.toLowerCase() === nodeName && elem.name === name) {
return elem;
}
}
}
function setNodeValue(node, type, value) {
if (type === 'select')
{
for (var i = 0, options = node.options; i < options.length; i++) {
if (options[i].value === value) {
options[i].setAttribute('selected', 'true');
}
else {
options[i].removeAttribute('selected');
}
}
}
// else if (type === 'checkbox' || type === 'radio') { /* ... */ }
else {
node.value = value;
}
}
sourceForm.addEventListener("submit", function(e) {
for (var i = 0, elems = sourceForm.elements; i < elems.length; i++) {
var elem = elems.item(i);
if (!elem.name) {
continue;
}
var type = elem.nodeName.toLowerCase();
var targetNode = findTargetNode(type, elem.name);
if (!targetNode) {
continue;
}
setNodeValue(targetNode, type, elem.value);
}
e.preventDefault();
// targetForm.submit();
}, false);
<form id="source-form" action="javascript:void(0)" role="form">
<select class="form-control" id="my-select" name="my-select">
<option value="-1">HOW MUCH ?</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<input id="my-text" type="text" name="my-text">
<input id="submit-source-form" type="submit" value="Fill the following form">
</form>
<section style="margin-top: 15px;">
<form id="target-form" method="post" action="contact.php" role="form">
<select class="form-control" id="my-select-2" name="my-select">
<option value="-1">HOW MUCH ?</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<input id="my-text-2" type="text" name="my-text" value="this will change">
<input id="additional-value" type="text" name="additional" placeholder="this value will not change">
<input id="submit-target-form" type="submit" value="Send form">
</form>
</section>
https://jsfiddle.net/cremugnt/
Note: "Send form" action doesn't work here because of "Blocked form submission to 'http://stacksnippets.net/contact.php' because the form's frame is sandboxed and the 'allow-forms' permission is not set."
Note: This snippet can copy only "select" and "input" fields so if you want to work with other fields like "checkbox" or "radio" you get the idea.
This is a more global approach using OODK-JS and jQuery compatible with any types of field (note as field matching is based on the name attribute ):
$.noConflict();
OODK.config({
'path': {
'oodk': '../src',
'workspace': 'workspace'
}
});
OODK(function($, _){
// POO approach to solve this problem
// define a FormHelper class
var FormHelper = $.class(function($, µ, _){
$.protected('form');
$.public(function __initialize(form){
µ.form = form;
});
$.public(function exportToLiteral(){
var exprt = {};
jQuery(µ.form).find(":input, [textarea]").each(function(){
var val;
if(this.type === 'radio'){
val = µ.exportRadioField(this, exprt);
}else if(this.type === 'checkbox'){
val = µ.exportCheckboxField(this, exprt);
}else{
val = µ.exportField(this, exprt);
}
if(typeof val !== "undefined" &&
typeof jQuery(this).attr("name") !== "undefined"){
exprt[jQuery(this).attr("name")] = val;
}
});
return exprt;
});
// export argument html field fld to object literal exprt
$.protected(function exportField(fld, exprt){
return jQuery(fld).val();
});
// export argument checkbox html field fld to object literal exprt
$.protected(function exportCheckboxField(fld, exprt){
var val;
if(jQuery(fld).is(':checked')){
if(typeof exprt[jQuery(this).attr("name")] !== "undefined"){
val = exprt[jQuery(this).attr("name")];
}else{
val = [];
}
val.push(jQuery(this).val());
};
return val;
});
// export argument html radio field fld to object literal exprt
$.protected(function exportRadioField(fld, exprt){
var val;
if(jQuery(fld).is(':checked')){
val = jQuery(this).val();
}
return val;
});
// copy all values of the source form to the destination form passed
// as argument
$.public(function copyToForm(destForm){
var oSrcForm = this.exportToLiteral();
jQuery(destForm).find(":input, [textarea]").each(function(){
if(typeof oSrcForm[jQuery(this).attr("name")] !== "undefined"){
var srcVal = oSrcForm[jQuery(this).attr("name")];
if(this.type == 'checkbox'){
µ.copyToCheckboxField(this, srcVal, oSrcForm);
}else if(this.type == 'radio'){
µ.copyToRadioField(this, srcVal, oSrcForm);
}else{
µ.copyToField(this, srcVal, oSrcForm);
}
}
});
});
$.protected(function copyToField(fld, val, exprt){
jQuery(fld).val(val);
});
$.protected(function copyToCheckboxField(fld, val, exprt){
if(Array.isArray(srcVal) && srcVal.indexOf(jQuery(fld).val()) !== -1){
jQuery(fld).prop('checked', true);
}
});
$.protected(function copyToRadioField(fld, val, exprt){
if(exprt[jQuery(fld).attr("name")] == jQuery(fld).val()){
jQuery(fld).prop('checked', true);
}
});
});
jQuery(document).ready(function(){
jQuery('#pd_applynowbt').bind('click', function(evt){
// prevent the source form to be submitted
evt.preventDefault();
var formHelper = $.new(FormHelper, jQuery('#home'));
// copy all fields from form #home to form #contact
formHelper.copyToForm(jQuery('#contact'));
});
});
});

javascript onChange event listener not working for input form

When I make this button:
<div id="Input #1">
<label for="input1">Input #1:</label>
<input type="number" id="input1" name="input1" onchange="i1set()">
</div>
And then have this JavaScript:
var i1 = undefined;
var i1set = function(){
i1 = document.getElementById("input1").value;
}
var solution = parseFloat(i1)+parseFloat(i2);
alert(solution);
It works no problem.
But, when I eliminate the onchange part of the html, and instead create an event listener in js, then I get problems. One of the problems is that having parseFloats give me "NaN" instead of a number answer... but the bigger problem is that even when I get rid of parseFloats, even with subtraction, addition, division, it gives me weird incorrect answers.
Below is my current code that no longer works:
<form>
<input type="radio" id="addition" name="addition" value="addition"><label>Addition</label><br>
<input type="radio" id="subtraction" name="subtraction" value="subtraction"><label>Subtraction</label><br>
<input type="radio" id="multiplication" name="multiplication" value="multiplication"><label>Multiplication</label><br>
<input type="radio" id="division" name="division" value="division"><label>Division</label><br>
<div id="Input #1">
<label for="input1">Input #1:</label>
<input type="number" id="input1" name="input1">
</div>
<div id="Input #2">
<label for="input2">Input #2:</label>
<input type="number" id="input2" name="input2">
</div>
<input type="submit" id="submit" value="Solve" />
</form>
<script>
var i1 = undefined;
var i2 = undefined;
var i1set = function(){
i1 = document.getElementById("input1").value;
}
var i2set = function(){
i2 = document.getElementById("input2").value;
}
var solve = function(){
if ( (i1 != undefined) && (i2 != undefined) ) {
if(document.getElementById('addition').checked) {
var solution = parseFloat(i1)+parseFloat(i2);
alert(solution);
}
if(document.getElementById('subtraction').checked) {
var solution = i1-i2;
alert(solution);
}
if(document.getElementById('multiplication').checked) {
var solution = i1*i2;
alert(solution);
}
if(document.getElementById('division').checked) {
var solution = i1/i2;
alert(solution);
}
}
}
document.getElementById("input1").addEventListener("change", i1set(), false);
document.getElementById("input2").addEventListener("change", i2set(), false);
document.getElementById("submit").addEventListener("click", solve, false);
</script>
</body>
</html>
The problem is that empty string is not equal to udnefined so this checkes:
if ((i1 != undefined) && (i2 != undefined)) {
behave not the way you expect. The if block can be simpler:
if (i1 && i2) { // or i1 !== '' && i2 !== ''
The second problem is that you need to provide function reference as event listener, not execute it immediately with ():
document.getElementById("input1").addEventListener("change", i1set, false);
// Note, you don't need () here ------^

Delete form fields using Javascript

Is it possible to write a Javascript function to delete form a field when somebody does not fill in the field?
<form id="myform">
<label for="q1" id="q1label">question 1</label>
<input type="text" id="q1" name="q1"/>
<label for="q2" id="q2label">question 2</label>
<input type="text" id="q2" name="q2"/>
<label for="q3" id="q3label">question 3</label>
<input type="text" id="q3" name="q3"/>
<input type="submit" value="Delete blank fields" onclick="return checkanddelete"/>
</form>
If somebody does not fill in question 2 for example, it deletes question 2 label and the field.
For jQuery:
<script type="text/javascript">
function checkanddelete() {
$('input').each(function(){
if ($(this).val() == '') {
var id = $(this).attr('id');
$.remove('#' + id);
$.remove('#' + id + 'label');
}
});
}
</script>
For JavaScript:
<script type="text/javascript">
function checkanddelete() {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++)
{
if (document.getElementsByTagName("input")[i].value.length == 0) {
var id = document.getElementsByTagName("input")[i].id;
(elem=document.getElementById(id)).parentNode.removeChild(elem);
(elem=document.getElementById(id + 'label')).parentNode.removeChild(elem)
}
}
}
</script>
Something like this?
With jquery:
$("#myform :text").each(function(){
if( !$.trim($(this).val()) )
$(this).prev('label').andSelf().remove();
});
i am using folloing function to remove element from document.
function removeElement(id)
{
if(typeof id === "object")
return id.parentNode.removeChild(id);
else
return (elem=document.getElementById(id)).parentNode.removeChild(elem);
}
You can pass a dom element or element Id itself to delete .
The following should do what you want :
var inputToDelete = document.getElementById("q2");
if (inputToDelete.value == "") {
var labelToDelete = document.getElementById("q2label");
var parentNode = document.getElementById("myform");
parentNode.removeChild(labelToDelete);
parentNode.removeChild(inputToDelete);
}

JavaScript if statment don't work

I need help with javascript. here is my problem:
<script type="text/javascript">
function validateForm() {
var ime = document.getElementById('ime');
var prezime = document.getElementById('prezime');
var telefon = document.getElementById('telefon');
var datum = document.getElementById('datum');
var patt1 = /^\+[0-9]+$/;
if (telefon.match(patt1) == null) {
alert("Niste dobro uneli broj");
}
if (ime.value.length == 0 && prezime.value.length == 0 && telefon.value.length == 0 && datum.value.length == 0) {
alert("Niste dobro uneli podatke!");
return false;
}
}
</script>
<form action="popup.php" method="post" onsubmit="return validateForm()">Vase ime:
<input type="text" name="ime" id="ime"> <br/>
Vase prezime:
<input type="text" name="prezime" id="prezime"> <br/>
Broj telefona:
<input type="text" name="telefon" id="telefon"> <br/>
Datum rodjenja:
<input type="text" name="datum" id="datum"> <br/>
<input type="submit" name="save" value="sacuvaj">
</form>
I don't understand why telefon.match(patt1)==null) doesn't work. Please help!
Reason is because you can't apply regex to HTML Element, you can apply it to its value:
var telefon = document.getElementById('telefon').value;
Then you can execute your regex on var telefon
telefon is a DOM element, not a string
telefon.value can be matched
The object stored in telefon will be a DOM element (e.g. HTMLDivElement), which has no method "match". You'll want to extract the pertinent text from that element before matching. How you do that will depend on the exact DOM type:
if (telefon.value.match(patt1) == null) // For form elements...
if (telefon.innerHTML.match(patt1) == null) // For "plain" DOM elements...

Categories

Resources