Cannot Parse String via JavaScript function - javascript

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!

Related

How to add value in href from JSON

i'm trying to create table from JSON.
I need to add a value from JSON in tag
function drawProjectRow(rowProject) {
var row = $("<tr/>")
$("#projectListTable").append(row);
row.append($("<td><a href = MY URL PLUS VALUE from rowProject.key> " + rowProject.key + "</a></td>"));
}
Here you can see the value is being rendered ,
var rowProject=2;
console.log("<td><a href ='MY URL"+rowProject+"'> " + rowProject + "</a></td>")
You can do that
row.append("<td><a href ='MY URL"+rowProject.key+"'> " + rowProject.key + "</a></td>");
Or you can follow template literals
Coolest way to handle this in JavaScript
"<td><a href = MY URL PLUS VALUE from rowProject.key> " + rowProject.key + "</a></td>"
to
`<td>${rowProject.key}</td>`;

Parentheses in string of javascript function call

I have a loop that creates links with a javascript function call in the onClick events and uses the text returned from a database as one of the parameters. My issues I am having is that sometimes this text being returned has parenthesis in them which is causing a syntax error in my code.
Example:
code:
formResults += "<a onclick='openForm(" + this.displayText + "," + this.ID + ");'>" + this.displayText + "</a>";
HTMLDisplay:
<a onclick="openForm(Example Form (Example Form 1) Application Instructions ,1108);">Example Form (Example Form 1) Application Instructions </a>
as you can see the name of the form contains a set of parenthesis. Is there anyway I can include these? The reason I need to is because the function points to another system that uses the ID and displayText in order to render the proper form.
thank you
The parenthesis aren't the problem, it's the lack of quotes inside the function.
formResults += "<a onclick='openForm(\'" + this.displayText + "," + this.ID + "\');'>" + this.displayText + "</a>";
This below snippet (from yours)
`openForm(Example Form...`)
Will throw an error because it's looking for variables Example and so on, quote that string!
I strongly suggest
code:
formResults += '<a class="openForm" data-text="'+this.displayText + '" id="'+this.ID + '">' + this.displayText + '</a>';
HTMLDisplay:
<a class="openForm" data-text="Example Form (Example Form 1) Application Instructions" id="1108">Example Form (Example Form 1) Application Instructions </a>
jQuery:
$(function() {
$(".openForm").on("click",function(e) {
e.preventDefault();
openForm($(this).data("text"),this.id);
});
});

edit (append?) a string stored in a jquery variable

I am bringing a big html string inside an ajax call that I want to modify before I use it on the page. I am wondering if it is possible to edit the string if i store it in a variable then use the newly edited string. In the success of the ajax call this is what I do :
$.each(data.arrangement, function() {
var strHere = "";
strHere = this.htmlContent;
//add new content into strHere here
var content = "<li id=" + this.id + ">" + strHere + "</li>";
htmlContent is the key for the chunk of html code I am storing in the string. It has no problem storing the string (I checked with an alert), but the issue is I need to target a div within the stored string called .widgteFooter, and then add some extra html into that (2 small divs). Is this possible with jquery?
Thanks
Convert the string into DOM elements:
domHere = $("<div>" + strHere + "</div>");
Then you can update this DOM with:
$(".widgetFooter", domHere).append("<div>...</div><div>...</div>");
Then do:
var content = "<li id=" + this.id + ">" + domHere.html() + "</li>";
An alternative way to #Barmar's would be:
var domHere = $('<div/>').html( strHere ).find('.widgetFooter')
.append('<div>....</div>');
Then finish with:
var content = '<li id="' + this.id + '">' + domHere.html() + '</li>';
You can manipulate the string, but in this case it's easier to create elements from it and then manipulate the elements:
var elements = $(this.htmlContent);
elements.find('.widgteFooter').append('<div>small</div><div>divs</div>');
Then put the elements in a list element instead of concatenating strings:
var item = $('<li>').attr('id', this.id).append(elements);
Now you can append the list element wherever you did previously append the string. (There is no point in turning into a string only to turn it into elements again.) Example:
$('#MyList').append(item);

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>";

iterate through form elements in javascript/jquery

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()

Categories