iterate through form elements in javascript/jquery - javascript

I am trying to iterate through all form elements with id that begins with a specified prefix and create an xml string with results, but it is getting a bit complicated as forms form input types seem to have different behaviors . Does this functionality already javascript, jQuery or third party jQuery module?
function fnPreIterate(){
var XMLstring;
$(':input[id*="f1"]').each(function() {
XMLstring += (" <" +this.name+ '>' + this.value + "</" + this.name + "> " );
});
$('#XMLstring').html("<pre>" + fnEncodeEntities(string) + "</pre>");
};

If you use:
$(this).val()
instead of
this.value
you'll save a lot of headaches with difference in form elements.
Another way to iterate is to use .serializeArray():
$.each($('#form').serializeArray(), function() {
string += (" <" +this.name+ '>' + this.value + "</" + this.name + "> " );
});
Hope this helps. Cheers
PS: To select by prefix, you should do $(':input[id^="f1"]') (use ^ instead of *)

Use $(this).val() to get the value.
Additionally you mixed up XMLString and string which results in your code creating a global variable and failing when it's called a second time.

Using jQuery you should try:
function fnPreIterate(){
var XMLstring='';
$(':input[id^="f1"]').each(function() {
var e = $(this), name=e.attr('name'), val=e.val();
XMLstring += (" <" +name+ '>' + val + "</" + name + "> " );
});
$('#XMLstring').html("<pre>" + fnEncodeEntities(XMLstring) + "</pre>");
};
I think it should work

You could make use of jQuery's serializeArray.

What is the problem you are facing?
try using $(this) selector in your function instead. something like this
$(this).attr('name') and $(this).val()

Related

Cannot Parse String via JavaScript function

I'm dynamically generate tables row (buttons) using JS- Ajax.when i parse a numeric value removeProduct function return the alert. but i cant get alert if i parse a String. can anyone help me to solve this problem
problem is in this line :
onclick='removeProduct( " + prcode + " )'
how to parse a String via function? (as a JavaScript String)
var single = alldata[i].split("##");
var rows = "";
var prcode = single[1];
rows += "<td><a class='btn' onclick='removeProduct( " + prcode + " )' href='#'><i class='fa fa-trash-o'></i></a></td></tr>";
$(rows).appendTo("#tblproductslist tbody");
Function :
function removeProduct(str) {
alert(str);
}
Thanks in advance!
Because you are trying to pass a string literal, so try to enclose the value in ""
onclick='removeProduct(\"" + prcode + "\")'
Since you are working with jquery, I would recommend you use event delegation to handle event and the data-api to store the data.
You need this:
rows += "<td><a class='btn' onclick='removeProduct( \"" + prcode + "\" )' href='#'><i class='fa fa-trash-o'></i></a></td></tr>";
If "prcode" is a string you must to quote it or it will be treated as (undefined) variable and will trigger an error.
Good luck!

How can I concatenate multiline string in javascript?

There are lots of results for the correct syntax for appending <li>'s, however I am trying to find a solution where +this['name']+ values are included in the <li>'s. firebug is displaying 'SyntaxError: unterminated string literal' and jslint is displaying 'Unclosed string'. I've tried many different variations of the placements of the commas but I haven't been able to get it to work.
$.each(data.result, function() {
$("ul").append("<li>Name: "+this['name']+"</li>
<li>Age: "+this['age']+"</li>
<li>Company: "+this['company']+"</li>
<br />");
});
Thank you.
you can escape end of line with backslash character \, like so:
$.each(data.result, function(){
$("ul").append("<li>Name: " + this['name'] + "</li> \
<li>Age: " + this['age'] + "</li> \
<li>Company: "+this['company']+"</li> \
<br />");
});
This is due to the fact that Javascript automatically insert semi-columns sometime on line end. And in this case, you string weren't close. Another solution is to close each string on each line, and using + to concat them all.
$.each(data.result, function(){
$("ul").append("<li>Name: " + this['name'] + "</li>" +
"<li>Age: " + this['age'] + "</li>" +
"<li>Company: "+this['company']+"</li>" +
"<br />");
});
(Unrelated, but you <br/> aren't allowed inside a <ul> element)
This should be much faster
li = '';
$.each(data.result, function(){
li += "<li>Name: " + this['name'] + "</li>" +
"<li>Age: " + this['age'] + "</li>" +
"<li>Company: "+this['company']+"</li>" +
"<br />"; // could remove this and use css
});
$("ul").append(li);
See http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/
You actually don't want to concatenate this at all! Consider for a moment what will happen to variable data that contains HTML or HTML-like data. Using your method, it will be parsed as such, possibly breaking things and even opening you up to XSS attack methods.
You're already using jQuery, so the proper way is easy:
$('ul').append(
$('<li/>').text('Name: ' + this.name),
$('<li/>').text('Age: ' + this.age),
// etc.
);
(Note: I believe .append() allows as many parameters as you give it. If not, try using an array of elements as you append.)

Javascript Parameter Passing Not Working

The code dynamically creates a listview which works but i want to make it so when a listview item is clicked it sends the a url paramater to another method. When i set a paramater it doesnt alert the paramater, but when i give no parameter it works.
var output =
"<li onclick='openURL()'><h3> Module Code: " +
results.rows.item(i).module
+ "</h3>Room: "
+ results.rows.item(i).room +
"</li>";
The above works - No parameter in openURL();
var output =
"<li onclick='openURL('" + results.rows.item(i).url + "')'><h3> Module Code: " +
results.rows.item(i).module
+ "</h3>Room: "
+ results.rows.item(i).room +
"</li>";
The above doesnt work - I have done alert(results.rows.item(i).url) and it has a value.
function openURL(url) {
alert("opening url " + url);
}
Could someone explain what i'm doing wrong, i've been trying to solve the problem for hours.
Cheers!
You are using single quotes to open the HTML attribute, you can't use it as JavaScript String because you'll be closing the HTML attribute, use double quotes:
var output =
"<li onclick='openURL(\"" + results.rows.item(i).url + "\")'><h3> Module Code: " +
results.rows.item(i).module
+ "</h3>Room: "
+ results.rows.item(i).room +
"</li>";

Javascript function call with arguments

I am developing a mobile application using phonegap and jquery mobile. I have this function which has to pass a variable to another function. It goes something like this:
$.each(response.records, function(i, contact) {
var url = contact.Id;
var newLi = $("<li><a href='javascript:dothis("+url+")'>" + (i+1) + " - " + contact.Name + " - Company "+contact.Company+"</a></li>");
ul.append(newLi);}
I have the dothis(argument) function but it does not get called when i put in the variable "url". When i erase the argument, it works. Please Help!
It's definitely not good practice to use the javascript: protocol in href attributes. It's much better to bind events to the links and respond accordingly.
Insert something like this after you append newLi to the ul:
$.find('a').bind('click', function() {
dothis(url);
});
Here's some more info about why it's bad practice to use the javascript: protocol:
Why is it bad practice to use links with the javascript: "protocol"?
You need to put the url in quotes in the javascript:
var newLi = $("<li><a href=\"javascript:dothis('" +
url +
"')\">" +
(i+1) + " - " + contact.Name +
" - Company " + contact.Company + "</a></li>");
You might need to consider escaping the URL so that, if it contains any difficult characters, your javascript won't break.

onMouseOver(SomeInt, SomeString) not working

I'm creating the following div using javascript, task_id is an int and person_name is a string, why is my alert not working!
when i send 2 integers, the alert works fine, when i send 2 strings the alert still doesn't work, what am i doing wrong?
'<div " onMouseOver="Drag(' + task_id + ',' + person_name +');"</div>'
.....
function Drag(id, name){
alert(id + " " + name);
}
thanks a million in advance
You need to correctly add escaped string delimiters around the string, otherwise you're sending a variable with the name of person_name's value. Try:
'<div onMouseOver="Drag(' + task_id + ',\'' + person_name +'\');"></div>'

Categories