jQuery $.load Not Executing - javascript

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.)

Related

How to hide the RESET button from a record through DOM?

Can anyone tell me how to hide the RESET button using DOM?
I am trying to make a uservent script with beforeLoad function that will hide/remove RESET button from a record.
I found a solution:
var form = ctx.form;
var field = form.addField({
id: 'custpage_code',
type: 'inlinehtml',
label: 'Code'
});
field.defaultValue = '<script>' +
'document.getElementById("resetter").style.display = "none";' +
'document.getElementById("tdbody_resetter").style.display = "none";' +// removed the extra line along the button
'</script>';
The other alternative is JQuery which is already pre-loaded in NS.
var hideFld = context.form.addField({
id:'custpage_hide_buttons',
label:'not shown - hidden',
type: serverWidget.FieldType.INLINEHTML
});
var scr = "";
scr += 'jQuery("#tbl_resetter").hide();';
scr += 'jQuery("#print").hide();';
hideFld.defaultValue = "<script>jQuery(function($){require([], function(){" + scr + ";})})</script>"
You can hide almost any element with this. Just search the page source for the element ID:
The "Reset" button's element is usually a table with the ID tbl_resetter. Add multiple elements easily as above.

Chrome is outputting something different than other browsers/IDE

Problem
I am making a wikipedia viewer for FreeCodeCamp. When I execute my code using Jetbrains Webstorm IDE, I get a total of 10 extra divs created at the end of my search results.
When I do so using JSfiddle, I see the correct results, which should just be the initial 10 search results, and not +10 more empty div containers.
Any idea what's going on?
Troubleshooting
After some more digging into it, it seems like this is more of a browser issue than an IDE issue. It looks like it's just Chrome that's doing this? I tried on Firefox and IE, and it runs as normal, just like the JSfiddle. I have also tried clearing all cookies and cache on Chrome.
When I open the console log and look at the elements, in Chrome, there are clearly 10 extra empty divs, as shown here.
But in Firefox, the same code does NOT create the divs, as shown here.
Edit: Okay, so in Chrome, if you hit enter, instead of clicking on the search button, it creates the extra divs. But if you click on the search icon, the results appear correctly. Can anyone explain why? Did I place/write the .keyup() code block incorrectly?
Here's a picture of said issue.
Javascript portion:
$(function(){
$("#search-bar").keyup(function(event) {
if(event.keyCode === 13) {
$(".btn").click();
}
});
$(".btn").click(function() {
$("#results").empty();
var searchTerm = $("#search-bar").val();
var url = "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + searchTerm + "&utf8=&format=json&origin=*";
console.log(url);
$.ajax({
cache: false,
url: url,
type: 'GET',
success: function(data) {
// Create a blank array to store the specific URLs in
var urlArr = [];
for (var i=0; i <= data.query.search.length; i++) {
// Adding the variables for use here
var headerData = data.query.search[i].title;
var urlSearchTerm = headerData.replace(/\s/gi, '_');
var snippetData = data.query.search[i].snippet + "...";
var createDiv = document.createElement("div");
var createHeader = document.createElement("h1");
var createSnippet = document.createElement("p");
var divId = "div" + i.toString();
var headerId = "header" + i.toString();
var snippetId = "snippet" + i.toString();
var resultUrl = "https://en.wikipedia.org/wiki/";
urlArr[i] = resultUrl + urlSearchTerm;
// Create the div element, give it an id
// Create <h1> element, give it an id
// Create <p> element, give it an id
// Give each <div> a class
createDiv.setAttribute("id", divId);
createHeader.setAttribute("id", headerId);
createSnippet.setAttribute("id", snippetId);
createDiv.setAttribute("class", "each-result");
// appending <div> elements in the #results id element in body
// appending <h1> element to the div element
// appending <p> element to the div element
document.getElementById("results").appendChild(createDiv);
document.getElementById(divId).appendChild(createHeader);
document.getElementById(divId).appendChild(createSnippet);
// populate json data into <h1> element
// populate json data into <p> element
$("#header" + i.toString()).text(headerData);
$("#snippet" + i.toString()).html(snippetData);
// create a click event handler that does 2 things
// 1. Gives each div an element that has a URL in the resultUrl array
// 2. Opens that url in a new window
(function(i) {
$("#div" + i.toString()).click(function() {
window.open(urlArr[i]);
});
}(i));
}
}
});
});
$("#random-wiki-button").click(function() {
window.open("https://en.wikipedia.org/wiki/Special:Random");
});
});
Actual full code including html/css + JS: JSfiddle
Maybe try updating chrome?
I would try to change your for loop to for (var i=0; i < 10; i++) { that way the increment stops at the 10th item.
edited.

How to make an OR selector instead of an AND statment

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.

jQuery id does not yield text representation

I’d like to add a button to certain text fields to allow for additional input methods. Since the button should be able to reference the text field it belongs to, I'm adding a parameter to the function call within the button’s onClick() handler, containing the ID of the text field.
At least, this is my plan. When I obtain the ID of the text field, and display it in an alert, it displays nicely. However, when I use the result of $(this).attr('id') as a function parameter, I'd expect a string to be given to the function (the id of the element). Instead some weird object is given.
How do I convert that object to a string? Or is there a conceptual flaw?
<form>
<input class="joeDateTime" type="text" name="n1" id="n1" value="2014-09-01 17:30:00">
</form>
<script>
function handleJoeDateTime(e)
{
alert('Edit '+e); // shows 'Edit [object HTMLInputElement]'
}
$(document).ready(function() {
$('.joeDateTime').each(function(){
var i = $(this).attr('id');
alert(i); // shows 'n1'
$('<button onclick="handleJoeDateTime(' + i + ');return false;">πŸ“…</button>').insertAfter($(this));
});
});
</script>
You are not passing i as a string value, you are passing it as an variable. In modern browsers the element's id are copied to properties of the window object(so you can access then as global variables).
So you need to enclose them using quotes to pass i as a string value
$('<button onclick="handleJoeDateTime(\'' + i + '\');return false;">πŸ“…</button>').insertAfter($(this));
Demo: Fiddle
Also Instead of using inlined event handlers, I would recommend using jQuery event handlres
$('.joeDateTime').each(function () {
var i = $(this).attr('id');
console.log(i); // shows 'n1'
$('<button />', {
text: 'πŸ“…',
click: function () {
handleJoeDateTime(i);
return false;
}
}).insertAfter(this);
});
Demo: Fiddle
Your problem lies here:
$('<button onclick="handleJoeDateTime(' + i + ');return false;">πŸ“…</button>')
where this should be
$('<button onclick=\"handleJoeDateTime(\"' + i + '\");return false;\">πŸ“…</button>')
When you're passing an element to jQuery ( $ ), it becomes a jquery object.
It had been made to handle id, class, elements, not html chunks.
What you want is inserting a piece of concatenated elements as an html node.
so first concatenate your elements then append it with the jQuery's after() method.
(or create/append it with vanilia js var btn = document.createElement("BUTTON");)
var Button = '<button class=\"AltBut\" id=\"' + i + '\">πŸ“…</button>';
$(this).after(Button);
or ( for compacity )
$(this).after('<button class=\"AltBut\" id=\"' + i + '\">πŸ“…</button>');
In this exemple, I'm adding an id to each enabled buttons where I store your variable i
Then add a click listener to those buttons, avoid inline js at all price, for maintainability's sacke.
$('.AltBut').on('click',function(){
var i = $(this).attr("id");
alert("i= "+i);
return false;
})
The whole demo is here: http://jsfiddle.net/x6x4v90y/1/

Html TD back to DOM

the issue: I have an appending json data to html table
here's how:
In a Loop->
var image = document.createElement('img');
image.src = data.data[i].picture.data.url;
var td=document.createElement('td');
var input=document.createElement('input');
input.setAttribute('type', 'checkbox');
input.setAttribute('onclick', 'testCheckBox()');
input.setAttribute('id','testid' + i)
td.setAttribute('onclick','tdClick()')
td.setAttribute('title',data.data[i].name );
td.setAttribute('id',''+ i );
td.appendChild(input);
td.appendChild(image);
tr.appendChild(td) ;
mytable.appendChild(tr);
}
$('#maincontent').append(mytable);
After that I got the data I need in attributes,
now I want to understand how can I get the TD= ID , and any other kind of attributes after that kind of click or another, from each td... that is different
Edit:
Function fixed to this :
function testCheckBox()
{
$(':checkbox').change(function(){
var i = $(this).closest('input').attr('id');
var id = $(this).closest('td').attr('id');
var fbname = $(this).closest('td').attr('title');
console.log(id + ' : ' + this.checked);
console.log(fbname + ' : ' + this.checked);
console.log(i + ' : ' + this.checked);
friend_name[i]=fbname;
friend_id[i]=id;
});
}
console.log(friend_name);
Working just GREAT!
the new Issue is that.. if I uncheck this checkbox.. I dont know how to remove it from Array!
and another Q: can I make 1 Array and not 2 Like here? that the 'I' will have 2 Elements Inside?
You are not javascripting the right question, i mean, you ask for the .html() and not the ID value.
HTML()
Get the HTML contents of the first element in the set of matched
elements or set the HTML contents of every matched element.
Try this :
console.log($(this).attr('id'));
attr()
Get the value of an attribute for the first element in the set of
matched elements or set one or more attributes for every matched
element.

Categories

Resources