changing id of div using jquery - javascript

EDIT 2: Problem solved. The jquery pluggin created a div. I was barking up the wrong tree.
Thanks for all your swift answers! long time reader of stackoverflow but first time i've posted a question!
EDIT: So the reason why I want to change the id is to change the rating of a rating bar(I use the jrating jquery pluggin). The pluggin uses the digits in the beginning of the id to set the initial rating. Now I want to use ajax when I load a new player and that new player has a new rating that I want to update. Is this enough context?
Im at a loss here. I want to change the id of a selected div but it doesnt work!
I does seem to change the div id because document.title has the correct id when I give it the id of the div I just changed. However When I open the source code of my webpage the id didnt change...
function changePlayer() {
xmlhttp = createXHR();
xmlhttp.onreadystatechange = function () {
document.title = "onreadystatechange";
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.title = "4 and 200 is ok!";
var xmlDocument = xmlhttp.responseXML;
var playerId = xmlDocument.getElementsByTagName("id")[0].childNodes[0].nodeValue;
var playerName = xmlDocument.getElementsByTagName("firstName")[0].childNodes[0].nodeValue;
var playerlastName = xmlDocument.getElementsByTagName("lastName")[0].childNodes[0].nodeValue;
var playerTeamId = xmlDocument.getElementsByTagName("teamId")[0].childNodes[0].nodeValue;
var playerPicUrl = xmlDocument.getElementsByTagName("mainPic")[0].childNodes[0].nodeValue;
var playerShooting = xmlDocument.getElementsByTagName("shooting")[0].childNodes[0].nodeValue;
document.getElementById("playerNameAndTeam").innerHTML = "<b>" + playerName + " " + playerlastName + "</b>" + "<br>" + playerTeamId;
document.getElementById("playerPicture").src = "img/players/" + playerPicUrl;
$("[id*='_shooting']").attr("id", playerShooting / 10 + "_shooting"); //attr("id", "5.1_shooting");
document.title = $("[id*='_shooting']").attr("id");
$("[id*='_shooting']").css("background-color", "blue");
$("[id*='playerNameA']").css("background-color", "blue");
}
}
xmlhttp.open("GET", "playerPageMVC/AJAX/getInfoPlayer.php", true);
xmlhttp.send();
}
function createXHR() {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
} else { // code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
}

Try with Native JS like replacing this line :
$("[id*='_shooting']").attr("id",playerShooting/10 + "_shooting");
By this one :
$("[id*='_shooting']")[0].id = playerShooting/10 + "_shooting";
Caution : If $("[id*='_shooting']") match many elements, only the first will be changed.
EDIT : If you want to keep jQuery technic, depends on your version, you can try using prop(...) instead of attr(...)

when I tried changing ID with a sample code using JQuery it worked. You can view example here. Just change the id attribute
You are suppose to check the id change by inspecting element not by checking the loaded source of the web page.

If you mean your:
$("[id*='_shooting']").attr("id", playerShooting / 10 + "_shooting");
You can check that id by simply doing these:
$("[id*='_shooting']").attr("id", playerShooting / 10 + "_shooting");
alert($("#"+ playerShooting / 10 + "_shooting").attr("id"));
By viewing the source, you only view the original source, not the DOM as it exists in a current state.

Related

Chrome won't change button text in loop

In firefox all work fine. Using tampermonkey and webextensions (addons). Example of code:
while (pc == 10) {
button3.textContent = "Scraping page " + page + "..."
var url ="https://somelink.to/page?"+page
xhr.open('GET', url, false);
xhr.send();
var json = JSON.parse(xhr.responseText);
obj.push(json.posts)
pc = json.posts.length
if (page == plimit) {
pc = "what you are doing here?"
}
page++  
}
Before used .innerHtml. Also used setTimeout(button3.textContent = "Scraping page "+page+"...",300) . Not work too. I don't know why in firefox work but not in chrome. Also when button clicked it look like freezed (pressed while script running). In Firefox it just clicked.

How to display results with Javascript and cgi, besides <iframe> and <object>?

I have an input form which in realtime display the results from three different cgi-based lookups.
My first approach was to have three iframes which i change the .src for every search, which works but feels unnecessary:
<iframe id="iframe1">
document.getElementById("iframe1").src="/cgi-bin/one.cgi";
My second approach was having three object:s which have their .data changed, but that also feels and looks bad:
<object id="object1">
document.getElementById("object1").data="/cgi-bin/one.cgi";
Both of the above examples works - functionally, but I would like to know a better way to do it. For example how do I get the same results using DIVs ? I.e. no iframe:s or object:s.
The alternative is to use AJAX. This means that you have to create and send an XMLHttpRequest. When the response is received, you have to put it into a <div>.
Here's a minimalistic example:
var div = document.getElementById("results");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
div.innerHTML = this.responseText;
} else {
div.innerHTML = "<h1>Error " + this.status + "</h1><p>The content could not be loaded.</p>";
}
}
};
xhttp.open("GET", "/cgi-bin/one.cgi", true);
xhttp.send();
For cross-browser compatibility, I recommend to use this function or the jQuery ajax function.

When I use new XMLHttpRequest in a function all page reload

I'm trying a week to find a way for the following problem.
I have a 1.php file
//bowser.js And fingerprint2.js are included I ignored them here
function HttpRequest(e) {
var i = !1;
i || "undefined" == typeof XMLHttpRequest || (i = new XMLHttpRequest), i && (i.open("GET", e, !1), i.send(null), embedpage(i))
}
function embedpage(e) {
(-1 == window.location.href.indexOf("http") || 200 == e.status) && 0 != e.responseText && document.write(e.responseText)
}
browser = bowser.name;
browserv = bowser.version;
bowser.windows ? os = "windows" : bowser.mac ? os = "mac" : bowser.linux ? os = "linux" : bowser.android ? os = "android" : bowser.ios ? os = "ios" : bowser.windowsphone ? os = "windowsphone" : bowser.chromeos ? os = "chromeos" : bowser.blackberry ? os = "blackberry" : bowser.firefoxos ? os = "firefoxos" : bowser.webos ? os = "webos" : bowser.tizen ? os = "tizen" : bowser.bada ? os = "bada" : bowser.sailfish && (os = "sailfish");
new Fingerprint2().get(function(result) {
url = 'http://gotoo.cf/2.php?tag=<?php echo $_GET["tag"] ?>&browser=' + browser + '&bv=' + browserv + '&os=' + os + '&secure=' + result;
HttpRequest(url);
});
2.php make html to show banners
when I use it in my blog by:
<script type="text/javascript" src="http://gotoo.cf/1.php?tag=6&width=120&height=240"></script>
it reload all page.
you can see there
http://adseo.blogfa.com/
but when I use HttpRequest(url);out of new Fingerprint2().get(function(result) { it works perfectly.
but the big problem is url var.( because ir can not be accessible out of function)
global var and cookie does not work because Fingerprint2().get(...) is asynchronous.
I want to know why HttpRequest(url); treat like that?
and how to store fingerprint2 result like function and use it whereever I want.
Or some method that you understand.
The problem is this here:
document.write(e.responseText)
The document.write will make the browser create a new document and then insert the passed text replacing all current content of the page. Instead, you need to tell the browser to insert the text into a specific part of the already existing document.
For example:
document.body.insertAdjacentHTML('afterbegin', e.responseText)
will insert the banner at the beginning of the page. In reality, you would want to use a more specific place inside the page. Use a div with a specific id as a placeholder and then replace the content of this div with the text retrieved via the asynchronous HTTP call.
Some more explanations:
When JavaScript code uses document.write() while the page is still being loaded, the content will be written at the current position of the currently loaded document. However, since you execute your code asynchronously using Fingerprint2.get(), the code is executed after the page has finished loading and document.write() will then lead to the browser starting with a new document.
From the documentation:
The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.
How to solve your dilemma:
In your code, first add a div with a random unique identifier to the document using document.write. Then, in the callback function, that is called from Fingerprint2.get(), add the content into that div.
See the following example set of files that show the mechanism:
A.html
<html>
<body>
<script src="Banner.js"></script>
<div>Static Content</div>
<script src="Banner.js"></script>
</body>
</html>
B.html
<div>
Some Banner!
</div>
Banner.js
// Note that HttpRequest and embedpage are declared inside insertBanner
// so that they can access the aRandomName parameter
function insertBanner(aRandomName)
{
// First add a placeholder div with the given random name
document.write('<div id="' + aRandomName + '"></div>');
// Then asynchronously call HttpRequest()
// We use setTimeout where then FingerPrint2.get() would be used
url = "B.html";
setTimeout(
function()
{
HttpRequest(url);
}
, 100
);
function HttpRequest(e)
{
i = new XMLHttpRequest;
i.onreadystatechange = embedpage;
i.open("GET", e, true); // Use HttpRequest asynchronously to not block browser
i.send();
}
function embedpage(e)
{
if(this.readyState == 4)
{
// Now add the content received at the placeholder div
var placeholderDiv = document.getElementById(aRandomName);
placeholderDiv.innerHTML = this.responseText;
}
}
}
// First get a random name for the banner div
var randomName = 'GotooCF' + makeid();
// Now call the banner using the random name
insertBanner(randomName);
// makeid() Taken from http://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript
function makeid()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
As NineyBerry said, the main problem is document.write()
so I used :
document.write=function(s){
var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
lastScript.insertAdjacentHTML("beforebegin", s);
}
In all browser except Firefox it works.
But still need to be modifiled,
I think we should make a new document.write function for these situations.
thanks

nodeName returns more often than expected

I've got some code that's reading an XML document and then using that to build the HTML page. Similar to markdown I suppose. I've simplified the below code but effectively that JS line at the end with CAROUSEL in it is looking at the XML, but it is creating 7 carousel divs instead of 1 like I want. I get why it's returning 7 times (sort of), but how do I get it to only create it once. the ITEM tags inside of the CAROUSEL tag (see the XML section) is to indicate what images should be inside that particular carousel.
JS:
var col9div = null;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET",'xml/index'+page_counter+".xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var col9div = document.createElement("div");
});
var tempvar = arr.length;
console.log(tempvar);
$(col9div).addClass("col-md-9");
$("#bannersize").append(col9div);
flush();
function flush(){
var activity_element_idcounter = 0;
var module_element_idcounter = 0;
var x=xmlDoc.getElementsByTagName("MODULE");
for (i=0;i<x.length;i++)
{
var getlastli = $(".sidecounter:last");
module_element_idcounter++;
col9div.insertAdjacentHTML('beforeend', '<div class="row"><div class="col-md-12 well"' + ' id="module' + module_element_idcounter + '"><div id="skrollr-div' + module_element_idcounter + '"></div></div>');
var scanner = x[i].getElementsByTagName("*");
for (var q=0;q<scanner.length;q++){
activity_element_idcounter ++;
$.each(scanner[q].childNodes, function(){
else if (scanner[q].nodeName === "CAROUSEL"){
do something here
}
XML:
<MODULE>
<CAROUSEL>
<ITEM>assets/images/index5/tehran-carousel/tehran-day-and-night.jpg</ITEM>
<ITEM>assets/images/index5/tehran-carousel/tehran-day-and-night-1.jpg</ITEM>
<ITEM>assets/images/index5/tehran-carousel/tehran-bazaar-entrance.jpg</ITEM>
</CAROUSEL>
</MODULE>
thanks,
Robbie
I assume this is executing in some kind of loop that you haven't shown us, but you are not using any conditional logic. What you seem to be getting is three separate statements:
// Always just evaluates to false and does nothing; the return value of
// getElementsByTagName() does not have a nodeName property
xmlDoc.getElementsByTagName("MODULE").getElementsByTagName("*").nodeName === "CAROUSEL"
{
// Always executes - simply a statement inside some curly braces
$("#module" + module_element_idcounter).append("...");
}
// Empty statement - does nothing
;
To get it to work the way you want it to, you probably need to use an if statement somewhere, but in order for us to help you, you need to show us more of your code than the tiny sampling you have provided.

New to javascript but my function works wrong in firefox

I'm just getting into javascript and so far enjoying the logic behind it but i have an issue with Firefox. basicly im generating my javascript from within a php function and its a NON SECURE pin code auth script.
So my php creates a call that passes variables pin number included, when called a modal popup with pinpad opens and the user inputs 4 digits, the pinpad onclick function adds the digits into a password field and after 4 clicks it compares it to a hidden field on the pinpad form, if it matches it calls another generated function to complete the success action, if no match pinpad frame turns red and a bypass button is enabled or they can try again.
This all works fine in Chrome, Opera and even IE but in Firefox it calls the success function after 4 digits even if they don't match the pin field.
Why could this be? Below is the function, but please remember I'm new so it could possibly be better written.
function add(text) {
var TheTextBox = document.pinform.elements['pin'];
var pincheckbox = document.pinform.elements['pincheck'];
var sidbox = document.pinform.elements['sid'];
TheTextBox.value = TheTextBox.value + text;
if (TheTextBox.value.length == 4) {
if (pinform.pin.value == pinform.pincheck.value) {
var pinn = document.getElementById('sid').value;
eval('pinpass' + pinn + '();');
} else {
document.getElementById("bypass").innerHTML = "Bypass";
document.getElementById("bypass").disabled = false;
document.getElementById("calc").style.backgroundColor = 'red';
TheTextBox.value = '';
return false;
}
}
}
Found the answer by trial and error as usual lol.
i need to add document. in front of pinform.pincheck.value and pinform.pin.value
Thanks for the help offered.
Nick
if (TheTextBox.value.length == 4) {
if (doucment.pinform.pin.value == document.pinform.pincheck.value) {
var pinn = document.getElementById('sid').value;
eval('pinpass' + pinn + '();');
} else {

Categories