JavaScript form input loop help - javascript

I have a form that currently only parses the first input variable in the POST.
I have had to add multiple variables, so I would like the function to loop through and grab all the input parameters and add to the POST
Here's the working code for grabbing the first name and value.... How can I get it to check the form and grab all custom name's and variables.
example here
// dynamically add key/value pair to POST body
function read_custom_param(){
var nameEl = document.getElementById("custom_name");
var valueEl = document.getElementById("custom_value");
// save custom param name and value
var cust_param_name = nameEl.value;
var cust_param_value = valueEl.value;
// remove old custom param form elements
if (valueEl.parentNode && valueEl.parentNode.removeChild){
valueEl.parentNode.removeChild(valueEl);
}
if (nameEl.parentNode && nameEl.parentNode.removeChild){
nameEl.parentNode.removeChild(nameEl);
}
// add new custom param form elements
var el=document.createElement("input");
el.type="text";
el.name=cust_param_name;
el.value=cust_param_value;
document.getElementById("dcapiform").appendChild(el);
}
Kind Regards,
Chris

for whatever purpose ur trying to send ambiguous field names to the server, here is what ur looking for (u should consider a smarter way, may br processing on the server side instead)
var elems = document.getElementsByTagName("input");
var arr = [];
for (var i = 0; i<elems.length; i++){
if (elems[i].type != "text") continue;
if (elems[i].name.indexOf("custom_name") < 0) continue;
var index = parseInt(elems[i].name.substring(11)); // you should rename custom_name to custom_name1, and so for custom_value
arr[arr.length] = elems[i].value+"=" + elems["custom_value"+index].value;
}
document.forms[0]["passedITems"] = arr.join(",");
docmentt.forms[0].submit();
on your server side, read "passedItems", and split by ",", you get an array of "name=value", split again on "=" you get a sub array of name, and value

Related

Firebase storing key only if it contains given data - javascript/jquery

I want to perform a if statement and only get the details from a key if a given value is present under the key field.
For example, given the below dataset
I want to search if the database 'jokes' contain text like 'HaHa', if it does, I want to make reference to the ID of that data set, in this case 'K9WJOahmsqmuPQbl8wD' and then perform a if statement only on the data under this ID.
for example,
var MyFirebase = data.val();
var keys = object.keys(MyFirebase); // This line gets all the keys in the table
// This loops through the keys
for (var i = 0; i < keys.length; i++){
var key = keys[i];
var author = MyFirebase[key].author;
var jokeText= MyFirebase[key].jokeText;
var votes= MyFirebase[key].votes;
// Now I want to carry out a if statement, that checks if given text is inside that id
IF jokeText == "HAHA" && author == "test"
getID = getParentID
IF getID IS parent of "HAHA" && "test"
DOsomething
ELSE
DOsomethingELSE
} // end for loop
I hope I have made myself clear, if not, please let me know :)

Validating multiple fields in an HTML form using JS

I have a signup form which is having some 12 fields. I want to validate data in those fields. First step is to check if any field is empty. One way of doing this is to get each field using Jquery and check if it is empty. I was planning to create a var array and check status of each field inside a loop using this code :
var input = new Array();
input[0] = $('.fullName')[0];
input[1] = $('.emailID')[1];
input[2] = $('.phno')[2];
input[3] = $('.userName')[3];
input[4] = $('.password')[4];
input[5] = $('.batch')[5];
input[6] = $('.nickname')[6]
input[7] = $('.enrno')[7];
input[8] = $('.dob')[8];
input[9] = $('.fromCity')[9];
input[10] = $('.currcity')[10];
input[11] = $('.interests')[11];
input[12] = $('.currComp')[12];
input[13] = $('.currDesig')[13];
Now I have to run a loop to get the values and check if any field is blank.
I am writing this code for checking
for(i=0;i<14;i++)
if(input[i].val()=="")
{
// do my work
}
But the problem is that the last 15 lines of code are pointing to actual HTML DOM element, so I can't use input[i].val() directly to access the value. Any way out?
You seriously need to just add a common class to the elements that needs validation, and then do
var is_valid = $('.validate_these').filter(function() {
return $.trim(this.value) === "";
}).length === 0;
That gets all the elements with that class, and filters them based on wether or not the value is empty. If no empty elements where found, it's valid

Assign new value to variable using itself

This doesn't work but I can't see why it wouldn't? any help people? :)
params = qs.split("=", 2),
id = params[1];
if(id.indexOf("?") != -1){
id = id.split("?", 1);
}
basically I want to change the value of 'ID' if the IF statement is true, if not.. it skips it and the value Id remains the default.
Thanks
The result of id = id.split("?", 1) is an array (of at most 1 item), but I think you want id to be a string. That would explain why id is not a string like you want.
I agree with the other comments. Please show us the URL string you want to parse and tell us which piece you're trying to get. Usually, you look for ? first, separate after that and then divide up various key=value sections.
If you had a URL like this:
http://www.example.com?foo=bar
Here's a simple function that gets you all the query parameters into an object:
function getParms(url) {
var sections, key, pieces = url.split("?");
var results = {};
if (pieces.length > 1) {
sections = pieces[1].split("&");
for (var i = 0; i < sections.length; i++) {
key = sections[i].split("=");
results[key[0]] = key[1];
}
}
return(results);
}
Working demo: http://jsfiddle.net/jfriend00/kNG3u/

Looping over array and comparing to regex

So, I'll admit to being a bit of a JS noob, but as far as I can tell, this should be working and it is not.
Background:
I have a form with 3 list boxes. The list boxes are named app1, db1, and db2. I'm using javascript to allow the user to add additional list boxes, increasing the name tag for each additional select box.
When I add additional app named boxes, the value increments properly for each additional field. If I try to add addtional db named selects, it fails to recognize the 2nd tag on the first loop through the array. This causes me to end up with 2 elements named db2. On each subsequent tag, it is recognized properly and is properly incremented.
Here is the HTML for the db1 tag:
<select name="db1">
*options*
</select>
And db2:
<select name="db2">
*options*
</select>
The tags are identical. Here is the function that I am using to figure out the next number in the sequence (note: tag is either app or db, tags is an array of all select tag names in the DOM, if I inspect tags, it gives me ['app1', 'db1', 'db2', '']):
function return_select_name(tag, tags) {
matches = new Array();
var re = new RegExp(tag + "\\d+", "g");
for (var i = 0; i < tags.length; i++) {
var found = re.exec(tags[i]);
if (found != null) {
matches.push(found[0]);
}
}
matches = matches.sort();
index = parseInt(/\d+/.exec(matches.last())) + 1;
index = tag + index;
return index;
}
If I add an app tag, it will return 'app2'. If I search for a db tag, it will return 'db2' on the first time through, db3 on the 2nd, etc, etc.
So basically, I'm sure I'm doing something wrong here.
I'd handle it by keeping a counter for db and a counter for app to use to generate the names.
var appCounter = 1;//set this manually or initialize to 0 and
var dbCounter = 2;//use your create function to add your elements on pageload
Then, when you go to create your next tag, just increment your counter and use that as the suffix for your name:
var newAppElement = document.createElement('select');
newAppElement.name = 'app' + (++appCounter);
..
// --OR for the db element--
var newDbElement = document.createElement('select');
newDbElement.name = 'db' + (++dbCounter );
..
The problem you are getting is that regex objects are stateful. You can fix your program by putting the regex creation inside the loop.
function return_select_name(tag, tags) {
matches = new Array();
// <-- regex was here
for (var i = 0; i < tags.length; i++) {
var re = new RegExp(tag + "\\d+", "g"); //<--- now is here
var found = re.exec(tags[i]);
if (found != null) {
matches.push(found[0]);
}
}
matches = matches.sort();
index = parseInt(/\d+/.exec(matches[matches.length-1])) + 1; //<--- I dont think matches.last is portable, btw
index = tag + index;
return index;
}
In any case, if I were to do this myself, I would probably prefer to avoid the cmplicated text matching and just store the next tag indices in a variable or hash map.
Another suggestion: if you put parenthesis in your regex:
// /tag(\d+)/
var re = new RegExp(tag + "(\\d+)", "g");
Then you can use found[1] to get your number directly, without the extra step afterwards.
I know this has already been answered, but I put this together as a proof of concept.
http://jsfiddle.net/zero21xxx/LzyTf/
It's an object so you could probably reuse it in different scenarios. Obviously there are ways it could be improved, but I thought it was cool so I thought I would share.
The console.debug only works in Chrome and maybe FF.

Get all Radio Button and Text Field values

I have a form on my page that is located in a class .class-lesson. The form itself only contains text field and radio buttons. I do not know how many of each are in the form since it is dynamically generated by PHP. Each new input in the form is named q1, q2, ... qn.
I am trying to get all the values, whether answered or not, and stored into a javascript array. This is my code so far:
// get the value of each input field
var numQuestions = $(".class-lesson label").not(".csubmit").length;
// store each answer
for (var i = 0; i < numQuestions; i++) {
// store our variables
var tempAnswer = undefined;
var tempReference = $(":input[name=q"+(i+1)+"]");
// loop through each item
if ( tempReference.attr('type') == 'radio' ) tempAnswer = $(":input[name=q"+(i+1)+"]:checked").val();
else tempAnswer = tempReference.val();
// output / store the item
alert( tempAnswer );
}
I am sure there has to be an easier way to do this but I don't know. This is why I am asking. If I don't have the :checked then it will just grab the first value of the radio group.
So, how can I make this more efficient?
To get an entire <form> (or any set of inputs) in serialized form, as it would be if submitted to the server normally (without any JavaScript involved), use .serialize(), like this:
var formData = $(".class-lesson :input").serialize();
//or...
var formData = $("#formID").serialize();
If you're submitting via AJAX for example this makes your code incredibly simple, for example:
$.post("test.php", $("#formID").serialize(), function(data) {
alert("Response was: " + data);
});

Categories

Resources