This is my jQuery part that makes my menu for my pages.
function fetchmenus() {
$.getJSON('sys/classes/fetch.php?proccess=1', function(status) {
// get line status
$.each(status, function(i, item) {
if (item.id == "1") {
active = "class='active'";
lastpageid = item.href;
}
else {
active = "class='nonactive'";
}
$('<li id="' + item.href + '" ' + active + '>' + item.menuTitle + '<span class="menuspan" id="' + item.href + '"></span></li>').appendTo('#menuarea ul#mainmenu');
});
});
}
What I want to do is get the item.menuTitle in the <a but before the <span>.
Currently I do it on this way:
$('ul#mainmenu li').live('click', function(event) {
//alert(this.id);
$("li#" + lastpageid).removeClass();
fetchpage(this.id);
$("#largemenutop").html($(this).text());
$("li#" + this.id).addClass("active");
lastpageid = this.id;
});;
Is there a better way to do this?
Nice solution Herman, though it can be reduced to something like this:
JS
$('li a').contents().filter(function() {
return this.nodeType == 3;
}).text();
HTML
<li>Apple<span>hi</span> Juice</li>
Will return Apple Juice
Fiddle: http://jsfiddle.net/49sHa/1/
Yes, you can select only the text contents of the element, like this:
var text = '';
$('a').contents().each(function(){
if(this.nodeType === 3){
text += this.wholeText;
}
});
$("#largemenutop").html(text);
Related
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 4 years ago.
I am using jquery to pull in JSON and loop through the results to create a collection of items. Namely, Anchors with a few data attributes. I then am watching those items so that on click I can pull the relevant data attributes and... do things with that data. When I hard code in the anchors with the data, everything works great. When I create them dynamically through the JSON I get nothing, and the page refreshes.
jQuery( document ).ready(function() {
$.getJSON("http://glacier.creativefilterdev.com/wp-json/wp/v2/chocolate?categories=42&per_page=100&order=asc", function(result) {
$.each(result, function(i, item) {
if(item.better_featured_image == null){
} else {
$(".white").append("<a class=\"choc-option\" href=\"\" data-text=\"" + item.title.rendered + ", \" data-img=\"" + item.better_featured_image.media_details.sizes.thumbnail.source_url + "\"><img class=\"chocolate\" src=\"" + item.better_featured_image.media_details.sizes.thumbnail.source_url + "\"><br>" + item.title.rendered + "</a>");
}
});
});
jQuery("a[data-text]").click(function(){
if(howMany < countVar) {
howMany += 1;
var imgurl = jQuery(".single").val();
var structure = jQuery('<div class="single" data-text="'+ jQuery(this).attr('data-text') +'"><img src="'+ jQuery(this).attr('data-img') +'"><a class="delete">-</a></div>');
jQuery('.buildbox').append(structure);
jQuery("#alert").css('display', 'none');
} else {
jQuery("#alert").css('display', 'block');
}
return false;
});
});
I apologize as there is code in there that I haven't explained as that is the "stuff" I'm doing with the data from the anchors.
You can do it like this
jQuery( document ).ready(function() {
$.getJSON("http://glacier.creativefilterdev.com/wp-json/wp/v2/chocolate?categories=42&per_page=100&order=asc", function(result) {
$.each(result, function(i, item) {
if(item.better_featured_image == null){
} else {
$(".white").append("<a class=\"choc-option\" href='' data-text=\"" + item.title.rendered + ", \" data-img=\"" + item.better_featured_image.media_details.sizes.thumbnail.source_url + "\"><img class=\"chocolate\" src=\"" + item.better_featured_image.media_details.sizes.thumbnail.source_url + "\"><br>" + item.title.rendered + "</a>");
}
});
});
$('body').on('click', 'a[data-text]', function(e) {
e.preventDefault();
alert('test');
if(howMany < countVar) {
howMany += 1;
var imgurl = jQuery(".single").val();
var structure = jQuery('<div class="single" data-text="'+ jQuery(this).attr('data-text') +'"><img src="'+ jQuery(this).attr('data-img') +'"><a class="delete">-</a></div>');
jQuery('.buildbox').append(structure);
jQuery("#alert").css('display', 'none');
} else {
jQuery("#alert").css('display', 'block');
}
return false;
});
});
Please take a look at the following jsfiddle.
https://jsfiddle.net/51Le6o06/42/
As you can see the table filter ('.filter-gift') populates itself with data from the HTML table below it. I have hidden all other scripts to make this easier to see.
The problem is when I select a filter for instance "Free TV" the corresponding table filters correctly, but if I then select the default filter option in the table the filter hides all rows.
Ideally selecting the default option "-Select-" should display all rows, how can I change my code so this is the case with my function.
jQuery/Javascript used:
$(document).ready(function() {
$('.filter-gift').each(filterItems);
});
function filterItems(e) {
var items = [];
var table = '';
tableId = $(this).parent().parent().attr('tag')
var listItems = "";
listItems += "<option value='0'> -Select- </option>";
$('div[tag="' + tableId + '"] table.internalActivities .information').each(function (i) {
var itm = $(this)[0].innerText;
if ($.inArray(itm, items) == -1) {
items.push($(this)[0].innerText);
listItems += "<option value='" + i + "'>" + $(this)[0].innerText + "</option>";
}
});
$('div[tag="' + tableId+ '"] .filter-gift').html(listItems);
$('.filter-gift').change(function () {
var tableIdC = $(this).parent().parent().attr('tag');
var text = $('div[tag="' + tableIdC + '"] select option:selected')[0].text.replace(/(\r\n|\n|\r| |)/gm, "");;
$('div[tag="' + tableIdC + '"] .product-information-row').each(function (i) {
if ($(this).text().replace(/(\r\n|\n|\r| |)/gm, "") == text) {
$(this).show();
$(this).prev().show();
$(this).next().show();
}
else {
$(this).hide();
$(this).prev().hide();
$(this).next().hide();
}
});
});
}
set value to 999 > use if($(this).val()!= 999) else statement as below
$('.filter-gift').change(function () {
if($(this).val()!= 999) {
var tableIdC = $(this).parent().parent().attr('tag');
var text = $('div[tag="' + tableIdC + '"] select option:selected')[0].text.replace(/(\r\n|\n|\r| |)/gm, "");;
$('div[tag="' + tableIdC + '"] .product-information-row').each(function (i) {
if ($(this).text().replace(/(\r\n|\n|\r| |)/gm, "") == text) {
$(this).show();
$(this).prev().show();
$(this).next().show();
}
else {
$(this).hide();
$(this).prev().hide();
$(this).next().hide();
}
});
} else {
$(this).parent().parent().find('table tr').show();
}
});
I'm trying to use my text input as a string variable and use that variable as a part of a URL to pull up JSON data but I can't seem to get it to work properly.
I don't know if I'm setting the variables incorrectly but any help would be appreciated. Thank you!
$(document).ready(function() {
var p = document.querySelector('p');
var input = document.getElementById('search').value;
$("#go").click(function() {
if (input === '') {
p.style.backgroundColor = 'transparent';
p.classList.add = 'hide';
p.innerHTML = '';
} else {
$.getJSON("https://en.wikipedia.org/w/api.php?action=opensearch&datatype=json&limit=5&search=" + input + "&callback=?", function(data) {
p.innerHTML = "<br> Click the links below";
p.classList.remove('hide');
var i = 0
for (i; i < 5; i++){
if (data[3][i] !== undefined){
p.innerHTML += '<h2> <a href ="' + data[3][i] + '" target = "_blank">' + data[1][i] + '<br>' + '<h3>' + data[2][i] + '</h3>' + '</h2>'
} else {
p.innerHTML = ' <h2> No matching result </h2>';
}
}
});
}
});
});
At the time you assign the variable value, it is empty because it is run when the site is loaded and there is probably no text in the search box yet. You want the content at the time #go is clicked, so just assign it inside the click event handler:
$(document).ready(function() {
var p = document.querySelector('p');
// the text field value is empty at this point
$("#go").click(function() {
// this is run when user clicks #go
var input = document.getElementById('search').value;
if (input === '') {
p.style.backgroundColor = 'transparent';
p.classList.add = 'hide';
p.innerHTML = '';
}
else {
// encode user input
$.getJSON("https://en.wikipedia.org/w/api.php?action=opensearch&datatype=json&limit=5&search=" + encodeURIComponent(input) + "&callback=?", function(data) {
p.innerHTML = "<br> Click the links below";
p.classList.remove('hide');
var i = 0
for (i; i < 5; i++){
if (data[3][i] !== undefined){
p.innerHTML += '<h2> <a href ="' + data[3][i] + '" target = "_blank">' + data[1][i] + '<br>' + '<h3>' + data[2][i] + '</h3>' + '</h2>'
}
else {
p.innerHTML = ' <h2> No matching result </h2>';
}
}
});
}
});
});
Additionally, you should always encode user input if you include it in a URI. Otherwise you'll experience unexpected behaviour when using any non alphanumerical character (including whitespace) in the search box. For a more detailed explanation of how and why, see the documentation.
I have this java script function
function showHideSearchPanel(dv) {
var Header = dv == 'Charts' ? 'ChartSearch' : 'ReportSearch';
var div = "ctl00_ContentPlaceHolder1_dv" + Header;
var panel = "ctl00_ContentPlaceHolder1_pnl" + Header;
var hiddenField = "ctl00_ContentPlaceHolder1_hdn" + Header + "Mode";
// I try to add this code in js but it not work
**var serchtextbox = document.getElementById("ctl00_ContentPlaceHolder1_txtSearchName");
if (serchtextbox != null) {
serchtextbox.focus();
}**
// I try to add this code in js but it not work
if ($("#" + div).attr('display') != 'block') {
window.status = 'Expanding contents....';
$("#" + div).slideToggle("slow");
$("#" + div).attr('visibility', 'visible');
$("#" + div).attr('display', 'block');
window.status = 'Done';
}
else {
window.status = 'Collapsing contents....';
$("#" + div).hide("slow");
$("#" + div).attr('visibility', 'hidden');
$("#" + div).attr('display', 'none');
window.status = 'Done';
}
$("#" + hiddenField).attr('value', ($("#" + hiddenField).attr('value') == 'On' ? 'Off' : 'On'));
}
This is my simple menu
When click on search button i want set focu on search textbox which is in below image
This is my jquery code:
$(document).ready(function() {
var contentText = $.ajax({
url: "index.php",
async: false
}).responseText;
$("#defaultData").append(contentText);
$('img').each(function(){
$(this).remove();
});
//delegate?
var test = 0;
var href = 0;
var title = 0;
$('.btn').click(function(){
var href = $('a').each(function() {
$(this).attr('href');
});
console.log(href);
var test = $('a').each(function() {
$(this).text();
});
console.log(test);
$.each(href, function(i, val) {
$("#data").append(i + " => " + val + "<br/>");
});
$.each(test, function(i, val) {
$("#data").append(i + " => " + val + "<br/>");
});
});
//for (var i = 0; 50; i++) {
//var pageNum = $("a#specificLink").attr("href").match(/page=([0-9]+)/)[1];
});
What this code does:
It gets a page (index.php) prints it, removes the images and gets the href and text from all a-tags.
1st question:
text
should give me: link and text
but it gives me link and link :s
I realy don't get this
2nd question:
Alse I want to append the href and text to a div, seperated by semi colons.
So it looks like this:
link;text
link;text
...
Now I get:
link
link
text
text
...
This should give you all the link;text link;text
var test = "";
$('a').each(function() {
test += $(this).attr('href') + ';';
test += $(this).text() + ' ';
});
alert(test);
The reason you end up with link;link;link then text;text.. is because you are processing all links via
$.each(href, function(i, val) {
$("#data").append(i + " => " + val + "<br/>");
});
before even processing the texts. Add them at the same time as shown above.
I don't think that $('slector').each() is designed to return values. You should populate a viariable inside the loop like this:
var href = []
$('a').each(function() {
href.push($(this).attr('href'))
})
console.log(href)
Just to add, it appears that you're using .each the way that .map should be used:
var href = $('a').map(function() {
return this.href + ';' + $(this).text();
}).get();
$("#data").append(href.join(' '));