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.
Related
I'm using jQuery to get values from ajax rest call, I'm trying to concatenate these values into an 'a' tag in order to create a pagination section for my results (picture attached).
I'm sending the HTML (divHTMLPages) but the result is not well-formed and not working, I've tried with double quotes and single but still not well-formed. So, I wonder if this is a good approach to accomplish what I need to create the pagination. The 'a' tag is going to trigger the onclick event with four parameters (query for rest call, department, row limit and the start row for display)
if (_startRow == 0) {
console.log("First page");
var currentPage = 1;
// Set Next Page
var nextPage = 2;
var startRowNextPage = _startRow + _rowLimit + 1;
var query = $('#queryU').val();
// page Link
divHTMLPages = "<strong>1</strong> ";
divHTMLPages += "<a href='#' onclick='getRESTResults(" + query + "', '" + _reg + "', " + _rowLimit + ", " + _startRow + ")>" + nextPage + "</a> ";
console.log("Next page: " + nextPage);
}
Thanks in advance for any help on this.
Pagination
Rather than trying to type out how the function should be called in an HTML string, it would be much more elegant to attach an event listener to the element in question. For example, assuming the parent element you're inserting elements into is called parent, you could do something like this:
const a = document.createElement('a');
a.href = '#';
a.textContent = nextPage;
a.onclick = () => getRESTResults(query, _reg, _rowLimit, _startRow);
parent.appendChild(a);
Once an event listener is attached, like with the onclick above, make sure not to change the innerHTML of the container (like with innerHTML += <something>), because that will corrupt any existing listeners inside the container - instead, append elements explicitly with methods like createElement and appendChild, as shown above, or use insertAdjacentHTML (which does not re-parse the whole container's contents).
$(function()
{
var query=10;
var _reg="12";
var _rowLimit="test";
var _startRow="aa";
var nextPage="testhref";
//before divHTMLPages+=,must be define divHTMLPages value
var divHTMLPages = "<a href='#' onclick=getRESTResults('"+query + "','" + _reg + "','" + _rowLimit + "','" + _startRow + "')>" + nextPage + "</a>";
///or use es6 `` Template literals
var divHTMLPages1 = `` + nextPage + ``;
$("#test").append("<div>"+divHTMLPages+"</div>");
$("#test").append("<div>"+divHTMLPages1+"</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>
So I have this code that I am trying to alter –
Original:
jQuery(document).ready(function() {
var name = '';
var firstLastName = '[[T6:[[E48:[[S334:fr-id]]-[[S334:px]]:cons.first_name]]]] [[T6:[[E48:[[S334:fr-id]]-[[S334:px]]:cons.last_name]]]]';
var screenname = '[[T6:[[S48:0:screenname]]]]';
if (screenname) {
name = screenname;
} else {
name = firstLastName;
}
var splitName = name.split('');
var nameCheck = splitName[splitName.length-1];
jQuery('#personal_page_header h2').html("Support " + name + "'s Fundraiser" );
});
someone wrote this up and are no longer here, and what I'm trying to do now is figure out how to instead of replace the existing text, add to it.
So right now what this code does is it replaces the h2 content with the constituents registered name, or screenname.
What I'm trying to do now is append to that so that it will say something like
<h2>
Welcome to my fundraiser
<br/>
"Support" + name + "'s Fundraiser"
</h2>
but unfortunately what I tried breaks the code and stops it from working.
what I tried to do is this:
jQuery('#personal_page_header h2').append('<span><br />"Support " + name + "'s Fundraiser"</span>' );
I've tried to do a variety of other things that gave the same unsuccessful result.
Any help would be really appreciated!
Thanks
This should work for you:
jQuery('#personal_page_header h2').append("<span><br/>Support " + name + "'s Fundraiser</span>");
You've just got your quotations a little out of place.
You need to concatenate your code correctly, so if you'd like to keep the " use ' to concatenate. Further you need to escape the ' inside the string with \:
jQuery('#personal_page_header h2')
.append('<span><br />"Support ' + name + '\'s Fundraiser"</span>');
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);
});
});
I am working on a simple form demo and i would like the input to display in a below the form. Currently i have it populating in the console. How do i may it display in the div when i click the submit button?
My code:
$(document).ready(function() {
$('.submitForm').on('click',function(event){
event.preventDefault();
$('#firstName').val();
$('#lastName').val();
$('#phoneNumber').val();
$('#address').val();
console.log($('#firstName').val());
console.log($('#lastName').val());
console.log($('#phoneNumber').val());
console.log($('#address').val());
});
});
Well, you're currently not putting the values anywhere but into the console.log.
I would expect to see something like (let's call your div you want the values to go to, "output"):
$(document).ready(function() {
$('.submitForm').on('click',function(event){
event.preventDefault();
// Borrowing from another response, this is better
// Putting these in variables protects you from
// 1) accidentally modifying your form values
// 2) invalid input, if you add some basic checks, like
// testing to see if the length is > 0, doesn't contain
// bad characters, etc.
var firstName = $('#firstName').val(),
lastName = $('#lastName').val(),
phone = $('#phoneNumber').val(),
address = $('#address').val();
// get a reference to the div you want to populate
var $out = $("#output");
// This is a better way of dealing with this
// because every call to .append() forces DOM
// reparsing, and if you do this too often, it can cause
// browser slowness. Better to put together one string
// and add it all at once.
$out.html("<p>" + firstName + "</p>" +
"<p>" + $('#lastName').val() + "</p>" +
"<p>" + $('#phoneNumber').val() + "</p>" +
"<p>" + $('#address').val() + "</p>");
});
});
$(document).ready(function() {
$('.submitForm').on('click',function(event){
event.preventDefault();
$(this).after('<div>First name: '+$('#firstName').val()+'<br>'+
'Last name: '+$('#lastName').val()+
' .... ');
});
});
First of all, the four lines where you read the .val() but don't do anything with it are essentially wasted cycles, you probably meant to store them in variables:
var firstName = $('#firstName').val();
var lastName = $('#lastName').val();
var phoneNumber = $('#phoneNumber').val();
var address = $('#address').val();
To show them in some other element, use the setter version of .val() for input types, or .text() if it's a display type (div, span, etc):
$('#someOtherElement').text(firstName + '\n' +
lastName + '\n'
phoneNumber + '\n'
address);
$(document).ready(function() {
$('.submitForm').on('click',function(event){
event.preventDefault();
//$('#firstName').val();
//$('#lastName').val();
//$('#phoneNumber').val();
//$('#address').val();
var htmlContent = $('#firstName').val() + '<br />' + $('#lastName').val() + '<br />' + $('#phoneNumber').val() + '<br />' + $('#address').val();
$('#ID_OF_YOUR_DIV_HERE').html(htmlContent);
});
});
Maybe this is what you're after??
You can add it to a div you want with .append(), for example
$("#divYouWantToAddTo").append($('#firstName'));
I don't know where to start... What is all that $('#....').val() in the middle there, wasting time only to throw away the result..?
What is wrong with document.getElementById('...').value instead of wasting time creating an entire jQuery object just to access something trivial?
Adding text to a node is as simple as container.appendChild(document.createTextNode(sometext)); - and if you want to have newlines between them you can also do container.appendChild(document.createElement('br'));.
There is no need for jQuery here at all...
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()