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>');
Related
At the moment i've got this code, which replaces a span class whith a hyperlink. The hyperlink includes a abbreviation and the alternate texxt for the hyperlink includes the same abbreviation. Now what i want to do is, to somehow replace the second abbreviation in the alternate text of the hyperlink. So that there isn't "click here to visit + 'name of'abbreviation" but instead an alias. So if the abbreviaton is ggl, the alias should be google. But the hyperlink shouldn't use this alias. Can sb help me? thx
(function($) {
var number = "1234567";
function linkBuilder(abbreviation) {
return "<a href='https://www.test.com/" + abbreviation + "?sitenumber=" + number + "default'>Click here to visit " + abbreviation + "</a>";
}
function linkBuilder2(abbreviation2) {
return "<a href='https://www.test.com/" + abbreviation2 + "?sitenumber=" + number + "default'>Click here to visit " + abbreviation2 + "</a>";
}
jQuery(document).ready(function() {
var fl = $(".first-link");
if (fl.length > 0) {
fl.html(linkBuilder(fl.data("abbreviation")));
}
var sl = $(".second-link");
if (sl.length > 0) {
sl.html(linkBuilder2(sl.data("abbreviation2")));
}
});
})(jQuery);
Here is a working jsfiddle:
https://jsfiddle.net/e7qdx031/1/
linkBuilder() should be re-usable, as kalsowerus mentioned.
Another thing that should be mentioned is that the following code returns a collection of elements, not just a single element.
var fl = $(".first-link");
...
var sl = $(".second-link");
The code you have provided will not function properly if there are multiple .first-link classes on the page. So instead I would iterate over each element using $.each() and run the linkBuilder() function on them individually.
As for the linkBuilder function I would modify it to accept the element object, then read the properties to retrieve alias and name. Full name is something that you seemed to indicate you need, but was not present in the code.
(function($) {
var number = "123456";
function linkBuilder($obj) {
var abbreviation = $obj.data('abbreviation');
var name = $obj.data('name');
return "<a href='https://www.test.com/" + abbreviation + "?sitenumber=" + number + "default'>Click here to visit " + name + "</a>";
}
jQuery(document).ready(function() {
$('.first-link, .second-link').each(function(index, obj){
$(obj).html(linkBuilder($(obj)));
});
});
})(jQuery);
What you probably want is something like this:
function linkBuilder(abbreviation, alias) {
return "<a href='https://www.test.com/" + abbreviation + "?sitenumber=" + number + "default'>Click here to visit " + alias + "</a>";
}
Just pass the display-name you want for your link as the second argument.
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 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.
I finally got my back-end to create the wheel codes from the checked taxonomies in the add custom post admin area.
Now, I want to add that tire code to the wheel_type taxonomy.
The below code ran great, until I added the if statement under //Add code to Taxonomy
Now nothing is working, but I get nothing in the error console.
I figure it must be a stupid syntax mistake - can anyone help me out?
Or am I missing something else?
jQuery('#replace').click(function(){
//get tire code and name
var code = jQuery('input[name="tire_code"]').val();
var name = jQuery('input[name="tire_name"]').val();
var bname = jQuery('input[name="tire_bname"]').val();
alert(code + " + " + name + " + " + bname);
//get tire brand
var tirebran = jQuery('#tire_brandchecklist').find(":checked").parent('label').text();
tirebran = jQuery.trim( tirebran );
//Add code to Taxonomy
if( term_exists( code, wheel_type ){
continue;
}
else
{
wp_insert_term( code, wheel_type );
}
//update title
var title = code + ' : ' + name + ' tires';
if(tirebran!=''){
title += ' with ' + bname + ' letters';
}
jQuery('input[name="post_title"]').focus().val(title);
});
//-->
</script>
unless i've misunderstood your question, you're trying to call wordpress methods via javascript.
term_exists() and wp_insert_term() are PHP methods within the wordpress code, not accessible directly via Javascript (unless you have written interfaces to them).
continue doesn't make any sense there; just check for !term_exists... and call wp_insert_term when it doesn't exist.
if (!term_exists(code, wheel_type)) {
wp_insert_term(code, wheel_type);
}
The continue statement is for continuing loops from the top of the loop; it does not stand on its own.
If i have
<p>someword here</p>
<span>another thing here</span>
<div id="text">other thing here</div>
<!-- any other html tags -->
How do I insert a space in first and last position of the content?
I want the result to be
<p> someword here </p>
<span> another thing here </span>
<div id="text"> other thing here </div>
<!-- after tags like <p> and before </p> there have one space -->
Naive (and incorrect!) example would be:
var victims = document.querySelectorAll('body *');
for( var i = 0; i < victims.length; i++ ) {
victims[i].innerHTML = " " + victims[i].innerHTML + " ";
}
But once you run it, you will find out that all your elements got destroyed! Because, when you are changing innerHTML, you are changing element children as well. But we can avoid that, by not replacing content, but adding it:
var padLeft = document.createTextNode( " " );
var padRight = document.createTextNode( " " );
victims[i].appendChild( padRight );
victims[i].insertBefore( padLeft, victims[i].firstChild );
Looks cool! But, o no - we ruin our script tags, images and so on. Lets fix that too:
var victims = document.querySelectorAll('body *');
for( var i = 0; i < victims.length; i++ ) {
if( victims[i].hasChildNodes ) {
var padLeft = document.createTextNode( " " );
var padRight = document.createTextNode( " " );
victims[i].appendChild( padRight );
victims[i].insertBefore( padLeft, victims[i].firstChild );
}
}
Here you got the script :) Its not cross-browser all the way down to Netscape4, but is enough to understand basic idea.
If you insist using JS + RegExp to pad every element's innerHTML then you could do:
var
r = /(<[^>]+>)(.*)(<\/[^>]+>)/g,
func = function(str) {
return str.replace(r, function(original, a, b, c) {
return a + ' ' + (r.test(b) ? func(b) : b) + ' ' + c;
});
};
func("<p name='somename'>someword here</p>");
// "<p name='somename'> someword here </p>"
func("<div>I have things here<span>And more here<p>And even more here</p></span></div>");
// "<div> I have things here<span> And more here<p> And even more here </p> </span> </div>"
This is just to show how you could do this, but I highly recommend against it. The examples I provide is extremely simple. Anything like a normal page (say, the one you are looking at now) has all sorts of tags. This would be extremely exhaustive. And not very wise.
For a single element (as you seem to be asking):
element.html(' ' + element.html() + ' ')
For every element on the page (as your example seems to indicate), apply that to each element.
With jQuery*:
$('#id').html(' ' + $('#id').html() + ' ');
If you know that the elements do not have nested elements, it would be better to use the simpler:
$('#id').text(' ' + $('#id').text() + ' ');
(*) The reason for using jQuery and not plain javascript is that browsers (I'm looking at you, IE), have different inbuilt properties for getting and setting these values. jQuery saves you from having to worry about that.
in your case:
$("*").html(function(index, html){ return " " + html + " "; });