is possible for example, to put this on browser
https://www.mywebsite.com/index.html + one X name, let's say Pedro
and once it opens it has a text
Automatically replace this with the name from domain link
So it would say,
Hi "Pedro", is possible? thanks!
You could do the following if your url looks like this.
https://www.example.com/Pedro
In order to ensure the DOM has loaded wrap it in a DOMContentLoaded event listener.
document.addEventListener("DOMContentLoaded", function(event) {
let name = window.alert(this.href.substr(this.href.lastIndexOf('/') + 1));
let new_h3 = document.createElement('h3');
new_h3.innerHTML = `Hi ${name}`;
document.getElementById("nameHolder").appendChild(new_h3);
});
or else you could do the following which is a bit more succinct.
let name = window.alert(this.href.substr(this.href.lastIndexOf('/') + 1));
document.getElementById("nameHolder")..innerHTML = "<h3>" + `Hi ${name}` + "</h3>";
Provided you can pass it as a query (i.e. https://www.mywebsite.com/index.html?Pedro), you should then be able to do something like this:
var name = decodeURIComponent(window.location.search.substring(1));
document.getElementById("nameHolder").innerHTML = "<h3>" + name + "</h3>";
Where you have some HTML element with an id of nameHolder.
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 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 using a javascript code to write on my document :
nr = Math.floor(Math.random()*99999999999);
document.write('<div class="wads-content-' + nr + '" id="flashcontent' + nr + '">'+ flashrequired +'</div>');
var flashcontent = document.getElementById('flashcontent' + nr);
In my page, i execute this script twice. The first time everything works, but the second time, flashcontent is null, but i know it's wrong because I just write the element before the :
document.getElementById
Any idea what is happening?
Instead of document.write, do (good ol' JavaScript)
var div = document.createElement("div");
div.className = "wads-content-" + nr;
div.id = "flashcontent";
div.innerHTML = flashrequired;
The jQuery way of doing things:
$("<div/>").addClass("wads-content" + nr).attr("id", "flashcontent" + nr);
var flashcontent = $("#flashcontent" + nr);
I can only assume that the second call of document.write() occurs after the document has been loaded. The document is overwritten by the call then, as the output stream has been closed. See also W3C DOM Level 2 HTML.
My solution was to use this code :
var div = document.createElement("div");
div.innerHTML = flashrequired;
//Add the flash HTML (embed) in my div
addFlash(div);
var el = '<div class="wads-content-' + nr + '" id="flashcontent' + nr + '">'+ div.innerHTML +'</div>';
document.write(el);
So i don't have to find the element in my dom, i create it in javascript and just write it in my document.
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.