Creating multidimensional array from dynamic form in JQuery - javascript

I'm trying to capture values from inputs and put them in JQuery object instead of having to deal with PHP indexing.
This is the form
<form name="second_form" id="second_form" action="#" method="POST">
Add Champion
<div id="ChampionInput">
</div>
<br><br>
<input id="obj" type="hidden" name="obj">
<input type="submit" name="submit">
</form>
My script that I'm trying to use to recreate the array:
$("#second_form").submit(function(event) {
var object = [];
$('.Champion').each(function() {
var champion = {
'name': $(this).find(".ChampionInput").val(),
'change': $(this).find("input:radio:checked").val(),
'General_Description': [],
'General_Change':[]
};
$(this).find('.GeneralChange').each(function() { champion.General_Description.push($(this).children(".GeneralChangeDescription").val());
champion.General_Change.push($(this).children(".General_Change").val());
});
object.push(champion);
});
object = JSON.stringify(object);
$('#obj').val(object); //Sending object to hidden input
});
And here is the way I used to create this PHP array which messes up indexing when I delete some inputs when creating the form
foreach($_POST['champion'] as $champion){
if(isset($_POST['Release'][$ChampionNumber])){
$_POST['Release'][$ChampionNumber]=='New' ? $champions[$champion]['New']=1 : $champions[$champion]['New']=0;
$_POST['Release'][$ChampionNumber]=='Rework' ? $champions[$champion]['Rework']=1 : $champions[$champion]['Rework']=0;
}
if(!empty($_POST['GeneralChangeDescription'][$ChampionNumber])){
foreach($_POST['GeneralChangeDescription'][$ChampionNumber] as $indexGeneral=>$GeneralChangeDescription){
$GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] =ucfirst(trim($GeneralChangeDescription));
if(substr($GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1], -1)!='.'){
$GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] = $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1].'.';
}
$GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] = preg_replace('/\s\/\s/','/',$GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1]);
$GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] = preg_replace( '/(\.?\d\/?%?)+/', '<strong>$0</strong>', $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1]);
$GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] = preg_replace( '/\b\w+\.(jpg|png|gif)/', '', $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1]);
$champions[$champion]['General']['Change'][] = $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1];
$champions[$champion]['General']['Type'][] = $_POST['GeneralChange'][$ChampionNumber][$indexGeneral];
}
}
$ChampionNumber++;
}
Removing champions
$('div#ChampionInput').on('click', 'a.Remove',function(){
var champion = $(this).closest('.Champion');
var id = champion.data("id");
var nextChampion = champion;
while((nextChampion = nextChampion.next()).length != 0){
nextChampion.attr("data-id",id++);
nextChampion.children('.ChampionInput').attr('placeholder','Champion '+ id);
}
championNumber=id+1;
championNumberArray=id;
champion.remove();
});
Removing changes
$('div#ChampionInput').on('click', 'a.RemoveGeneralChange',function(){
$(this).closest('.GeneralChange').remove();
});
Here is how my array looks like in PHP: http://i.imgur.com/rURnNTG.png and I want to get array looking like that after sending JQuery object through hidden input in form and obtaining it in PHP. Here is how my JQuery object looks like right now http://imgur.com/2r9iyKN which is not even close.
Here is also JSfiddle of form creation: jsfiddle.net/g50zd384/

If you really need that array, so create it in PHP after sending the form:
$array;
for($i = 1; $i <= count($_POST['champion']); $i++) {
$champion = $_POST['champion'][$i];
$array[$champion]['General'] = $_POST['GeneralChangeDescription'][$i];
$array[$champion]['Type'] = $_POST['GeneralChange'][$i];
$array[$champion]['Release'] = $_POST['Release'][$i];
}
Your form should be created with this names:
championNumber = 1;
championNumberArray = 0;
$('a#AddChampion').on('click',function(){
$('div#ChampionInput').append(
'<div class="Champion">\
<br>\
<input type="text" class="ChampionInput" name="champion['+championNumber+']" placeholder="Champion '+championNumber+'">\
<datalist id="champions"></datalist>\
<input type="radio" name="Release['+championNumber+']" value="New">New\
<input type="radio" name="Release['+championNumber+']" value="Rework">Rework\
<input type="radio" name="Release['+championNumber+']" value="None" checked>None\
Add General Change\
<div class="GeneralChanges">\
</div>\
<br>\
<div>');
championNumber++;
});
$('div#ChampionInput').on('click','a.AddGeneralChange', function(){
var id = $(this).data('id');
$(this).siblings('.GeneralChanges').append(
'<div class="GeneralChange">\
<textarea type="text" size="20" rows="3" cols="50" maxlength="500" class="GeneralChangeDescription" name="GeneralChangeDescription['+id+'][]" placeholder="Enter General Change Description"></textarea>\
<select class="General_Change" name="GeneralChange['+id+'][]">\
<option value="buff">Buff</option>\
<option value="nerf">Nerf</option>\
<option value="new">New</option>\
<option value="change">Change</option>\
<option value="bugfix">Bugfix</option>\
</select>\
</div>');
});
It is important, that you name your inputs in this way!
..not the best way, but better than sending json data in a hidden input form. I hope this could help you.

Related

how do I populate html form fields from a dynamic form dropdown

I am trying to figure out a way to fill html form fields based on the selection of a dynamic form dropdown menu.
I have been looking around and trying to tweek what I have found. So far I am up to filling one of my form fields. But have no gone off piste trying to fill all three, leaving the radio empty when I want it to pick up the 0 value on all my dummy entries and select enable (0)
<option value="<?= $row['ENABLED2'] . " - " . $row['ID2'] . " - " . $row['SOLDTO2'] ?>"> ..</option>
<?php
}
?>
</select>
...
<script>
$(document).ready(function() {
$("#ddlModel").on("change", function() {
var GetValue = $("#ddlModel").val();
const GetValueArray = GetValue.split(" - ");
var GetValueSold = GetValueArray[2];
var GetValueID = GetValueArray[1];
var GetValueEn = GetValueArray[0];
$("#SOLDTO2").val(GetValueSold);
$("#ID2").val(GetValueID);
$("#ENABLED2").val(GetValueEn);
});
});
</script>
...
<FORM id='addClient' action='process/process-addclient.php' method='post'>
<input type='text' id='ID2' name='ID2' maxlength='4' placeholder='Four Digit Sage Code' style='display:inline'>
<textarea id='SOLDTO2' name='SOLDTO2' placeholder='Client Name and Address - 6 Lines Max'></textarea>
<input type="radio" name='ENABLED2' id='enable' value='0'> <label for='enable'>Enable Client</label>
<input type="radio" name='ENABLED2' id='disable' value='1'> <label for='disable'>Disable Client</label>
In writing this out I have answered some of my own questions but I cant figure out how to get the last column (radio) to populate.
I am new to JS/JQ
The way to populate the radio field is by using the following code:
<script>
$(document).ready(function() {
$("#ddlModel").on("change", function() {
var GetValue = $("#ddlModel").val();
const GetValueArray = GetValue.split(" - ");
var GetValueSold = GetValueArray[2];
var GetValueID = GetValueArray[1];
var GetValueEn = GetValueArray[0];
$("#SOLDTO2").val(GetValueSold);
$("#ID2").val(GetValueID);
$("#ENABLED2").val(GetValueEn);
//Check radio field based on value of GetValueEn
if (GetValueEn == 0) {
$("#enable").prop('checked', true);
}
else {
$("#disable").prop('checked', true);
}
});
});
</script>

How to get the selected radio buttons value?

i am trying to get the value of selected radio buttons so i can submit my form using Ajax i searched here for some help but i couldn't find any useful solution
<input type="radio" id="answer" name="answer<?php echo $function::escape_string($question_row->question_id); ?>"
value="<?php echo $function::escape_string($answer_row>answer_id); ?>"/>
-HTML Output
<input type="radio" id="answer" name="answer16" value="107"/>
<input type="radio" id="answer" name="answer17" value="109"/>
<input type="radio" id="answer" name="answer15" value="104"/>
i found this function here
function findSelection(field) {
var test = document.getElementsByName(field);
var sizes = test.length;
alert("Size is " + sizes);
for (i=0; i < sizes; i++) {
if (test[i].checked==true) {
alert(test[i].value + ' you got a value');
return test[i].value;
}
}
}
var radioinputs = findSelection("answer");
But I do not know what to change so I can make it work with me properly
You can structure like this:
function findSelection(field) {
var test = document.getElementsByClassName(field);
var sizes = test.length;
//alert("Size is " + sizes);
result = [];
// result[16]=107;
// result[17]=109;
// result[15]=104;
for (i=0; i < sizes; i++) {
var index = test[i].dataset.index;
if(test[i].checked == true){
result[index] = test[i].value;
}else{
result[index] = undefined; // for a answer doesn't have a value
}
}
return result;
}
function checkfunction(){
var radioinputs = findSelection("radioanswer");
console.log(radioinputs);
console.log(radioinputs[15]);
};
<form id="form1">
<input type="radio" class="radioanswer" name="answer16" data-index="16" value="107"/>
<input type="radio" class="radioanswer" name="answer17" data-index="17" value="109"/>
<input type="radio" class="radioanswer" name="answer15" data-index="15" value="104"/>
<button type="button" onclick="checkfunction();"> Check </button>
</form>
A class can has multiple instances, but id has only one! And you can see document about data attributes here: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
From the looks of it you have a dynamic name field, i.e. name="answer2", name="answer3", etc. Because of that your query document.getElementByName(field) will not find a field matching "answer".
To remedy this either get rid of the dynamic name or if you really need it then I would say add a class to all those radio buttons and use document.getElemenetsByClassName.

AJAX jquery not responding and showing divs

I have code a simple form in which I retrieve data dynamically and then sending it to another page. Using that data i want some divs to be displayed on my page. It is returning divs when I check it simply without using AJAX. But now I have applied some AJAX and it is not working. Any suggestions please.
AJAX
$("document").ready(function() {
$("#search_keyword").on("submit", function (e) {
e.preventDefault();
$.post("keyword_search.php?query="+encodeURIComponent($("#keyword").val())+"category="+encodeURIComponent($("#category").val())+"store="+encodeURIComponent($("#store").val()), function (data) {
var res = JSON.parse(data);
if (res.divs) {
$('#search_result').html("");
for (var i = 0; i < res.divs.length; i++) {
$('#search_result').append(res.divs[i]);
}
} else {
$('#search_result').html("No matched coupons found !");
}
});
});
});
form
<form class="form-horizontal select-search" id="search_keyword" method="post">
<label class="control-label ">Keyword</label>
<input class="form-control" id="keyword" name="keyword" type="text">
<!-- Select Category -->
<label class="control-label " for="category">Select category</label>
<select class="category" id="category" name="category">
<?php
$sm=mysqli_query($con,"select * from categories ");
while ($row1 = mysqli_fetch_array($sm,MYSQLI_ASSOC)){
$cat_id = $row1['cat_id'];
$name = $row1['cat_name'];
echo '<option value="' . $cat_id . '">' . $name . '</option>';
}
?>
</select>
<label class="control-label " for="store">Select a store</label>
<select class="storesname" id="store" name="store">
<option selected="selected">Select Stores</option>
</select>
<button id="search_btn" name="search_btn" class="btn btn-danger">Search coupons</button>
</form>
<div id="search_result"> </div>
You need to change from button to submit type so that it can actually submit.
So change:-
<button id="search_btn" name="search_btn" class="btn btn-danger">Search coupons</button>
To:-
<input type="submit" id="search_btn" name="search_btn" class="btn btn-danger" value="Search coupons"/>
Note:- Make sure that jQuery library added before your script code so that it will work.
Change your code like below:-
$("document").ready(function() {
$("#search_keyword").on("submit", function (e) {
e.preventDefault();
var data = {'query':encodeURIComponent($("#keyword").val()),'category':encodeURIComponent($("#category").val()),'store':encodeURIComponent($("#store").val())};
$.post("keyword_search.php",data, function (data) {
var res = JSON.parse(data);
if (res.divs) {
$('#search_result').html("");
for (var i = 0; i < res.divs.length; i++) {
$('#search_result').append(res.divs[i]);
}
} else {
$('#search_result').html("No matched coupons found !");
}
});
});
});
And in your keyword_search.php check like this:-
<?php
echo "<pre/>";print_r($_POST); //check that how post data are coming
// rest do code accordingly
?>
Also remove method="post" from your current <form>
You just to change some thing in jQuery.
I have just changed "submit" to "click" and "#search_keyword" to "#search_btn"
$("document").ready(function() {
$("#search_btn").on("click", function (e) {
e.preventDefault();
$.post("keyword_search.php?query=" + encodeURIComponent($("#keyword").val())+encodeURIComponent($("#category").val())+encodeURIComponent($("#store").val()), function (data) {
var res = JSON.parse(data);
if (res.divs) {
$('#search_result').html("");
for (var i = 0; i < res.divs.length; i++) {
$('#search_result').append(res.divs[i]);
}
} else {
$('#search_result').html("No matched coupons found !");
}
});
});
});
It might help you

how to get two dynamic textbox value in jquery

Thanks in advance, Actually i have a form with two hidden textbox fields one is <input type="hidden" name="item_name" class="course_name" value="<?php echo $cartData['exam'];?>"> and the other is <input type="hidden" name="amount" class="amount" value="<?php echo $priceTotal;?>">, the the value is taken inside the hidden field dynamically from PHP code through loop. So how can i get the dynamic values of "item_name" textbox field and "amount" textbox field in comma seperated using Jquery when clicking the image button with id="placeOrder".
For example like this : for amount-->200,300 and for course name -->PMP,CAPM . I have written some code it will take the values within the jquery each loop but i have to pass through ajax as json format like this data : {cname:course_name,priceBox:textboxVal} so value with comma seperated value should pass through course_name & textboxVal.
My Page is
<html>
<head>
<title></title>
<script>
$(document).ready(function(){
var myArray = [];
$('.amount').each(function(){
var textboxVal = $(this).val();
//alert(textboxVal);
});
var myCourse = [];
//dynamic course name
$('.course_name').each(function(){
var course_name = $(this).val();
//alert(course_name);
});
if(textboxVal!="")
{
$.ajax({
type : "POST",
url : "/invl_exams/cart",
cache : "false",
data : {cname:course_name,priceBox:textboxVal},
success : function(result){
console.log(result);
}
});
}
});
</script>
</head>
</html>
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
<td>
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="shopbusiness#myshop.com">
<input type="hidden" name="upload" value="1">
<?php
if(isset($cartDatas))
{
$itm_no = 1;
$amt = 0;
foreach($cartDatas as $key=> $cartData)
{
$prices = $cartData['price'];
$prd_price = ltrim($prices,'$');
$priceTotal = number_format((float)$prd_price, 2, '.', '');
?>
<input type="hidden" name="item_number" value="<?php echo $itm_no++;?>">
<input type="hidden" name="item_name" class="course_name" value="<?php echo $cartData['exam'];?>">
<input type="hidden" name="amount" class="amount" value="<?php echo $priceTotal;?>">
<input type="hidden" name="shipping" value="shipping Address">
<input type="hidden" name="quantity" value="<?php echo $cartData['orders'];?>">
<?php
$price = ltrim($prices,'$');
$orders = $cartData['orders'];
$amt_Total = $price * $orders;
$amt += $amt_Total;
$amt_Total = number_format((float)$amt, 2, '.', '');
///$amt_Total = round($price * floatval( $orders ),2);
}
?>
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="amount" value="<?php echo $amt_Total;?>">
<?php
}
?>
<input type="image" src="http://www.paypal.com/en_US/i/btn/x-click-but03.gif" name="submit" id="placeOrder">
</td>
</form>
You can do something like following:
$(function(){
var amount = [];
var course = [];
$('.amount').each(function(){
amount.push($(this).val());
});
$('.course_name').each(function(){
course.push($(this).val());
});
console.log(amount.join(',')); //comma seperated value
console.log(course.join(',')) //comma seperated value
});
DEMO
You can use jQuery and attribute selectors to get the value:
var item_name = $('input[name=\'item_name\']').val();
var amount = $('input[name=\'amount\']').val();
var result = item_name + ',' + amount;
Now you can put this in your click handler.
If your inputs are enclosed within form element you can use this serialize the form input values to json object and then pass it to ajax call.
var postData = $("#enclosing_form_elm").serializeObject();
and in your script add reference to serialize object function after jquery
$.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;
};
Just a demo https://plnkr.co/edit/7maJAUSdakDuvVqXhnzi?p=preview
Thanks to Convert form data to JavaScript object with jQuery

Convert Form data to JSON

<html>
<head></head>
<body>
<form name="abc" action="#" method="post">
Name: <input type="text" name="name"><br>
Age : <input type="text" age="name"><br>
<input type="submit"><br>
</form>
</body>
</html>
Can any one write this HTML code in such a way that when I will submit this form the the form data will be submitted in JSON format .
A pure JavaScript solution would be:
var form = document.getElementsByTagName('form')[0];
form.addEventListener('submit',function(event){
event.preventDefault();
var data = {
"name":this.name.value,
"age":this.age.value
};
console.log(data);
});
Try substituting name="age" for age="name" at second input type="text" , utilizing .serializeArray() , $.post()
$("form").submit(function(e) {
e.preventDefault();
var data = $(this).serializeArray();
console.log(data);
// $.post("/path/to/server", data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<form name="abc" action="#" method="post">
Name:
<input type="text" name="name">
<br>Age :
<input type="text" name="age">
<br>
<input type="submit">
<br>
</form>
check this function
var formDataToObject = function (formElm) {
var formObj = new FormData(formElm),
result = {},
values = formObj.values(),
keys = formObj.keys(),
key;
while (!(key = keys.next()).done) {
result[key.value] = values.next().value;
}
return result;
};
Two notes here:
1) No support for multiple select options, it will return the last selected option!!
2) The loop breaks when the next() return object with done equals to true,
but this object also contains the key for the last element in the form
which is in most cases the Submit Button, so if you don't have one in the form the last element will be excluded, easy to fix.

Categories

Resources