How to make an OR selector instead of an AND statment - javascript

This statement will look for the div #content-company and load the appropriate data when it finds it. However my problem is:
On this occasion I have to use a slider that I can't rename to the same as the div so in this instance I have an additional called .slides
I normally would do this:
// JavaScript Document
$(function(){
$('.tileSB').click(function(e){
e.preventDefault();
var url = $(this).attr('href') + ' #' + $(this).attr('data-target');
$('#content-company, .slides').load(url);
});
});
But that simply overlays both the content associated with the div and the slides class so you have them with the same name at the same time and I don't want that.
Can someone explain how I can have this?:
// JavaScript Document
$(function(){
$('.tileSB').click(function(e){
e.preventDefault();
var url = $(this).attr('href') + ' #' + $(this).attr('data-target');
$('#content-company OR .slides').load(url);
});
});
Thanks in advance

You can check if the #content-company element exists. If it doesn't you can use .slides instead. Something like this:
$('.tileSB').click(function(e){
e.preventDefault();
var url = $(this).attr('href') + ' #' + $(this).attr('data-target');
var $target = $('#content-company');
if (!$target.length)
$target = $('.slides');
$target.load(url);
});

You can use ? :(ternary operator). The code below will use the #content-company, if it existst otherwise uses .slides.
var $selector = $('#content-company').length ? $('#content-company') : $('.slides');
$selector.load(url);

You can simply use this:
$("#content-company, .slides").first()
Note that first element is determined according to HTML order. If more than one matching elements are found then the first one in HTML order is returned.

Related

jQuery $.load Not Executing

I am currently using jQuery on my Django site to reload a div once a user clicks a button.
$(document).ready(function(){
var post_list = Array.from(document.getElementsByClassName("post_container"))
for(var post in post_list){
post_list[post].id = 'post' + post;
}
var $arrows = $(".arrow");
$arrows.each(function(index){
var data = $(this).data();
var element = $(this);
element.on('click', function(event){
if(user_auth){
var currentParentElement = element.parent().parent().parent().get(0);
var id = $(currentParentElement).attr('id');
$(id).load(document.URL + ' ' + id);
}
})
})
});
From the console I can see that currentParentElement and id are pointing to the correct div to reload, but $(id).load() does not seem to be doing anything.
In the image linked below, the clicking the arrow buttons should make the green or red number change. The number does not change when the arrow is clicked, but it does change when I reload the entire page.
https://i.stack.imgur.com/T26wn.png
Your ID selector is missing the # symbol. For example, suppose the id of this target element is "myID":
var id = $(currentParentElement).attr('id');
Then the jQuery selector you're using is:
$('myID')
Which is looking for a <myID> element. There isn't one, so no matches are found, so there's nothing to call .load() on.
You could add the symbol to your selector:
$('#' + id).load(document.URL + ' #' + id);
(Note: The same correction was also made in the selector passed to load() for the same reason.)

Move array of DOM elements to placeholders in page

I have a design received on my page with a set of placeholders such as:
<span id="ApplicationDate_" class="removeMe"></span>
Plus other many elements as well inside that html. These spans should be replaced by real inputs coming from another area on the page, such inputs look like:
<input type="text" id="ApplicationDate_48596977"/>
So basically what I need to do, is to get all input elements in an array, and then for each element, get its ID up to "_", and search for the span that equals that value, and replace it with this element, then remove all spans with class=removeMe, but I can't achieve it in code, below is what I have reached:
$(document).ready(function () {
var coll = $("input");
coll.each(function () {
var id = this.id; //getting the id here
var substringId = id.substring(0, id.indexOf('_') + 1); //getting the span id
this.appendTo("#" + substringId); //having problems here..
});
$(".removeMe").each(function () {
this.remove();
});
});
it tells me this.appendTo is not a function, any help or hint is much appreciated.
TL;DR - Just use:
$(".removeMe").replaceWith(function() {
return $("input[id^='" + this.id + "']");
});
Here's why:
this is a DOM element, but .appendTo() is a jQuery method. You probably just need to wrap this in a call to jQuery:
$(this).appendTo("#" + substringId);
That would place the <input> element inside the <span> like this:
<span id="ApplicationDate_" class="removeMe">
<input type="text" id="ApplicationDate_48596977"/>
</span>
But, then you call:
$(".removeMe").each(function () {
this.remove();
});
First, you would have the same problem as above - this is a DOM element, but .remove() is a jQuery method. Second, it would be better to just call $(".removeMe").remove() - wrapping it in a .each() is redundant. Third, that would remove the span, and the input along with it. That's not what you are trying to do is it?
If you want to replace the span with the input, use .replaceWith():
var coll = $("input");
coll.each(function () {
var substringId = this.id.substring(0, id.indexOf('_') + 1);
$("#" + substringId).replaceWith(this);
});
It seems like the whole thing could be rewritten, taking advantage of the attribute starts with selector, as:
$(".removeMe").replaceWith(function() {
return $("input[id^='" + this.id + "']");
});

js How to add href + text onclick

I need to pass (using javascript) text inside span to href
<div class='tableCell'><span>information</span></div>
<div class='tableCell'><span>contact</span></div>
<div class='tableCell'><span>about</span></div>
for example when i click to about link must be example.com/tag/about/
Here is my Answer. I'm using Javascript to manipulate the DOM to add a new element with the href equal to the inner text within the span element.
I hope you find this answer helpful.
Thanks.
var spans = document.getElementsByTagName('span')
var baseUrl = 'http://example.com/tag/'
for(var i=0; i<spans.length; i++)
{
var curElement = spans[i];
var parent = curElement.parentElement;
var newAElement = document.createElement('a');
var path = baseUrl+curElement.innerHTML;
newAElement.setAttribute('href', path);
newAElement.appendChild(curElement);
parent.appendChild(newAElement)
}
DEMO
The simplest way:
$( "span" ).click(function() {
var link = 'http://yousite.com/tag/'+ $(this).text().replace(/ /, "-")+"/";
window.location.href= link.toLowerCase();
});
DEMO
http://codepen.io/tuga/pen/yNyYPM
$(".tableCell span").click(function() {
var link = $(this).text(), // will provide "about"
href = "http://example.com/tag/"+link; // append to source url
window.location.href=href; // navigate to the page
});
You can try the above code
You do not have links but span in your html. However, you can get build the href you want and assign it to an existing link:
$('div.tableCell').click(function(){
var href = 'example.com/tag/' + $(this).find('span').text();
})
Lets work with pure javascript, I know you want to use jQuery but I am really sure too many people can't do this without looking in to web with pure javascript. So here is a good way.
You can follow it from jsFiddle
var objectList = document.getElementsByClassName("tableCell");
for(var x = 0; x < objectList.length; x++){
objectList[x].addEventListener('click', function(){
top.location.href = "example.com/tag/" + this.childNodes[0].innerHTML;
});
}
Lets work on the code,
var objectList = document.getElementsByClassName("tableCell");
now we have all element with the class tableCell. This is better than $(".tableCell") in too many cases.
Now objectList[x].addEventListener('click', function(){}); using this method we added events to each object.
top.location.href = "example.com/tag/" + this.childNodes[0].innerHTML; with this line if somebody clicks to our element with class: We will change the link to his first child node's text.
I hope it is useful, try to work with pure js if you want to improve your self.
Your Method
If you always are going to have the url start with something you can do something like this. The way it is set up is...
prefix + THE SPANS TEXT + suffix
spaces in THE SPANS TEXT will be converted to -
var prefix = 'http://example.com/tag/',
suffix = '/';
$('span').click(function () {
window.location.href = prefix + $(this).text().replace(' ', '-').trim().toLowerCase() + suffix;
//An example is: "http://example.com/tag/about-us/"
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='tableCell'><span>Information</span></div>
<div class='tableCell'><span>Contact</span></div>
<div class='tableCell'><span>About</span></div>
You can adjust this easily so if you want it to end in .html instead of /, you can change the suffix. This method will also allow you to make the spans have capitalized words and spaces.
JSBIN

For Loop to Programmatically hide elements

I am currently trying to programmatically hide div elements on a page using an Array and loop in jQuery, but it doesn't seem to work.
I have done alerts and console.log to confirm the array is firing and the loop is working through the items, but it's the .hide() method that seems to be giving issue. Any help would be appreciated.
Thanks
$(document).ready(function(){
var divsToHide = ["fin_0", "fin_1", "fin_2", "fin_3", "fin_4", "fin_5",
"fin_6", "fin_7", "fin_8", "fin_9", "fin_10", "fin_10-1", "fin_10-2", "fin_10-3",
"fin_10-4", "fin_10-5", "fin_10-6", "fin_10-7", "fin_10-8", "fin_10-9", "fin_20",
"fin_21", "fin_22", "fin_23"];
$.each(divsToHide, function(index, value)
{
var currentDiv = "div#" + value;
var stringCurrent = currentDiv.toString();
var currentHide = $(' stringCurrent ');
console.log(currentDiv);
currentHide.hide();
});
});
You should probably use:
var currentHide = $(stringCurrent);
Your code
var currentHide = $(' stringCurrent ');
has no reference to stringCurrent variable, it just try to find <stringCurrent> element.
Even better, you should use
$.each(divsToHide, function(index, value)
{
$("#" + value).hide()
});
since an element id should be unique to the document
You need to remove the ' around stringCurrent. Otherwise your string is not interpreted but jquery searches for ' stringCurrent '

JQuery replace html element contents if ID begins with prefix

I am looking to move or copy the contents of an HTML element. This has been asked before and I can get innerHTML() or Jquery's html() method to work, but I am trying to automate it.
If an element's ID begins with 'rep_', replace the contents of the element after the underscore.
So,
<div id="rep_target">
Hello World.
</div>
would replace:
<div id="target">
Hrm it doesn't seem to work..
</div>​
I've tried:
$(document).ready(function() {
$('[id^="rep_"]').html(function() {
$(this).replaceAll($(this).replace('rep_', ''));
});
});​
-and-
$(document).ready(function() {
$('[id^="rep_"]').each(function() {
$(this).replace('rep_', '').html($(this));
});
​});​
Neither seem to work, however, this does work, only manual:
var target = document.getElementById('rep_target').innerHTML;
document.getElementById('target').innerHTML = target;
Related, but this is only text.
JQuery replace all text for element containing string in id
You have two basic options for the first part: replace with an HTML string, or replace with actual elements.
Option #1: HTML
$('#target').html($('#rep_target').html());
Option #2: Elements
$('#target').empty().append($('#rep_target').children());
If you have no preference, the latter option is better, as the browser won't have to re-construct all the DOM bits (whenever the browser turns HTML in to elements, it takes work and thus affects performance; option #2 avoids that work by not making the browser create any new elements).
That should cover replacing the insides. You also want to change the ID of the element, and that has only one way (that I know)
var $this = $(this)
$this.attr($this.attr('id').replace('rep_', ''));
So, putting it all together, something like:
$('[id^="rep_"]').each(function() {
var $this = $(this)
// Get the ID without the "rep_" part
var nonRepId = $this.attr('id').replace('rep_', '');
// Clear the nonRep element, then add all of the rep element's children to it
$('#' + nonRepId).empty().append($this.children());
// Alternatively you could also do:
// $('#' + nonRepId).html($this.html());
// Change the ID
$this.attr(nonRepId);
// If you're done with with the repId element, you may want to delete it:
// $this.remove();
});
should do the trick. Hope that helps.
Get the id using the attr method, remove the prefix, create a selector from it, get the HTML code from the element, and return it from the function:
$('[id^="rep_"]').html(function() {
var id = $(this).attr('id');
id = id.replace('rep_', '');
var selector = '#' + id;
return $(selector).html();
});
Or simply:
$('[id^="rep_"]').html(function() {
return $('#' + $(this).attr('id').replace('rep_', '')).html();
});
From my question, my understanding is that you want to replace the id by removing the re-_ prefix and then change the content of that div. This script will do that.
$(document).ready(function() {
var items= $('[id^="rep_"]');
$.each(items,function(){
var item=$(this);
var currentid=item.attr("id");
var newId= currentid.substring(4,currentid.length);
item.attr("id",newId).html("This does not work");
alert("newid : "+newId);
});
});
Working Sample : http://jsfiddle.net/eh3RL/13/

Categories

Resources