Not able to set the JavaScript JSON object value into Form - javascript

My JSP:
<form:form modelAttribute="myForm" action="/action">
<input type="checkbox" value="1" name="checkboxValue" />
<input type="hidden" name="jsonObject" id="jsonObj" value=""/>
<input type="submit" value="Submit" onclick="function getjson()"/>
</form:form>
JavaScript:
function getjson(){
var json = [];
var checkedBoxes = $('input[name="checkedList"]:checked').map(function() {
return this.value;
}).get();
var checkedBoxes1 = $('input[name="checkedList1"]:checked').map(function() {
return this.value;
}).get();
json.push({"id":checkedBoxes});
json.push({"Flap":checkedBoxes1});
document.getElementById("jsonObj").value = json;
}
I have a MyForm.Java:
private String checkboxValue;
private jsonObject jsonObject;
//getters and setters
Here the value of checkboxValue is saving in variable checkboxValue but the jsonObject is not binding with the variable. I don't know why. Need some serious help please.

Your jsp should be like this
<form:form modelAttribute="myForm" action="/action" id="Submitform">
<input type="checkbox" value="1" name="checkboxValue" />
<input type="hidden" name="jsonObject" id="jsonObj" value=""/>
<input type="button" value="Submit" onclick="getjson()"/>
</form:form>
And Your javascript should change to this
function getjson(){
var json = [];
var checkedBoxes = $('input[name="checkedList"]:checked').map(function() {
return this.value;
}).get();
var checkedBoxes1 = $('input[name="checkedList1"]:checked').map(function() {
return this.value;
}).get();
json.push({"id":checkedBoxes});
json.push({"Flap":checkedBoxes1});
document.getElementById("jsonObj").value = json;
document.getElementById("Submitform").submit();
}

Related

jquery populates attribute input form multiple value

is that possible to populate attributes name, value, type from :input or something like jQuery serialize for all kinds of input, and combine the value if there is have multiple name like checkbox and radio choices
the concept like this :
$(this).attr('name');
$(this).attr('type');
$(this).attr('value'); // <--- combine this value when the type is checkbox or radio
i try to populate the attributes using each function :
it work but i still don't know how to combine type
$('.submit').click(function(){
var tipe = {}
var form = {}
$('input[type=text], textarea', '.register').each(function(){
const name = $(this).attr('name');
const value = $(this).val();
const type = $(this).attr('type');
form[name] = value;
tipe[name] = type;
});
$('input[type=checkbox], input[type=radio]', '.register').each(function(){
const name = $(this).attr('name');
const value = $(this).val();
const type = $(this).attr('type');
if(form[name] === undefined) {
form[name] = [value];
tipe[name] = [type];
} else {
form[name].push(value);
}
});
console.log(form);
//console.log(tipe);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="register">
<input type="text" name="full_name">
<textarea name="address"></textarea>
<input type="radio" name="sex" value="male">
<input type="radio" name="sex" value="female">
<input type="checkbox" name="hobies" value="foodball">
<input type="checkbox" name="hobies" value="basketball">
</div>
<input type="button" class="submit" value="Submit">
you can use below logic where you can create one map to store value of each input and append values if input type is of type radio or checkbox
$('.submit').click(function(e){
var formValues = {};
$('.register :input').each(function(){
var name = $(this).attr('name');
var type = $(this).attr('type');
var value = $(this).val();
var inputElement = {};
var valid = true;
if(type == 'radio' || type == 'checkbox') {
valid = $(this).is(':checked');
if(valid) {
if(formValues[name]) {
inputElement = formValues[name];
var preVal = inputElement['value'];
value = preVal + ',' + value;
}
}
}
if(valid) {
inputElement['name'] = name;
inputElement['type'] = type;
inputElement['value'] = value;
formValues[name] = inputElement;
}
});
console.log(formValues);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="register">
<input type="text" name="full_name">
<textarea name="address"></textarea>
<input type="radio" name="sex" value="male">
<input type="radio" name="sex" value="female">
<input type="checkbox" name="hobies" value="foodball">
<input type="checkbox" name="hobies" value="basketball">
</div>
<input type="button" class="submit" value="Submit">

Pass checkbox value to js upon clicking 'submit'

I have a bunch of checkboxes queried from a database via a js function at id='checkboxes'. I'm trying to pass the checked value to a js function but the console returns an undefined endpoint (i.e. ..../undefined HTTP/1.1 200 --)
HTML:
<form action="javascript:getQuestionData(this.value)" method="post">
<div id="checkboxes">
</div>
<input type='submit' value="Submit">
</input>
</form>
Javascript:
function getQuestionData(sampleValue) {
document.getElementById("question").innerHTML = ""
document.getElementById("solve").innerHTML = ""
var endPointQuestionData = '/api/v1/questions/' + sampleValue
Plotly.d3.json(endPointQuestionData, function(error, response) {
if (error) return console.warn(error);
appendInnerHTML(response)
});
};
Why is the checked value not being passed to the getQuestionData function?
Add following code in the submit button:
onclick='return getQuestionData();
function getQuestionData() {
var question = document.getElementsByName("question")[0].checked;
alert(question);
var endPointQuestionData = '/api/v1/questions/' + question
Plotly.d3.json(endPointQuestionData, function(error, response) {
if (error) return console.warn(error);
appendInnerHTML(response)
});
};
<form method="post">
<input type="checkbox" name="question" value = "Question"> Question<br>
<input type="checkbox" name="question" value = "Solve"> Solve<br>
<input type='submit' value="Submit" onclick = "getQuestionData()">
</form>

Merging List of JSONs into one JSON in javascript

I have an HTML form and I'm trying to stringify and parse its content into JSON on submission using javascript
for example:
<form id="form1" enctype="multipart/form-data">
<input type="hidden" name="presented" value="1" />
<input type="checkbox" name="RESPONSE" value="ch1">ch1</input>
<input type="checkbox" name="RESPONSE" value="ch2">ch2</input>
<input type="checkbox" name="RESPONSE" value="ch3">ch3</input>
<input id="submit_button" name="submit" type="submit"/>
</form>
and the javascript:
$(document).ready(function () {
$("#submit_button").click(function (e) {
e.preventDefault();
var formData = JSON.parse(JSON.stringify(jQuery('#form1').serializeArray()));
alert(JSON.stringify(formData));
});
});
I'm getting an output like this (considering that only the first two checkboxes are checked):
[{"name":"presented","value":"1"},
{"name":"RESPONSE","value":"ch1"},
{"name":"RESPONSE","value":"ch2"}]
but I'm expecting this result in one JSON with arrays for duplicated keys:
{"presented" : "1", "RESPONSE" : ["ch1", "ch2"]}
jsfiddle here
You will need to write your own serializer. For example to group values of the elements with the same name you could do something like this using Array.prototype.reduce:
$("#submit_button").click(function (e) {
e.preventDefault();
var formData = jQuery('#form1').serializeArray().reduce(function(prev, curr) {
if (prev.hasOwnProperty(curr.name)) {
prev[curr.name] = $.isArray(prev[curr.name]) ? prev[curr.name] : [prev[curr.name]]
prev[curr.name].push(curr.value);
}
else {
prev[curr.name] = curr.value;
}
return prev;
}, {});
document.querySelector('pre').innerHTML = JSON.stringify(formData, null, 4);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" enctype="multipart/form-data">
<input type="hidden" name="presented" value="1" />
<input type="checkbox" name="RESPONSE" value="ch1">ch1</input>
<input type="checkbox" name="RESPONSE" value="ch2">ch2</input>
<input type="checkbox" name="RESPONSE" value="ch3">ch3</input>
<input id="submit_button" name="submit" type="submit"/>
</form>
<pre></pre>
I think that your new object's value should always be an array for consistency. Here's how to build it:
var arr = [{"name":"presented","value":"1"},
{"name":"RESPONSE","value":"ch1"},
{"name":"RESPONSE","value":"ch2"}];
var newObj = {};
arr.forEach(function(item){
if(!newObj.hasOwnProperty(item.name)){
newObj[item.name] = [];
}
newObj[item.name].push(item.value);
});
And here's a way to build it exactly like you want it:
var newObj = {};
arr.forEach(function (item) {
if (!newObj.hasOwnProperty(item.name)) {
newObj[item.name] = item.value;
} else {
if (Object.prototype.toString.call(newObj[item.name]) !== '[object Array]') {
var newItem = newObj[item.name];
newObj[item.name] = [newItem];
}
newObj[item.name].push(item.value);
}
});
Think other than JSON parsing library. It's very simple Java Program using String.split() method that convert Json String into name> without using any library.

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/

Undefined value, reading an input

i am geting undefined for ans . why? what is wrong?
function submitAnswer()
{
var myForm = document.getElementById('quiz');
var ansVal = myForm.ans.value;
var qnoVal = myForm.qno.value;
alert ("ans=" + ansVal);
alert ("qno = " +qnoVal);
return;
}
<form nam="quiz" id="quiz" >
Yes:
<input type="radio" id="ans" name="ans" value="1" />
<br />No:
<input type="radio" id="ans" name="ans" value="0" />
<input id="qno" type="text" name="qno " value="qqq" />
<input type="button" value="" onClick="submitAnswer(); " />
</form>
Using theForm.inputElement is not standard and can't be guaranteed to work. Instead, you should use document.getElementById, or some other DOM mechanism, to find the input element you want. theForm.elements[name] also works.
You'll also need to fix your element IDs before you can do that - you have two <input type="radio" /> elements with an ID "ans", which is incorrect. IDs must be unique:
<input type="radio" id="ans1" name="ans" value="1" />
<input type="radio" id="ans2" name="ans" value="0" />
<script type="text/javascript">
var ans1 = document.getElementById('ans1');
var ans1value = ans1.value;
</script>
Or, get the radio button group as a single element using elements:
<script type="text/javascript">
var theForm = document.getElementById('quiz');
var ansValue = theForm.elements['ans'].value;
</script>
You have two elements with the same ID, causing a name conflict. They're also the same as the name attribute on the same element, which could cause some confusion down the road.
Try:
var ansVal = myForm.ans.checked;
This will work:
function submitAnswer() {
var myForm = document.getElementById('quiz');
// Set a default value, in case no radio button is selected
var ansVal = 'default value here';
var qnoVal = myForm.qno.value;
// Loop through radio buttons, getting the value of the
// one that is checked (selected).
var radioButtons = myForm.ans;
for (var i = 0; i < radioButtons.length; i++) {
if (radioButtons[i].checked) {
ansVal = radioButtons[i].value;
}
}
alert ("ans=" + ansVal);
alert ("qno = " +qnoVal);
return;
}
this will work too
function submitAnswer()
{
var myForm = document.getElementById('quiz');
var qnoVal = myForm.qno.value;
var ansVal = 'none';
for( i = 0; i < myForm.ans.length; i++ )
{
if( myForm.ans[i].checked == true )
{
ansVal = myForm.ans[i].value;
break;
}
}
alert ("ans=" + ansVal);
alert ("qno = " +qnoVal);
return;
}
This will work
<html>
<form name="form">
Which one is good?<br>
<input type="radio" name="food" value="Spud"
checked="checked"> Spud<br>
<input type="radio" name="food" value="Carrot"> Carrot<br>
<input type="submit" onclick="get_radio_value()">
</form>
<script type="text/javascript>
<!--
function get_radio_value()
{
for (var i=0; i < document.form.food.length; i++)
{
if (document.form.food[i].checked)
{
var rad_val = document.form.food[i].value;
alert(rad_val);
}
}
}
//-->
</script>
</html>

Categories