jQuery - Select with :contains then change content - javascript

I have this code below and I am trying to add html before and after a span which has no id.
I can only select it with the :contains selector.
Using this selector, how can I add my elements?
var tel = $('span:contains("+33 (0)1 02 03 04 05")');
var telText = tel.text();
var newTel = '' + telText + '';
tel.html(newTel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js">
<span>phone number</span>
<span>+33 (0)1 02 03 04 05</span>

It works here, you just have to use contains on the text that is inside the span.
var tel = $('span:contains("+33 (0)1 02 03 04 05")');
var telText = tel.text();
var newTel = '' + telText + '';
tel.html(newTel);
console.log(telText)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<span>phone number</span>
<span>+33 (0)1 02 03 04 05</span>

Related

How to convert an element into 2 elements with jquery

I have this element:
<h4>username (role) on 26 Nov 2018 20:39:42 +00:00:</h4>
and I need it to be like this:
<h4>username (role)</h4>
<p>on 26 Nov 2018 20:39:42 +00:00:</p>
There will always be 2 words in the <h4> element, but those words will vary. The <p> element will be dynamically updated to the current date and time, but will always start with "on" and end with "00:".
How can I achieve this outcome? I'm using jQuery but am fairly new to it, so I can't seem to find the right approach.
You can split on on and then use after() to create a new p:
$('h4').each(function() { // use an each so it will work if there are multiple on a page
var $h4 = $(this),
text = $h4.text(),
textParts = text.split(' on'); // split on ` on`
if (textParts.length == 2) { // only update if there is a paragraph
$h4.text(textParts[0]).after('<p>on ' + textParts[1] + '</p>'); // update the h4 text and put the new paragraph after it
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4>username (role) on 26 Nov 2018 20:39:42 +00:00:</h4>
It will be better to fix this kind of cases without the use of the JS code, but if you don't have access to the source and you really need a JS soltion, check this one:
var h4_p = $('h4').text().split(' on');
$('h4').text(h4_p[0]);
$('<p>on ' + h4_p[1] + '</p>').insertAfter($('h4'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4>username (role) on 26 Nov 2018 20:39:42 +00:00:</h4>
Code
// gets the header element and caches it since we use it twice
let header = $('h4');
// get header text
let headerText = header.text();
// run regex to get the items we need
let result = /(.*?) (on .*)/i.exec(headerText);
// create a new header for the first group found
let newHeader = '<h4>' + result[1] + '</h4>';
// create the paragraph with the second group found
let newParagraph = '<p>' + result[2] + '</p>';
// replace the current header with the new one
header.replaceWith(newHeader + newParagraph);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4>username (role) on 26 Nov 2018 20:39:42 +00:00:</h4>
Description
This answer utilizes regex and jquery to get the current header and then create the new elements.
Quick and dirty solution:
var split = $("h4").text().split(" ");
var newhtml = "<h4>"+split[0]+" "+split[1]+"</h4>";
newhtml += "<p>";
for(i = 2; i < split.length;i++){
newhtml += split[i]+" ";
}
newhtml += "</p>";
alert(newhtml)

Javascript syntax alignment (moment.js)

In working with timestamps, moment.js, and the provided example of implementation by founddrama, I added the following to my html site:
<span id="then" data-date="Aug 22 2018 11:33:00 GMT-0700 (PDT)"></span>
<script>
$(document).ready(function(){
var then = $('#then'),
date = moment(new Date(then.attr('data-date'))),
update = function(){
then.html(date.fromNow());
};
update();
setInterval(update, 60000);
});
</script>
The output result was successful.
I would, however, like to add multiple timestamps.
In order to successfully render, I coded in this manner:
<span id="then" data-date="Aug 18 2018 07:33:00 GMT-0700 (PDT)"></span>
<span id="then1" data-date1="Aug 3 2018 16:33:00 GMT-0700 (PDT)"></span>
<script>
$(document).ready(function(){
var then = $('#then'),
date = moment(new Date(then.attr('data-date'))),
update = function(){
then.html(date.fromNow());
};
update();
setInterval(update, 60000);
});
</script>
<script>
$(document).ready(function(){
var then = $('#then1'),
date = moment(new Date(then.attr('data-date1'))),
update = function(){
then.html(date.fromNow());
};
update();
setInterval(update, 60000);
});
</script>
I am looking for a clean, concise way to properly group the javascript code, and place within one script block, instead of two.
This will find all DOM elements with the class then and then find each of their data-date attributes and set their inner HTML to a moment.js object.
<span class="then" data-date="Aug 22 2018 11:33:00 GMT-0700 (PDT)"></span>
<span class="then" data-date="July 15 2018 9:33:00 GMT-0700 (PDT)"></span>
<script>
$(document).ready(function(){
var dates = $('.then');
$.each(dates, function(){
var date = moment(new Date($(this).attr('data-date')))
$(this).html(date.fromNow());
})
});
</script>
First provide the class name to span elements.
Then parse to each span elements.
Make data attribute common i.e. data-date and not different for each span.
Then parse through all the span and append the html.
<span class="then" data-date="Aug 18 2018 07:33:00 GMT-0700 (PDT)"></span>
<span class="then" data-date="Aug 3 2018 16:33:00 GMT-0700 (PDT)"></span>
<script>
$(document).ready(function(){
$('.then').each(function(i) {
var $this = $(this);
var date = moment(new Date($this.attr('data-date')));
var update = function() {
$this.html(date.fromNow());
};
update();
setInterval(update, 60000);
});
});
</script>

How to break feed line according to page width?

I don't know exactly how to say that, I'll try to express myself here.
I have this feed url :
http://v2.afilio.com.br/aff/aff_boutique_show_ads.php?boutiqueid=37930-895835&currencypos=0&display_img=1&diplay_name=1&diplay_price=1&thumbsize=80%&truncate_desc=15&numrows=1&numcols=20&colorname=000000&colorprice=E30000&bkcolor=FFFFFF&bordercolor=FFFFFF&self_target=0&
It pulls out 15 items at once, it's like a store. The problem is that it won't break the line once it reaches the full width, on the other hand, it will just add a horizontal scroll bar at the bottom.
What I need to do is, instead of displaying the items like this:
|--- WIDTH 300px ---|
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15
I need to display them like this:
|--- WIDTH 300px ---|
01 02 03 04 05 06
07 08 09 10 11 12
13 14 15
Here is my code :
http://v2.afilio.com.br/aff/aff_boutique_show_ads.php?boutiqueid=37930-895843&currencypos=0&display_img=1&diplay_name=1&diplay_price=1&thumbsize=80%&truncate_desc=15&numrows=1&numcols=20&colorname=000000&colorprice=E30000&bkcolor=FFFFFF&bordercolor=FFFFFF&self_target=0&");
echo ($a);
?>
I also would like to know if it's possible to use javascript instead of php.
If you dont have access another api endpoint (eg one that produces json or xml), then you will have to parse the html to strip the unwanted cruft;
$xml = new DOMDocument();
#$xml->loadHTMLFile('http://v2.afilio.com.br/aff/aff_boutique_show_ads.php?boutiqueid=37930-895835&currencypos=0&display_img=1&diplay_name=1&diplay_price=1&thumbsize=80%&truncate_desc=15&numrows=1&numcols=20&colorname=000000&colorprice=E30000&bkcolor=FFFFFF&bordercolor=FFFFFF&self_target=0&');
$products = array();
//Loop through each <td> tag in the dom and extract inner html
foreach($xml->getElementsByTagName('td') as $p) {
$children = $p->childNodes;
$phtml = '';
foreach ($children as $child)
{
$phtml.= $p->ownerDocument->saveHTML($child);
}
echo '<div class="product">' . $phtml . '</div>';
}
Css
<style type="text/css">
.product{
width: 100px; float:left;
}
</style>

Typeerror: Undefined form element in FireFox only

For some reason I am getting an error in FireFox only:
Typeerror: document.forms.myCity.optionname is undefined
The script works in all the other browsers:
function WriteCookie()
{
document.cookie = "city" + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
cookievalue = document.forms['myCity'].optionname.value + ";";
document.cookie='city='+cookievalue +'; expires=Fri, 3 Aug 2021 20:47:11 UTC; path=/';
window.location.href = "http://mywebsite.com";
}
This script is in the header and is executed by this form:
<form name="myCity" action="http://mywebsite.com/" method="POST">
<?php
function get_terms_dropdown($taxonomies, $args){
$myterms = get_terms($taxonomies, $args);
$optionname = "optionname";
$emptyvalue = "";
$output ="<select name='". $optionname ."'><option selected='". $selected . "' value='" . $emptyvalue . "'>Select a City</option>'";
foreach($myterms as $term){
$term_taxonomy=$term->pa_city; //CHANGE ME
$term_slug=$term->slug;
$term_name =$term->name;
$link = $term_slug;
$output .="<option name='".$link."' value='".$link."'>".$term_name."</option>";
}
$output .="</select>";
return $output;
}
$taxonomies = array('pa_city');
$args = array('order'=>'ASC','hide_empty'=>true);
echo get_terms_dropdown($taxonomies, $args);
?>
<input type="submit" value="click" name="submit" onclick="WriteCookie()">
</form>
The error is only in FireFox, any ideas?
Your error is this:
Typeerror: document.forms.myCity.optionname is undefined
I believe the issue is in this element:
<form name="myCity" action="http://mywebsite.com/" method="POST">
It looks like forms use the id selector instead of the name selector. I ran into this issue before, and I solved it by placing both id and name into the <form> element. The only explicit online reference I can find to this is here from the MSN XHTML Standards page:
The name attribute on the form element is not allowed in XHTML 1.1
guidelines.
I also found a discussion thread here on XHML 1.1 strict standards & forms that makes reference to it as well:
The W3 says the name attribute is deprecated a deprecated part of HTML
4.0 and only the ID tag fits the new XHTML 1.1 standards.
And then I found this official W3 reference that nails the issue on the head; emphasis is mine:
name = cdata [CI]
This attribute names the element so that it may be
referred to from style sheets or scripts. Note. This attribute has
been included for backwards compatibility. Applications should use the
id attribute to identify elements.
So just add an id attribute to that element like this:
<form name="myCity" id="myCity" action="http://mywebsite.com/" method="POST">
You want to have both name and id in there to cover all bases on different browsers and their implementation of XHTML 1.1 standards.
But if somehow that still does not work, just do this instead in your JavaScript on top of the id change:
function WriteCookie()
{
document.cookie = "city" + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
cookievalue = document.getElementById("myCity").optionname.value + ";";
document.cookie='city='+cookievalue +'; expires=Fri, 3 Aug 2021 20:47:11 UTC; path=/';
window.location.href = "http://mywebsite.com";
}
I changed the line that read like this:
cookievalue = document.forms['myCity'].optionname.value + ";";
To be this:
cookievalue = document.getElementById("myCity").optionname.value + ";";

Cookie (document.cookie)

Iep, i have a problem, its the first time that im working with cookies and i was trying to save them.
The question is that only the 2 first values are saved, in this case "nombre" and "tuValor". If i do "alert(document.cookie)" the other values dont apear.
<script type="text/javascript">
function guardar() {
Nombre = "Empire";
tuValor = "F"+food;
tuValor2 = "w"+wood;
caduca = "31 Dec 2020 23:59:59 GMT";
document.cookie = Nombre+"="+tuValor+tuValor2+"expire= "+caduca ;
}
</script>
You forgot the semicolon before expire.
It goes like this:
document.cookie="my_cookie=empireWh4t3v3r;expires=Thu, 23 Apr 2020 15:37:15 GMT;"

Categories