Unable to update element ID of HTML text using Javascript Jquery [duplicate] - javascript

This question already has answers here:
jquery executes too fast
(2 answers)
Closed 1 year ago.
Using JS and AJAX, I am loading a template file on my Index.html page.
Once the template is loaded, I then want to apply changes to the DOM.
The template is successfully loading on the index.html page.
The JS is FAILING to update the DOM elements.
What am I doing wrong?
I have 2 html pages.
index.html
page-banner-area.html
index.html
<div id="page-banner-area"></div>
<script>
$(function(){
$("#page-banner-area").load("assets/static_html/page-banner-area.html");
$("#title").text('Join a Community Group in your area.');
$("#keypoint-1").text('We are against mandatory vaccines & passports.');
$("#keypoint-2").text('We do not stand for corruption & censorship.');
$("#keypoint-3").text('We believe in freedom!');
});
</script>
page-banner-area.html
<div class="p-2 flex-grow-1">
<h3><span id="title"></span></h3>
<span id="keypoint-1"></span><br />
<span id="keypoint-2"></span><br />
<span id="keypoint-3"></span>
</div>

The problem is that the load() method is asynchronous, you need to do your changes within a callback method in order for them to be properly applied. See the JQuery docs for more information https://api.jquery.com/load/
As for a solution, you should be doing this instead:
$(function(){
$("#page-banner-area").load("assets/static_html/page-banner-area.html", function() {
$("#title").text('Join a Community Group in your area.');
$("#keypoint-1").text('We are against mandatory vaccines & passports.');
$("#keypoint-2").text('We do not stand for corruption & censorship.');
$("#keypoint-3").text('We believe in freedom!');
});
});

I thinks this can solve your problem!
<div id="page-banner-area"></div>
<script>
$(() => {
$("#page-banner-area")
.load("assets/static_html/page-banner-area.html", () => {
$("#title").text('Join a Community Group in your area.');
$("#keypoint-1").text('We are against mandatory vaccines & passports.');
$("#keypoint-2").text('We do not stand for corruption & censorship.');
$("#keypoint-3").text('We believe in freedom!');
});
});
</script>

Related

How do I have a function find two elements? [duplicate]

This question already has answers here:
Can you do an 'AND' on a jQuery selector to target multiple buttons?
(3 answers)
Closed 4 months ago.
I'm a beginner with JavaScript so I'm sure this will be an elementary question.
With this function below, I want it to find the two elements and add them to a header element. Right now, the only thing that is working is the element, the link with the rel:author tag. I'm sure this is probably a syntax thing.
(function($) {
$(document).ready(function() {
$(".single .single-post-module").each(function() {
$(this).find('a[rel="author"]', 'span[class="updated"]').clone().appendTo($(this).find('.post-header h1'));
// ^^^
});
});
})(jQuery)
Edit: I'm using Divi on wordpress and the site is in maintenance mode. That's why didn't show the HTML or give a link.
This could be done with pure Javscript querySelectorAll with an CSS selector that will find both elements.
To clone the element, use cloneNode(true) where the first parameter indicates to clone 'deep'
const header = document.querySelector('.post-header > h1');
const elements = document.querySelectorAll('.single, .single-post-module');
Array.from(elements).forEach(e => header.append(e.cloneNode(true)));
<div class='single'>
<a rel='author'>Link</a>
<span class='updated'>Span</span>
</div>
<div class='single-post-module'>
<a rel='author'>Link</a>
<span class='updated'>Span</span>
</div>
<div class='post-header'>
<h1></h1>
</div>

Why does JQuery .val() method sometimes return undefined when code is valid? [duplicate]

This question already has answers here:
val() vs. text() for textarea
(2 answers)
Closed 4 years ago.
Not a duplicate question; so please consider the content closely before presumption.
I've been using JQuery for years and have never seen this type of behavior before. Consider the following:
<html>
<div class="order-form-group">
<label class="order-form-label" for="guestSpecialInstructions">Special Instructions:</label>
<textarea class="order-form-textarea" id="guestSpecialInstructions" type="text"></textarea>
</div>
<div class="order-form-group">
<label class="order-form-label" for="guestReason">Reason:</label>
<textarea class="order-form-textarea" id="guestReason" type="text"></textarea>
</div>
<div class="button-container">
<input class="order-form-submit" type="submit" value="Submit">
</div>
</html>
I've observed that the following script in some instances will return 'undefined' even when "all" the more obvious reasons have been eliminated. Such as
having the incorrect selector, having more than 1 id on the page and etc.
<script>
var specInstr = $("#guestSpecialInstructions").val();
var guestReason = $("#guestReason").val();
</script>
I spent literally hours attempting to determine what the disconnect was; stripping my code to the simplest basic level and couldn't find any reasonable explanation for the behavior.
The code is contained within a simple HTML page; nothing fancy and references the JQuery repository https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
I have another project which runs in an aspx page, still the markup is identical and the .val() method works without issue.
After hours of hitting a wall I ran across the post at JQuery: .val() is not working for textarea and someone else attesting to the exact same issue using valid code and the suggestion was:
<script>
var specInstr = $("#guestSpecialInstructions")[0].value;
var guestReason = $("#guestReason")[0].value;
</script>
Then the issue is automagically resolved. Only problem I have with this is that there no one seems to have answered the question of why the JQuery .text() method sometimes return undefined when all aspects of the code is valid.
Resolutions are great but without understanding why the issue exists, really gains nothing intellectually.
If I need to change the wording of the title, let me know.
You can only use text() on a <textarea> if it is pre-populated and to return the original content
Any changes to the content by user or setting new value programatically will not alter what is returned by text() as it will always be the original pre-pre-populated content
Always use val() to get and set
var $txt = $('textarea')
console.log('text() Original content:', $txt.text())
console.log('val() Original content:', $txt.val())
$txt.val( 'Some new content')
console.log('text() after value change:', $txt.text())
console.log('val() after value change:', $txt.val())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="one" type="text">
Original text
</textarea>

Injecting <br/> tag form a Json file is not working on an Angular page [duplicate]

This question already has answers here:
Angular HTML binding
(24 answers)
Closed 4 years ago.
I am trying to get the Line Break element working on my Angular page, injecting it form my Json file, with not luck.
I had a look to the following question: SO similar question but I think I have got a different scenario.
My scenario:
JSON FILE
{
"boxLeft": {
"boxLeftHeaderDesktop": "HOURS PER <br/> WEEK",
}
}
ANGULAR:
Angular version: 1.4.9
<div class="header">
{{boxLeft.boxLeftHeaderDesktop}}
</div>`
RESULT - rong
HOURS PER <br/> WEEK
WHAT I HAVE TRIED:
1: {{locale.earnings.boxLeftHeaderDesktop | raw}} - not working
2: <br \/> - not working
3: <div class="header">
<div [innerHTML]="boxLeft.boxLeftHeaderDesktop"></div>
</div> - not working
Please, is there any other solution which I could try to use?
HOW I HAVE SOLVED IT:
using: angular-sanitize.js
use the innerHTML to render the html tags
<div class="header">
<div [innerHTML]="boxLef.boxLeftHeaderDesktop"></div>
</div>

document.getElementbyId() returning null [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 6 years ago.
In the code at the line marked as //Error in comments. I get Javascript error saying: "Cannot read property style of 'null'". I have no idea what it is not able to find the object. I have thought and tried everything. Please help. Here is the code:
<script type="text/javascript">
$.getJSON('https://graph.facebook.com/647045111?fields=first_name&<%= Session["Token"] %>',
function (data) {
$('#userName').html(data.first_name);
});
document.getElementById('connectedUnregistered').style.display = 'block'; //Error
</script>
<div id="userName"></div>
<div id="disconnected" style="display:block;">
<div id="heading">Facebook login</div>
<div id="fbConnectButton"><img src="/Content/Images/fbconnect.png"/></div>
</div>
<div id="connectedUnregistered" style="display:none">
<div id="heading">Register Now</div>
</div>
You are executing your javascript code BEFORE the <div id="connectedUnregistered" /> was actually created.
Also note that you did not close your <div> with a corresponding </div>.
So move your javascript code to a part below your HTML. Or execute it after the page finished loading. If you are using JQuery you can do:
<script>
$(document).ready(function() {
... your code ...
});
</script>
Put your script at the end of the HTML document instead of the beginning, and see if that solves things.
JavaScript can't edit the DOM element because it hasn't been created yet.
Perhaps try placing this code in a
$(document).ready(function(){
//Code
});
block
in my case it was because of having this line at the beginning of the jsp/html(whatever) file:
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
removing it solved the problem for me(I do not remember what it was doing on my page at first place)
Also, if in some part of the code you are using document.write it's very common to get null.
The script is trying to get the element before the element is loaded. Place the script after the element or put it in a load or ready event.
The code executes prior to the element being created. Since you are using jquery, simply wrap it in document.ready:
$(function(){
// code goes here
});
This will execute after the DOM is created.
The javascript code is running before the DOM is fully available and the call fails. Try the following instead
$(document).ready(function() {
document.getElementById('connectedUnregistered').style.display = 'block'; //Error
}
This error could also indicate that the element doesn't have an ID.
<input type="text" name="myelem" />
Make sure your element has an ID.
<input type="text" name="myelem" id="myelem" />

How to auto-translate a section using google translate tools?

This is more like a auto-click link problem. But my problem is this link is generate by google's script.
http://translate.google.com/translate_tools
If you choose "translate a section" , there will be a link generate inside the goog-trans-control class
Original script:
<div class="goog-trans-section">
<div class="goog-trans-control">
</div>
Original Text here.
</div>
Script code after execute (Check Component):
<div class="goog-trans-section">
<div class="goog-trans-control">
<div class="skiptranslate goog-te-sectional-gadget-link" style="">
<div id=":1.gadgetLink">
<a class="goog-te-gadget-link" href="javascript:void(0)">
<span class="goog-te-sectional-gadget-link-text">Translate</span>
</a>
</div>
</div>
</div>
Original Text here.
</div>
How would I auto-click (or execute) the Translate link after this page is totally loaded?
For some reason, jsfiddle is not working with my script, though I still post this for your convenience.
http://jsfiddle.net/Wb7tE/
Really appreciate for your time and help.
Edited:
I tried Google translate API, but there is a limitation of 5000 words at a time.
My translations include whole html with tables and scripts, so it reach the limit with no exception.
I have a similar problem, and I solved it temporally like this
google_initialized = false;
function google_auto_translate()
{
if(google_initialized)
{
$('a.goog-te-gadget-link')[0].click();
}
else if(google.translate)
{
google_initialized = true;
setTimeout(google_auto_translate, 500);
}
else
setTimeout(google_auto_translate, 100);
}
window.onload = google_auto_translate;
but on slower connection, in 50 % of time google doesn't load on time, and script already clicks before loading is done. So if anyone know any other way to do this, via some events or something similar please add it here...
P.S. Don't use Google Translation API it's Deprecated and will be removed till the end of this year.

Categories