Posting variable data with variable names using jquery - javascript

I am trying to adjust the code in this question for my needs. I need to extract the title attributes from selected elements and post them but my attempt at adjusting it is not quite working...
function submit(id) {
var answers = document.getElementsByClassName("selected");
var answersobject = {qid: id}
for (var i = 0 ; i < answers.length ; i++){
var j = i + 1;
var ans = "a" + j;
answersobject[ans] = answers[i].getAttribute['title'];
}
var loc = "testsub.php";
$.redirectPost(loc, answersobject);
}
$.extend(
{
redirectPost: function(location, args)
{
var form = '';
$.each( args, function( key, value ) {
form += '<input type="hidden" name="'+key+'" value="'+value+'">';
});
$('<form action="'+location+'" method="POST">'+form+'</form>').appendTo('body').submit();
}
});
Currently it redirects but no data is being posted.

Related

Looping error in Javascript with eventHandler

I have the following Javascript code within and HTML page. Its function is to display elements on the form based on the user pressing a + button and if the element is not needed then it removes it via the user pressing the - button. Currently its throwing an error "TypeError: docs[n]" is undefined after the following sequence of events:
Select button to add elements
Remove elements not needed
Add elements back (Error Thrown)
Any help would be most appreciated
`<script language="JavaScript">`
var idx = 0;
var d;
//Make getElementsByClassName work for all of IE revs
if (!document.getElementsByClassName) {
document.getElementsByClassName = function (cn) {
var rx = new RegExp("(?:^|\\s)" + cn+ "(?:$|\\s)");
var allT = document.getElementsByTagName("*"), allCN = [],ac="", i = 0, a;
while (a = allT[i=i+1]) {
ac=a.className;
if ( ac && ac.indexOf(cn) !==-1) {
if(ac===cn){ allCN[allCN.length] = a; continue; }
rx.test(ac) ? (allCN[allCN.length] = a) : 0;
}
}
return allCN;
}
}
function add_fields(e) {
// for some reason, adding the new fields wipes out existing values, so save and restore
var docs = document.getElementsByClassName("doc");
var revs = document.getElementsByClassName("rev");
++idx;
/* console.log("test " + idx); */
var saveDocs = new Array(idx);
var saveRevs = new Array(idx);
for (n=0; n < idx; n++) {
saveDocs[n] = docs[n].value; **//Error is thrown here**
saveRevs[n] = revs[n].value;
}
node = document.getElementById("content");
theNewRow = document.createElement("tr");
theNewCell = theNewRow.insertCell(0);
theNewCell.innerHTML = "Approver Name";
theNewCell.setAttribute("style","font-size: 12pt");
theNewCell1 = theNewRow.insertCell(1);
theNewCell1.innerHTML = "<input type='text' class='doc' style='width:180px;' id='docNum0'/>";
theNewCell1.setAttribute("style","padding-left: 10px");
theNewCell2 = theNewRow.insertCell(2);
theNewCell2.innerHTML = "Approver Email";
theNewCell2.setAttribute("style","font-size: 12pt");
theNewCell2.setAttribute("style","padding-left: 10px");
theNewCell3 = theNewRow.insertCell(3);
theNewCell3.innerHTML = "<input type='text' class='rev' style='width:180px;' id='rev0'/> <input class='minusThing' type='button' style='font-size:10px' value='- '/>";
theNewCell3.setAttribute("style","padding-left: 0px");
node.appendChild( theNewRow );
// restore old arrays and add the id tags to the fields just added
docs = document.getElementsByClassName("doc");
revs = document.getElementsByClassName("rev");
for (n=0; n < idx; n++) {
docs[n].value = saveDocs[n];
revs[n].value = saveRevs[n];
}
docs[idx].id = "docNum" + idx;
revs[idx].id = "rev" + idx;
}
//for Loop the entries
function myfunction() {
alert('Inside Function')
var values = "";
for (n=0; n <= idx; n++)
{
var doc = document.getElementById("docNum"+n).value;
var rev = document.getElementById("rev"+n).value;
//alert(doc+rev);
//Call VbScript Sub and pass value
PassValues(doc,rev);
```
If you've removed all the docs, document.getElementsByClassName("doc"); is going to return an empty array. If you're incrementing idx before your loop, the loop will execute once and try to access docs[0], which is undefined.

JSON input string error using $.ajax

My web API accepts below JSON format (this is input parameter)
[{
"atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe",
"atrSpaClassLegendId": "00D18EECC47E7DF44200011302",
"atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"},
{
"atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe",
"atrSpaClassLegendId": "00D18EECC47E7DF44200011302",
"atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"
}
]
I am building request below in javascript.
var administratorId = '47fe8af8-0435-401e-9ac2-1586c8d169fe'
var districtId = '144d0d78-c8eb-48a7-9afb-fceddd55622c'
var atrUserLegendsInputs
for (i = 0; i < list.get_items().get_count() ; i++)
{
atrUserLegendsInputs += { atrSpaUserId: administratorId, atrSpaClassLegendId: list.getItem(i).get_value(), atrSpaCityDistrictId: districtId } + ',';
}
atrUserLegendsInputs = atrUserLegendsInputs.substring(0, atrUserLegendsInputs.length - 1);
var legendIds = '[' + atrUserLegendsInputs + ']';
var atrDistrictLegend = { districtID: cityDistrictId, legendIDs: legendIds };
var test = JSON.stringify(atrDistrictLegend);
getting error message:
{["The input was not valid."]}
I am not sure whether I am doing the right way. I am new to Json and ajax calls. Can you one please help me to fix this issue
Try this code
var administratorId = '47fe8af8-0435-401e-9ac2-1586c8d169fe';
var districtId = '144d0d78-c8eb-48a7-9afb-fceddd55622c';
//* create empty array for legends
var atrUserLegendsInputs = [];
for (i = 0; i < list.get_items().get_count() ; i++) {
//* put some values into legends' array
atrUserLegendsInputs.push({
atrSpaUserId: administratorId,
atrSpaClassLegendId: list.getItem(i).get_value(),
atrSpaCityDistrictId: districtId
});
}
var atrDistrictLegend = {
districtID: cityDistrictId,
legendIDs: atrUserLegendsInputs
};
var test = JSON.stringify(atrDistrictLegend);

how to return a value from function to another in js using phonegap android

I am creating an app in which i am using jquery mobile autocomplete. To create the listview i am calling a function in js file. When a user enter the character in the input field it will call the js file and then i want to call another function which is return to access the data from data base and it will create and array object and this created array i want to pass back to the function called and then it will create an li base on that array.
Here is the code inside the demoautocomplete.js
function createlist(autocomplete_name){
var objdata=['user_name','user_id'];
$( "#"+autocomplete_name).on("listviewbeforefilter", function ( e, data ) {
var autocompleteData=new Array();
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
getdatafromtable(autocompleteData,value); var dataarray=getdatafromtable(autocompleteData);
if ( value && value.length > 1 )
{
$.mobile.loading('hide');
for(var j=0;j<dataarray.length;j++)
{
html +="<li id='"+dataarray[j].id+"'>"+dataarray[j].user_name+"</li>";
}
$ul.html( html );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");
$.mobile.activePage.find('input[placeholder="Find a name..."]').attr('id','autocomplete');
}
$("ul>li").click(function()
{
var textval=$(this).text();
var id=$(this).attr('id');
$('#autocomplete').val(textval);
$.mobile.activePage.find("[data-role=listview]").children().addClass('ui-screen-hidden');
storeselectedid(id,autocompleteData);
});
});
}
function getdatafromtable(autocompleteData,value){
db.transaction(function(tx){
$.mobile.loading('show');
var selectQuery='select first_name||" "||last_name user_name,user_id from users where first_name like "%'+value+'%" or last_name like "%'+value+'%" limit 10';
var selectQuery1='select account_name user_name,account_id from crm_account where account_name like "%'+value+'%" limit 10';
tx.executeSql(selectQuery,[],function(tx,results){
var dataset=results.rows;
if(dataset.length>0){
for(var i=0;i<dataset.length;i++)
{
var item=dataset.item(i);
var element = new Object();
element['id']=autocomplete_name+"_"+i;
for(var j=0;j<objdata.length;j++)
{
element[objdata[j]]=item[objdata[j]];
}
autocompleteData[i]=element;
}
return autocompleteData;
}
});
}); }
here the script code in html from where js will be called:
$(function(){
<ul id="autocomplete" data-role="listview" data-inset="true" data-filter="true" data-filter-placeholder="Find a name..."
data-filter-theme="d" >
</ul>
var autocomplete=$(document.createElement('ul')).attr('id',autocomplete_name);
autocomplete.attr('data-role','listview');
autocomplete.attr('data-inset',true);
autocomplete.attr('data-filter',true);
autocomplete.attr('data-filter-placeholder','Find a name');
autocomplete.appendTo("#contentDemo");
createlist(autocomplete_name); });
when getdatafromtablefunction is called it should create fill the data in the array object and pass that arrayobject back to the createlistfunction and then if loop should be executed.
here is the flow of code how it should work :
1. the page is loaded then when user enters a character in the input field.
2.it will go to thejs file then input value is assign to value variable. which i want to pass to the function getdatafromtable so base o that input it fetch the data from the database.
3.the retrive is stored in the array object than its pass back to the function from where it was called.
4.After retriving the array data it should create the li listview.
Any help is appreciated.
Thanks in advance.
Assuming your getdatafromtable function is properly made to return the array
var data_array = getdatafromtable(autocompleteData);
and in your getdatafromtable function you should have a return statement returning an array
Also dont name your variable the same as an already existing function. autocompleteData in this case is both a local variable and a function name.
Edit:
$("#" + autocomplete_name).on("listviewbeforefilter", function (e, data) {
var autocompleteData = new Array();
var $ul = $(this),
$input = $(data.input),
value = $input.val(),
html = "";
$ul.html("");
getdatafromtable(autocompleteData, $ul, $input, value, html);
});
function after_data_retrieved(autocompleteData, $ul, $input, value, html) {
if (value && value.length > 1) {
$.mobile.loading('hide');
for (var j = 0; j < dataarray.length; j++) {
html += "<li id='" + dataarray[j].id + "'>" + dataarray[j].user_name + "</li>";
}
$ul.html(html);
$ul.listview("refresh");
$ul.trigger("updatelayout");
$.mobile.activePage.find('input[placeholder="Find a name..."]').attr('id', 'autocomplete');
}
$("ul>li").click(function () {
var textval = $(this).text();
var id = $(this).attr('id');
$('#autocomplete').val(textval);
$.mobile.activePage.find("[data-role=listview]").children().addClass('ui-screen-hidden');
storeselectedid(id, autocompleteData);
});
}
function getdatafromtable(autocompleteData, $ul, $input, value, html) {
db.transaction(function (tx) {
$.mobile.loading('show');
var selectQuery = 'select first_name||" "||last_name user_name,user_id from users where first_name like "%' + value + '%" or last_name like "%' + value + '%" limit 10';
var selectQuery1 = 'select account_name user_name,account_id from crm_account where account_name like "%' + value + '%" limit 10';
tx.executeSql(selectQuery, [], function (tx, results) {
var dataset = results.rows;
if (dataset.length > 0) {
for (var i = 0; i < dataset.length; i++) {
var item = dataset.item(i);
var element = new Object();
element['id'] = autocomplete_name + "_" + i;
for (var j = 0; j < objdata.length; j++) {
element[objdata[j]] = item[objdata[j]];
}
autocompleteData[i] = element;
}
}
after_data_retrieved(autocompleteData, $ul, $input, value, html);
});
});
}

passing url parameters to hidden field with javascript

I need help with below code.
What I need to do is to pass the URL parameters to these two hidden fields.
http://www.yoursite.com/index.php?fieldOne=Work&fieldTwo=Play
It doesn't seem to be working. Also I cannot add id to the form field.
<input type="hidden" name="fieldOne">
<input type="hidden" name="fieldTwo">
<script>
function FillForm() {
var FormName = "myformname";
var qLoc = location.href.indexOf('?');
if(qLoc < 0) { return; }
var q = location.href.substr(qLoc + 1);
var list = q.split('&');
for(var i = 0; i < list.length; i++) {
var kv = list[i].split('=');
if(! eval('document.'+FormName+'.'+kv[0])) { continue; }
kv[1] = unescape(kv[1]);
if(kv[1].indexOf('"') > -1) {
var re = /"/g;
kv[1] = kv[1].replace(re,'\\"');
}
eval('document.'+FormName+'.'+kv[0]+'.value="'+kv[1]+'"');
}
}
FillForm();
</script>`
NULL had it kind of there with the simplification (albiet there is a small error in your code regarding the iteration over the query). Here is NULL's simplification corrected, and also my guess as to why you're not getting the desired results:
<form name="myformname">
<input type="hidden" name="fieldOne">
<input type="hidden" name="fieldTwo">
</form>
<script type="text/javascript">
var formName = "myformname",
query = location.href.split("?").pop().split("&"),
i = 0,
len = query.length,
split, elem;
for ( ; i < len; i++ ) {
split = query[i].split("=");
//alert(split);
elem = document[formName][split[0]];
if ( elem ) {
elem.value = split[1].replace(/"/g, '\\"');
}
}
</script>
1) Make sure you're using a form tag with an id. I can't see your HTML.
2) Be sure that you are not seeing new data appear in the hidden <input>'s? I advise using a debugger and checking the live DOM tree as opposed to the source code. Some debuggers don't update the source in real-time.
EDIT:
Based on new information from the questioning party, here is another stab at a fix:
<script type="text/javascript">
$(document).ready(function(){
var formName = "dSOfferAllE10Test-1349977611926";
var query = location.href.split("?").pop().split("&");
var len = query.length;
var split, elem;
for (var i = 0; i < len; i++ ) {
split = query[i].split("=");
$('form[name="'+formName+'"]').find('input[name="'+split[0]+'"]').each(function(){
$(this).val(split[1].replace(/"/g, '\\"'));
});
}
});
</script>​​​​​​​​​​​​​​​​​​​​​​​​​​​​
This uses jQuery, so make sure that you attach a reference to jQuery in your <head> (or at least near the top of the <body> if you don't have access to the <head>. Best to grab the snippet from the Google-hosted version: https://developers.google.com/speed/libraries/devguide#jquery
You can simplify your code:
var formName = "myformname",
query = location.href.split("?").pop().split("&"),
i = 0,
len = query.length,
split, elem;
for ( ; i < len; i++ ) {
split = query.split("=");
elem = document[formName][split[0]];
if ( elem ) {
elem.value = split[1].replace(/"/g, '\\"');
}
}

How to get number of option is answered/not answered using jQuery?

In android phonegap application, I created 5 or more question with respective option (checkboxes) in div dynamically. Each question and respective option have same id. Now I want to know how many question are answered/how many questions are not answered while clicking submit button.
please guide me. Thanks in advance.
My code is:
for dynamic div: retrive value from local database
function list(results){
for (i = 0; i < results.rows.length; i++) {
$("#poll").append("<li id='"+i+"'>"+results.rows.item(i).ques+"</li>"+"<br/>" );
var optiontypearray = new Array();
var arr = results.rows.item(i).option;
var optiontypearray=arr.split(" ");
for(var j=0; j<optiontypearray.length; j++) {
$("#poll").append("<input id='"+i+"' name='ckbox' value='"+optiontypearray[j]+"' type='checkbox'/>"+optiontypearray[j]+"<br/>");
}
}
}
for submit button:get question with respective answer
function submit(){
$answers = $(':checked');
var $questions=$('li');
$answers.each(function(index,el) {
var list1=$(this).attr("id");
alert("list1:"+list1);
var val=$('#'+list1).val();
alert($questions.eq(list1).html() + ' : ' + $(el).val());
});
}
HTML:
<div id="poll">
This is what happens when you click submit button.
$('#submit').click(function () {
var questionsAnswered = questionsNotAnswered = 0
var arrQuestions = new Array();
$('li').removeAttr('style').each (function (i) {
if ($(this).children('input:checked').length > 0) {
var ans = '';
$(this).children('input:checked').each(function () {
ans+= $(this).val() + ', ';
});
arrQuestions[questionsAnswered] = new Array($(this).attr('id'), ans);
questionsAnswered++;
} else if ($(this).attr('class') == 'required' && $(this).children('input:checked').length == 0) {
$(this).css({border : '1px solid red'});
questionsNotAnswered++;
alert($(this).clone().children('span').remove().end().text());
}
});
$('div#finalResults').html("Questions Answered : " + questionsAnswered + "<br /> Questions Not Answered : " + questionsNotAnswered);
});
$.each (arrQuestions, function () {
$('div#finalResults').append("<br /> Q: " + this[0] + " A: " + this[1]);
});
Demo. http://jsfiddle.net/tmM76/9/
Please note that the code in list() function might change as per your existing code which you did not share ;-).
u can do something like..
var qanswered;
for( j = 0; j < numberofQuestions; j++){
qanswered = false;
ques = questions[j];
for( k = 0; k < ques.choices.length; k++){
btn = $('.ui-page-active input#'+k); // k is your choice id whatever way u define it
if(btn[0].checked){
qanswered = true;
}
}
if(!qanswered){
//this question is not answered, do something
}
}
btn gets the jquery object of the inputs one by one, of the ques

Categories

Resources