JQuery html() does not work with css - javascript

I am developing an application, and I need to parse JSON and display it. I used the getJSON() function, which is working fine, and I'm using $(class_name).html(text). When I view the isolated HTML file in the browser, minus the CSS formatting, I can see the text, but when I run the application, and navigate to the page, the text (with the CSS formatting) does not show up. Even when I Inspect the element, the text is not present in it. Why is this happening?
Thank you
What console.log(data); contains:
schools:"Schools"
search-school:"Search school by number or name"
student-det:"Student Details"
students:"Students"
summary:"Summary"
The actual JSON:
{
"schools":"Schools",
"search-school":"Search school by number or name",
"student-det":"Student Details",
"students":"Students",
"summary":"Summary"
}
$.getJSON("./lang/en.json", function(data) {
$(".SecondTopBarTitleProperties").html(data.schools);
});
.SecondTopBarProperties
{
background-color:#333333;
height:40px;
}
.SecondTopBarTitleProperties
{
color:white;
font-size:16px;
margin-top:6px;
margin-left:6px;
font-family: Helvetica;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container SecondTopBarProperties">
<label class="SecondTopBarTitleProperties"></label>
<button data-bind="click:NewSchool" type="button" class=" pull-right btn btn-primary btn-default btn-sm" style="margin-right: 10px;margin-top: 2px; margin-bottom: 2px;">Add School</button>
</div>
Before the "Add School" button, it's supposed to display "Schools".
Plain HTML:
Formatted:
Any help please?

you need to include your styles into your html code i prepared this fiddle
https://jsfiddle.net/vmf3e3mf/4/
$(function(){
var data = { name = "hey" }
$('.SecondTopBarTitleProperties').html('<span style="color:red">'+data.name+'</span>')
})

You need to wait with the execution of your JS until the DOM is ready, else your JS can't manipulate the DOM elements, because they do not yet exist.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$( document ).ready(function() {
// Code inside this block will be executed when the DOM is ready
var data = {
schools: "Schools"
};
$(".SecondTopBarTitleProperties").html(data.schools);
}); // DOM ready
</script>
<div class="container SecondTopBarProperties">
<label class="SecondTopBarTitleProperties">
</label>
<button data-bind="click:NewSchool" type="button" class=" pull-right btn btn-primary btn-default btn-sm" style="margin-right: 10px;margin-top: 2px; margin-bottom: 2px;">Add School</button>
</div>
If this does not work for you, then you need to check what your $.getJSON("./lang / en.json ", function(data) { does, because we can't test this part for you.
Maybe it's due to copy&paste, but it should probably read $.getJSON("./lang/en.json", function(data) { without those spaces.
Check your browser's Network tab (in the browser's console) to see what you're requesting from the server and what the server returns.

I've tried this in w3schools and it works fine.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var data = { name :"hey" };
alert('hi');
$('.SecondTopBarTitleProperties').html(data.name);
});
</script>
</head>
<body>
<div class="container SecondTopBarProperties">
<label class="SecondTopBarTitleProperties"></label>
<button data-bind="click:NewSchool" type="button" class=" pull-right btn btn-primary btn-default btn-sm" style="margin-right: 10px;margin-top: 2px; margin-bottom: 2px;">Add School</button></div>
</body>
</html>

Related

JQuery .autocomplete not found?

I am trying to give my search bar autocomplete function.
$(function() {
var availableTags = [{
"game1": "title1"
},
{
"game2": "title2"
},
{
"game3": "title3"
},
];
$("#choices-text-preset-values").autocomplete({
source: availableTags
});
});
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<form method="GET" action="{% url 'search_results' %}" style="display: inline; background-color: transparent;" method="get">
<div id="search_bar" class="row" style="margin-top: 0px; text-align: center;">
<input name="q" class="sb-pos" id="choices-text-preset-values" type="text" placeholder="Aramak istediğiniz oyunu yazın! " style="padding-left: 30px;" />
<button type="submit" style="background-color: transparent; border: none;" class="sb-icon-pos">
<i class="fa fa-search" style="color: black; font-size: x-large;"></i>
</button>
</div>
</form>
I am getting this error:
TypeError: $( "#choices-text-preset-values" ).autocomplete is not a function. (In '$( "#choices-text-preset-values" ).autocomplete({
source: ['deneme','deneme2']
})', '$( "#choices-text-preset-values" ).autocomplete' is undefined)
The jQuery (or any javascript API in general) API might not be found for a various number of reasons.
Usually the problem is caused by the jQuery javascript code not being loaded at the moment your script executes. This can be due to a various number of reasons:
An adblocker might have blocked the jQuery javascript file
The jQuery javascript file is hosted on a CDN / other server that is offline
You loaded jQuery, but forgot to include jQuery UI (autocomplete is part of jQuery UI!)
Your code was executed before jQuery was loaded.
This can be caused because your <script>$(document).ready(/*whatever*/);</script> code is located before the <script src="/path/to/jquery.js"></script> block, or alternately because you mistakenly made the jquery script tag async. So, make sure that:
the jQuery script tag is located before your script and
it is not marked as async.

document.getElementById() not working as intended with multiple ids

I have an issue with document.getElementById(). Basically I have different forms each one with a different id and I'm using a bit of Javascript to replace some classes and add dinamically file name after upload.
That should be really easy, but I don't know why even if the ids are totally unique I get a weird behavior: whatever is the form in which I submit a file javascript will apply changes always on the first of them.
function spinnerLoad(){
document.getElementById('file-name[[${id}]]').textContent = this.files[0].name;
document.getElementById('spinner[[${id}]]').classList.replace('fas', 'spinner-border');
document.getElementById('spinner[[${id}]]').classList.replace('fa-file-upload', 'spinner-border-sm');
document.getElementById('uploadForm[[${id}]]').submit()
}
/*I'm using Bootstrap for my styling rules*/
/*${id} variable is server-side and it's there to make unique each form, I'm using Thymeleaf template engine*/
<form th:id="'uploadForm'+${id}" method="post" enctype="multipart/form-data" th:action="#{/upload/{id} (id=${id})}">
<label for="file-upload" class="btn btn-outline-success">
<span th:id="'spinner'+${id}" class="fas fa-file-upload"></span> <b>Upload file:</b> <i th:id="'file-name'+${id}">No file selected</i>
</label>
<input id="file-upload" type="file" name="multipartFile" accept="application/pdf" style="display: none" th:onchange="spinnerLoad()"/>
</form>
I googled the problem but I didn't manage to find a specific answer to my issue, so that's why I'm here bothering you.
I hope someone can help my figure this out, thank you.
You get a lot of repeating code and that can be hard to maintain. Here I placed the event listener on the the parent <div> to all the buttons. Then I need to test if is a button. And there is no need for an id for each button.
Actually, if you are just replacing a class name you don't even need to do the test (if()), because replace() will only do the replacement when the old value is present. This should be fine:
buttons.addEventListener('click', e => {
e.target.classList.replace('btn-success', 'btn-danger');
});
But here is the full example with the test:
var buttons = document.getElementById('buttons');
buttons.addEventListener('click', e => {
if (e.target.nodeName == 'BUTTON') {
e.target.classList.replace('btn-success', 'btn-danger');
}
});
.btn-success {
background-color: green;
}
.btn-danger {
background-color: red;
}
<div id="buttons">
<button class="btn-success">Button 1</button>
<button class="btn-success">Button 2</button>
<button class="btn-success">Button 3</button>
</div>
You're missing the css that would make this work, but otherwise your example is functional. However, it can be done more simply by working on the buttons as a class instead of individually.
var btns = document.getElementsByClassName("btn");
var addDanger = function(){
this.classList.replace('btn-success', 'btn-danger')
};
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', addDanger, false);
};
.btn {height:20px; width: 50px;}
.btn-success {background-color:green}
.btn-danger {background-color:red}
<button id="btn1" class="btn btn-success"></button>
<button id="btn2" class="btn btn-success"></button>
<button id="btn3" class="btn btn-success"></button>

How can I show/hide a bootstrap spinner with jQuery?

I'm trying to show a bootstrap spinner after a click on a button and then hide it after getting a response from an API (basically a loading status).
My button is as follow:
<div class="col-6">
<button type="button" name="btn-enviar" class="btn btn-primary w-100">
<span class="spinner-border spinner-border-sm mr-3" id="spinner" role="status" aria-hidden="true">
</span>Enviar</button>
</div>
So far I've tried to comment/uncomment my span tag with no luck, there would be an easier way to start/stop my spinner?
My comment/uncomment functions which I took from here and are not working (as requested):
function comment(element) {
element.html('<!--' + element.html() + '-->')
}
function uncomment(element) {
element.html(element.html().substring(4, element.html().length - 3))
}
Html (with added class .spinner):
<div class="col-6">
<button type="button" name="btn-enviar" class="btn btn-primary w-100">
<span class="spinner spinner-border spinner-border-sm mr-3" id="spinner" role="status" aria-hidden="true">
</span>Enviar</button>
</div>
Add css to css-file:
#spinner { display:none; }
body.busy .spinner { display:block !important; }
Or use visibility:
#spinner { visibility:hidden; }
body.busy .spinner { visibility:visible !important; }
JQuery:
$(document).ready( function()
{
$('#spinner').on('click', function()
{
$('body').addClass('busy');
});
});
When done, do:
$('body').removeClass('busy');
With a class like 'busy' added to the body of the html page, you can also do very nice things like blocking input elements and such without extra js code. Let CSS do all the work for you instead of js. You only have to add some extra CSS rules.
PS: Check your html for errors with html validator. If there are errors in the markup, strange things might happen or it doesn't work.
Have fun.
There are animation and -webkit-animation css attributes on the element.
Use a class like this
.stop {
animation-name: none !important;
-webkit-animation-name: none !important;
}
With JQuery you can toggle this class on the element. If it is added, the animation will stop.
Update
This will show then hide the spinner.
$(() => {
$('button').on('click', e => {
let spinner = $(e.currentTarget).find('span')
spinner.removeClass('d-none')
setTimeout(_ => spinner.addClass('d-none'), 2000)
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://getbootstrap.com/docs/4.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="canonical" href="https://getbootstrap.com/docs/4.3/components/spinners/">
<button class="btn btn-primary" type="button">
<span class="d-none spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
Click me...
</button>
I just faced the same problem and solved it with visibility style attribute.
HTML:
<span class="spinner-border spinner-border-sm" id="spinner" style="visibility: hidden"></span>
JS:
let spinner = document.getElementById("spinner");
spinner.style.visibility = 'visible'; //'hidden'
I didn't get your code exactly but I am putting my idea, you can try if feasible.
$(document).ready(function() {
$("#spinner").spinner({
start: function(event, ui) {
$('#d1').html("Spinner has started ");
},
stop: function(event, ui) {
$('#d1').html("Spinner has stopped ");
}
});
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/blitzer/jquery-ui.css" rel="stylesheet">
<input id="spinner" class='selector' value=12 size=3>
<div id=d1></div>

1 Form, 2 Divs, JQuery not working

I have a form that contains 2 divs, and in each div is an input, and when I press the buttons associated with each input, nothing happens and I believe it has something to do with the divs in the form. I know this code works when there wasn't the 2 divs, but I need to the divs so I can have the layout the way it is. Any suggestions?
I know I'd forgotten to add JQuery to this post, it was my mistake, but even with JQuery added it wasn't working in my project, in which this code is based.
Live code: https://jsfiddle.net/1brk3npL/
$(document).ready(function() {
$('#addLikes').click(function() {
if ($('#likes').val() === "") {
alert("Likes input is empty.");
} else {
$('#likesOutput').append($("<option></option>")
.attr("value", $('#likes').val()).text($('#likes').val()));
}
});
$('#removeLikes').click(function() {
$('#likesOutput option:selected').remove();
});
$('#addDislikes').click(function() {
if ($('#dislikes').val() === "") {
alert("Dislikes input is empty.");
} else {
$('#dislikesOutput').append($("<option></option>")
.attr("value", $('#dislikes').val()).text($('#dislikes').val()));
}
});
$('#removeDislikes').click(function() {
$('#dislikesOutput option:selected').remove();
});
});
select {
width: 250px;
}
input[type=text] {
font-family: "ProximaRegular", sans-serif;
width: 250px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="preferenceDiv">
<form id="preferenceInput">
<div style="float:left; position:relative; width : 50%;">
Likes:
<br/>
<input type="text" id="likes" />
<br />
<button id="addLikes" type="button">Add Likes</button>
<button id="removeLikes" type="button">Remove Likes</button>
<br />Selected Likes:
<br />
<select id="likesOutput" multiple="multiple"></select>
</div>
<div style="float:left; position:relative; width : 50%;">
Dislikes:
<br/>
<input type="text" id="dislikes" />
<br />
<button id="addDislikes" type="button">Add Dislikes</button>
<button id="removeDislikes" type="button">Remove Dislikes</button>
<br />Selected Dislikes:
<br />
<select id="dislikesOutput" multiple="multiple"></select>
</div>
</form>
</div>
Ok, so the code started working as intended yesturday. I don't know what happened, I didn't change the code in anyway. But one minute it wasn't working, then suddenly it was.
Add jQuery and also add $ reference to jQuery.
Chnage the first line of the JS like this
jQuery(document).ready(function ($) {
Even if you include jQuery there is reference missing. PLease change it and it'll work.
Just Add below jquery library in this https://jsfiddle.net/1brk3npL/ HTML part and see it's working :)
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Thanks
jQuery is not defined.
I just added jQuery on your jsfiddle and your code works.
Click on Javascript options -> FRAMEWORKS & EXTENSIONS -> Select jQuery version - > Click On Run

how to make visible a div which is initially hidden by clicking on button using javascript

I want that my hidden div will be visible continuously after clicking the button.
This is my js code:
document.getElementById("share").onclick=function show(){
document.getElementById("taskdiv2").style.visibility='visible';
};
This is my html code:
<a id="share" onclick="show()" type="button" class="btn btn-lg btn-default" href="">Share</a>
<div id="taskdiv2" style="visibility:hidden" class="row">
hiiiii !this is vivek.
</div>
You have used an anchor tag, so it tries to go to a link unless you prevent default:
document.getElementById("share").onclick=function show(event){
event.preventDefault();
document.getElementById("taskdiv2").style.visibility='visible';
};
Alternatively changing your html anchor to a button will also do the trick, in which case above change is not required:
<button id="share" onclick="show()" type="button" class="btn btn-lg btn-default" href="">Share</button>
It's best to do this using classes as mentioned in above answer by Rayon, if you are going for a better standard of coding. Though based on your requirement I would just add the class to your element, rather than toggle.
Remove inline onclick attribute as you have registered event using JavaScript
Add event.preventDefault() as default behavior of <a> elements is to navigate.
document.getElementById("share").onclick = function(e) {
e.preventDefault();
document.getElementById("taskdiv2").style.visibility = 'visible';
};
<a id="share" type="button" class="btn btn-lg btn-default" href="">Share</a>
<div id="taskdiv2" style="visibility:hidden" class="row">
hiiiii !this is vivek.
</div>
If you are expecting toggle of visibility,
Use Element.classList.toggle
document.getElementById("share").onclick = function show() {
document.getElementById("taskdiv2").classList.toggle('show');
};
.show {
visibility: hidden;
}
<div id="taskdiv2">Content Goes Here!!!</div>
<button id="share">Toggle</button>
function becomevisible() {
document.getElementById("div").style.opacity="1";
}
div {
background:red;
height: 100px;
width: 100px;
opacity: 0;
}
<div id="div">Test</div>
<button onclick="becomevisible()">See the div!</button>
try this one out :
document.getElementById("share").onclick = function show() {
document.getElementById("taskdiv2").classList.toggle('show');
};
.show {
visibility: hidden;
}
<div id="taskdiv2">Content Goes Here!!!</div>
<button id="share">Toggle</button>

Categories